Esempio n. 1
0
 def checkPluginUpdatesAvailable(self):
     """
     Public method to check the availability of updates of plug-ins.
     """
     period = Preferences.getPluginManager("UpdatesCheckInterval")
     if period == 0:
         return
     elif period in [1, 2, 3]:
         lastModified = QFileInfo(self.pluginRepositoryFile).lastModified()
         if lastModified.isValid() and lastModified.date().isValid():
             lastModifiedDate = lastModified.date()
             now = QDate.currentDate()
             if period == 1 and lastModifiedDate.day() == now.day():
                 # daily
                 return
             elif period == 2 and lastModifiedDate.daysTo(now) < 7:
                 # weekly
                 return
             elif period == 3 and \
                 (lastModifiedDate.daysTo(now) <
                  lastModifiedDate.daysInMonth()):
                 # monthly
                 return
     
     self.__updateAvailable = False
     
     request = QNetworkRequest(
         QUrl(Preferences.getUI("PluginRepositoryUrl6")))
     request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                          QNetworkRequest.AlwaysNetwork)
     reply = self.__networkManager.get(request)
     reply.finished.connect(self.__downloadRepositoryFileDone)
     self.__replies.append(reply)
Esempio n. 2
0
    def downloadFile(self):
        self.url = QUrl(self.urlLineEdit.text())
        fileInfo = QFileInfo(self.url.path())
        fileName = fileInfo.fileName()

        if not fileName:
            fileName = 'index.html'

        if QFile.exists(fileName):
            ret = QMessageBox.question(self, "HTTP",
                    "There already exists a file called %s in the current "
                    "directory. Overwrite?" % fileName,
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

            if ret == QMessageBox.No:
                return

            QFile.remove(fileName)

        self.outFile = QFile(fileName)
        if not self.outFile.open(QIODevice.WriteOnly):
            QMessageBox.information(self, "HTTP",
                    "Unable to save the file %s: %s." % (fileName, self.outFile.errorString()))
            self.outFile = None
            return

        self.progressDialog.setWindowTitle("HTTP")
        self.progressDialog.setLabelText("Downloading %s." % fileName)
        self.downloadButton.setEnabled(False)

        self.httpRequestAborted = False
        self.startRequest(self.url)
Esempio n. 3
0
 def __saveFileName(self, directory):
     """
     Private method to calculate a name for the file to download.
     
     @param directory name of the directory to store the file into (string)
     @return proposed filename and original filename (string, string)
     """
     path = parseContentDisposition(self.__reply)
     info = QFileInfo(path)
     baseName = info.completeBaseName()
     endName = info.suffix()
     
     origName = baseName
     if endName:
         origName += '.' + endName
     
     name = directory + baseName
     if endName:
         name += '.' + endName
         if not self.__requestFilename:
             # do not overwrite, if the user is not being asked
             i = 1
             while QFile.exists(name):
                 # file exists already, don't overwrite
                 name = directory + baseName + ('-{0:d}'.format(i))
                 if endName:
                     name += '.' + endName
                 i += 1
     return name, origName
Esempio n. 4
0
    def outputFiles(self, map, fileName):
        result = []

        # Extract file name without extension and path
        fileInfo = QFileInfo(fileName)
        base = fileInfo.completeBaseName() + "_"
        path = fileInfo.path()

        # Loop layers to calculate the path for the exported file
        for layer in map.layers():
            if layer.layerType() != Layer.TileLayerType:
                continue

            # Get the output file name for this layer
            layerName = layer.name()
            layerFileName = base + layerName + ".csv"
            layerFilePath = QDir(path).filePath(layerFileName)

            result.append(layerFilePath)

        # If there was only one tile layer, there's no need to change the name
        # (also keeps behavior backwards compatible)
        if len(result) == 1:
            result[0] = fileName

        return result
Esempio n. 5
0
 def __open(self):
     """
     Private slot to open the downloaded file.
     """
     info = QFileInfo(self.__output)
     url = QUrl.fromLocalFile(info.absoluteFilePath())
     QDesktopServices.openUrl(url)
Esempio n. 6
0
 def restoreDir(self):
     "用户点击了“默认运行目录”按钮。"
     path = self.txtPath.text().strip()
     fi = QFileInfo(path)
     if path == "" or not fi.exists():
         return
     self.txtDir.setText(fi.dir().absolutePath())
Esempio n. 7
0
 def __insertFlashCookie(self, path):
     """
     Private method to insert a Flash cookie into the cache.
     
     @param path Flash cookies path
     @type str
     """
     solFile = QFile(path)
     if not solFile.open(QFile.ReadOnly):
         return
     
     dataStr = ""
     data = bytes(solFile.readAll())
     if data:
         try:
             reader = FlashCookieReader()
             reader.setBytes(data)
             reader.parse()
             dataStr = reader.toString()
         except FlashCookieReaderError as err:
             dataStr = err.msg
     
     solFileInfo = QFileInfo(solFile)
     
     cookie = FlashCookie()
     cookie.contents = dataStr
     cookie.name = solFileInfo.fileName()
     cookie.path = solFileInfo.canonicalPath()
     cookie.size = int(solFile.size())
     cookie.lastModified = solFileInfo.lastModified()
     cookie.origin = self.__extractOriginFrom(path)
     
     self.__flashCookies.append(cookie)
Esempio n. 8
0
 def openFolder(self):
     """
     Public slot to open the folder containing the downloaded file.
     """
     info = QFileInfo(self.__fileName)
     url = QUrl.fromLocalFile(info.absolutePath())
     QDesktopServices.openUrl(url)
Esempio n. 9
0
    def _addIcon(self):
        filter_ = self.tr("Images (*.jpg *.jpeg *.bmp *.png *.tiff *.gif);;"
                          "All files (*.*)")
        fileName, _selectedFilter = QFileDialog.getOpenFileName(self,
                self.tr("Open File"), self.latestDir,
                filter_)
        if fileName:
            file_info = QFileInfo(fileName)
            self.latestDir = file_info.absolutePath()

            image = QImage()
            if image.load(fileName):
                maxWidth = 22
                maxHeight = 15
                if image.width() > maxWidth or image.height() > maxHeight:
                    scaledImage = image.scaled(maxWidth, maxHeight,
                            Qt.KeepAspectRatio, Qt.SmoothTransformation)
                else:
                    scaledImage = image

                ba = QByteArray()
                buffer = QBuffer(ba)
                buffer.open(QIODevice.WriteOnly)
                scaledImage.save(buffer, 'png')

                model = self.model()
                index = model.index(self.selectedIndex().row(), model.fieldIndex('icon'))
                model.setData(index, ba)
Esempio n. 10
0
    def open(self, file_name):
        """Open the file at the given path for reading.

        Args:
            file_name (str): File path of the file to open. Only .wav files
                permitted.

        Raises:
            FileNotFoundError: If the filename given cannot be opened.
        """
        if file_name is not None:
            file_info = QFileInfo(file_name)
            if file_info.exists():
                self.file_name = file_name
                # Update the waveform data
                wave_read = wave.open(file_name, 'r')
                self.waveform_info = wave_read.getparams()
                step = int(self.waveform_info.framerate / self.stored_fps)
                self.waveform_data = list(bytesToInts(
                        data=wave_read.readframes(-1),
                        channelWidth=self.waveform_info.sampwidth,
                        numChannels=self.waveform_info.nchannels,
                        signed=True,
                        step=step))
                # Update the media player
                url = QUrl.fromLocalFile(file_info.absoluteFilePath())
                self.media_player.setMedia(QMediaContent(url))
                # Send out appropriate event
                self.signalFileChanged.emit()
                wave_read.close()
            else:
                raise FileNotFoundError('No file exists at given file path')
Esempio n. 11
0
    def __init__(self, ui_file, bus, devices=[], parent=None):
        QtWidgets.QMainWindow.__init__(self, parent=parent)

        self.bus = bus

        # TODO: CAMPid 980567566238416124867857834291346779
        ico_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), "icon.ico")
        ico = QtGui.QIcon(ico_file)
        self.setWindowIcon(ico)

        ui = ui_file
        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.ui.action_About.triggered.connect(self.about)

        device_tree = epyqlib.devicetree.Tree()
        device_tree_model = epyqlib.devicetree.Model(root=device_tree)
        device_tree_model.device_removed.connect(self._remove_device)
        self.ui.device_tree.setModel(device_tree_model)

        self.ui.device_tree.device_selected.connect(self.set_current_device)
Esempio n. 12
0
class FileBasedTextStream(QTextStream):
    def __init__(self, qfile):
        super().__init__(qfile)
        self.saved_file = qfile
        self.qfi = None # may never need this
    def rewind(self):
        self.flush()
        self.seek(0)
    def writeLine(self, str):
        self << str
        self << '\n'
    def open_mode(self):
        return self.saved_file.openMode()
    def fullpath(self):
        if self.qfi is None:
            self.qfi = QFileInfo(self.saved_file)
        return self.qfi.canonicalFilePath()
    def folderpath(self):
        if self.qfi is None:
            self.qfi = QFileInfo(self.saved_file)
        return self.qfi.canonicalPath()
    def filename(self):
        if self.qfi is None:
            self.qfi = QFileInfo(self.saved_file)
        return self.qfi.fileName()
    def basename(self):
        if self.qfi is None:
            self.qfi = QFileInfo(self.saved_file)
        return self.qfi.completeBaseName()
    def suffix(self):
        if self.qfi is None:
            self.qfi = QFileInfo(self.saved_file)
        return self.qfi.suffix()
Esempio n. 13
0
 def __init__(self, pluginManager, pluginFileNames, parent=None):
     """
     Constructor
     
     @param pluginManager reference to the plugin manager object
     @param pluginFileNames list of plugin files suggested for
         installation (list of strings)
     @param parent parent of this dialog (QWidget)
     """
     super(PluginInstallWidget, self).__init__(parent)
     self.setupUi(self)
     
     if pluginManager is None:
         # started as external plugin installer
         from .PluginManager import PluginManager
         self.__pluginManager = PluginManager(doLoadPlugins=False)
         self.__external = True
     else:
         self.__pluginManager = pluginManager
         self.__external = False
     
     self.__backButton = self.buttonBox.addButton(
         self.tr("< Back"), QDialogButtonBox.ActionRole)
     self.__nextButton = self.buttonBox.addButton(
         self.tr("Next >"), QDialogButtonBox.ActionRole)
     self.__finishButton = self.buttonBox.addButton(
         self.tr("Install"), QDialogButtonBox.ActionRole)
     
     self.__closeButton = self.buttonBox.button(QDialogButtonBox.Close)
     self.__cancelButton = self.buttonBox.button(QDialogButtonBox.Cancel)
     
     userDir = self.__pluginManager.getPluginDir("user")
     if userDir is not None:
         self.destinationCombo.addItem(
             self.tr("User plugins directory"),
             userDir)
     
     globalDir = self.__pluginManager.getPluginDir("global")
     if globalDir is not None and os.access(globalDir, os.W_OK):
         self.destinationCombo.addItem(
             self.tr("Global plugins directory"),
             globalDir)
     
     self.__installedDirs = []
     self.__installedFiles = []
     
     self.__restartNeeded = False
     
     downloadDir = QDir(Preferences.getPluginManager("DownloadPath"))
     for pluginFileName in pluginFileNames:
         fi = QFileInfo(pluginFileName)
         if fi.isRelative():
             pluginFileName = QFileInfo(
                 downloadDir, fi.fileName()).absoluteFilePath()
         self.archivesList.addItem(pluginFileName)
         self.archivesList.sortItems()
     
     self.__currentIndex = 0
     self.__selectPage()
Esempio n. 14
0
    def set_mode_by_filename(self, filename):
        file = QFile(filename)
        fileinfo = QFileInfo(file)

        suffix = fileinfo.suffix()
        self.page().mainFrame().evaluateJavaScript("editor.getSession().setMode('%s');" % (
            self.SUFIX_2_MODE[suffix] if suffix in self.SUFIX_2_MODE else self.SUFIX_2_MODE[None]
        ))
Esempio n. 15
0
    def onActivated(self, index):
        path = self.model().filePath(index)
        fileInfo = QFileInfo(path)
        if (fileInfo.isDir()):
            prefs = preferences.Preferences.instance()
            prefs.setMapsDirectory(fileInfo.canonicalFilePath())
            return

        self.mMainWindow.openFile(path)
Esempio n. 16
0
 def setFileIcon(self, path):
     "每当txtPath的值改变时,就设置快捷方式的图标"
     fi = QFileInfo(path)
     if not fi.exists():
         self.shortcutIcon = QIcon(":/images/unknown.png")
     else:
         ip = QFileIconProvider()
         self.shortcutIcon = ip.icon(fi)
     self.btnFace.setIcon(self.shortcutIcon)
Esempio n. 17
0
def _qfile_to_stream(a_file, I_or_O, encoding=None):
    if not a_file.open(I_or_O | QIODevice.Text) :
        f_info = QFileInfo(a_file) # for the name
        utilities_logger.error('Error {0} ({1}) opening file {2}'.format(
            a_file.error(), a_file.errorString(), f_info.fileName() ) )
        return None
    fbts = FileBasedTextStream(a_file)
    fbts.setCodec(_check_encoding(fbts.filename()) if encoding is None else encoding)
    return fbts
Esempio n. 18
0
    def findDocument(self, fileName):
        canonicalFilePath = QFileInfo(fileName).canonicalFilePath()
        if (canonicalFilePath==''): # file doesn't exist
            return -1
        for i in range(self.mDocuments.size()):
            fileInfo = QFileInfo(self.mDocuments.at(i).fileName())
            if (fileInfo.canonicalFilePath() == canonicalFilePath):
                return i

        return -1
class QuarkNotebookModel:
    """Subdirectories located in the Quark notes directory (defined by its path in
'config.json' under "notes_dir") are represented by this class in the Quark
note manager."""

    def __init__(self, dirPath):
        """Initialize data for the model."""

        self._notebookDir = QFileInfo(dirPath)  #store path to the notebook as a 'QFileInfo' for added flexibility
        q = QFileIconProvider()                 #objec used to create model display icon
        self._icon = q.icon(self._notebookDir)  #create model display icon
        self._notes = []                        #initialize empty list of notes

        notebookPath = self._notebookDir.absoluteFilePath() #get the absolute path to the notebook

        #load all the notes inside this notebook
        for item in sorted(os.listdir(notebookPath)):               #for every item in the notebook

            itemPath = os.path.join(notebookPath, item)         #get absolute path to the item

            if os.path.isfile(itemPath):                        #if the item is a file/note
                self._notes.append( QuarkNoteModel(itemPath, self) )    #append a new note to the notes list


    def noteAt(self, i):
        """Returns the note at a given index."""

        if i >= 0 and i < len(self._notes):
            return self._notes[i]
        else:
            return None


    def noteCount(self):
        """Returns the number notes inside this notebook."""

        return len(self._notes)


    def getName(self):
        """Returns the name of this notebook/directory."""

        return self._notebookDir.fileName()


    def getFilePath(self):
        """Returns path to the note."""

        return self._notebookDir.absoluteFilePath()


    def getIcon(self):
        """Returns the icon to be displayed in the Quark note manager."""

        return self._icon
Esempio n. 20
0
 def accept(self):
     if self.txtName.text().strip() == "":
         QMessageBox.information(self, self.windowTitle(),
                 self.tr("请填写快捷方式的名称。"))
         self.txtName.setFocus(Qt.OtherFocusReason)
         return
     path = self.txtPath.text().strip()
     if path == "":
         QMessageBox.information(self, self.windowTitle(),
                 self.tr("请填写目标文件/程序。"))
         self.txtPath.setFocus(Qt.OtherFocusReason)
         self.txtPath.selectAll()
         return
     if not os.path.exists(path):
         QMessageBox.information(self, self.windowTitle(),
                 self.tr("目标文件/程序不存在。"))
         self.txtPath.setFocus(Qt.OtherFocusReason)
         self.txtPath.selectAll()
         return
     openwith = self.txtOpenwith.text().strip()
     if openwith != "":
         if not os.path.exists(openwith):
             QMessageBox.information(self, self.windowTitle(),
                     self.tr("编辑程序不存在。请重新选择。该选项是选填项,并不一定要填写。"))
             self.txtOpenwith.setFocus(Qt.OtherFocusReason)
             self.txtOpenwith.selectAll()
             return
         fi = QFileInfo(openwith)
         if not fi.isExecutable():
             QMessageBox.information(self, self.windowTitle(),
                     self.tr("编辑程序必须是一个可执行文件。请重新选择。该选项是选填项,并不一定要填写。"))
             self.txtOpenwith.setFocus(Qt.OtherFocusReason)
             self.txtOpenwith.selectAll()
             return
     dir = self.txtDir.text().strip()
     if dir == "":
         QMessageBox.information(self, self.windowTitle(),
                 self.tr("请填写运行目录。可以使用“默认运行目录”按钮恢复默认的运行目录。"))
         self.txtDir.setFocus(Qt.OtherFocusReason)
         self.txtDir.selectAll()
         return
     if not os.path.exists(dir):
         QMessageBox.information(self, self.windowTitle(),
                 self.tr("运行目录不存在。请重新选择。可以使用“默认运行目录”按钮恢复默认的运行目录。"))
         self.txtDir.setFocus(Qt.OtherFocusReason)
         self.txtDir.selectAll()
         return
     if not os.path.isdir(dir):
         QMessageBox.information(self, self.windowTitle(),
                 self.tr("运行目录必须是一个目录,而非文件。请重新选择。可以使用“默认运行目录”按钮恢复默认的运行目录。"))
         self.txtDir.setFocus(Qt.OtherFocusReason)
         self.txtDir.selectAll()
         return
     QDialog.accept(self)
 def add_song(self, song_path):
     if song_path.split(".")[-1] not in ["mp3", "flac", "ogg"]:
         raise AssertionError
     song = self.path_to_song(song_path)
     filepath = song.path
     fileInfo = QFileInfo(filepath)
     if fileInfo.exists():
         url = QUrl.fromLocalFile(fileInfo.absoluteFilePath())
         if fileInfo.suffix().lower() == "mp3" or "flac" or "ogg":
             self.playlist.addMedia(QMediaContent(url))
             self.songs.append(song)
Esempio n. 22
0
def path_with_tilde_homepath(path):
    if IS_WINDOWS:
        return path
    home_path = QDir.homePath()
    fi = QFileInfo(QDir.cleanPath(path))
    outpath = fi.absoluteFilePath()
    if outpath.startswith(home_path):
        outpath = "~" + outpath[len(home_path):]
    else:
        outpath = path
    return outpath
    def _addIcon(self):
        filter_ = self.tr("Images (*.jpg *.jpeg *.bmp *.png *.tiff *.gif *.ico);;"
                          "All files (*.*)")
        fileName, _selectedFilter = QFileDialog.getOpenFileName(self,
                self.tr("Open File"), self.latestDir,
                filter_)
        if fileName:
            file_info = QFileInfo(fileName)
            self.latestDir = file_info.absolutePath()

            self.loadFromFile(fileName)
Esempio n. 24
0
    def destinationButtonClicked(self):
        destination = self.destination.text()
        if not destination and self.collection:
            destination = self.latestDir + '/' + self.collection.getCollectionName() + '_mobile.db'
        file, _selectedFilter = QFileDialog.getSaveFileName(
            self, self.tr("Select destination"), destination, "*.db")
        if file:
            file_info = QFileInfo(file)
            self.latestDir = file_info.absolutePath()

            self.destination.setText(file)
            self.acceptButton.setEnabled(True)
Esempio n. 25
0
def addShapeToCanvas( shapefile_path ):
    file_info = QFileInfo( shapefile_path )
    if file_info.exists():
        layer_name = file_info.completeBaseName()
    else:
        return False
    vlayer_new = QgsVectorLayer( shapefile_path, layer_name, "ogr" )
    if vlayer_new.isValid():
        QgsProject.instance().addMapLayers( [vlayer_new] )
        return True
    else:
        return False
Esempio n. 26
0
    def _fileinfo_from_user(self, user_path):
        """ Convert the name of a file or directory specified by the user to a
        QFileInfo instance.  A user path may be relative to the name of the
        project and may contain environment variables.
        """

        fi = QFileInfo(self.expandvars(user_path.strip()))

        if fi.isRelative() and self._name is not None:
            fi = QFileInfo(self._name.canonicalPath() + '/' + fi.filePath())

        return fi
Esempio n. 27
0
def ask_executable(caption, parent=None, starting_path=''):
    (chosen_path, _) = QFileDialog.getOpenFileName(
            parent,
            caption,
            starting_path,''
        )
    if len(chosen_path) == 0 : # user pressed Cancel
        return ''
    qfi = QFileInfo(chosen_path)
    if not qfi.isExecutable() :
        return None
    return chosen_path
Esempio n. 28
0
 def __saveMessages(self):
     """
     Private slot to save the contents of the messages display.
     """
     hasText = not self.messages.document().isEmpty()
     if hasText:
         if Utilities.isWindowsPlatform():
             htmlExtension = "htm"
         else:
             htmlExtension = "html"
         fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter(
             self,
             self.tr("Save Messages"),
             "",
             self.tr(
                 "HTML Files (*.{0});;Text Files (*.txt);;All Files (*)")
             .format(htmlExtension),
             None,
             E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
         if fname:
             ext = QFileInfo(fname).suffix()
             if not ext:
                 ex = selectedFilter.split("(*")[1].split(")")[0]
                 if ex:
                     fname += ex
                 ext = QFileInfo(fname).suffix()
             if QFileInfo(fname).exists():
                 res = E5MessageBox.yesNo(
                     self,
                     self.tr("Save Messages"),
                     self.tr("<p>The file <b>{0}</b> already exists."
                             " Overwrite it?</p>").format(fname),
                     icon=E5MessageBox.Warning)
                 if not res:
                     return
                 fname = Utilities.toNativeSeparators(fname)
             
             try:
                 if ext.lower() in ["htm", "html"]:
                     txt = self.messages.toHtml()
                 else:
                     txt = self.messages.toPlainText()
                 f = open(fname, "w", encoding="utf-8")
                 f.write(txt)
                 f.close()
             except IOError as err:
                 E5MessageBox.critical(
                     self,
                     self.tr("Error saving Messages"),
                     self.tr(
                         """<p>The messages contents could not be written"""
                         """ to <b>{0}</b></p><p>Reason: {1}</p>""")
                     .format(fname, str(err)))
Esempio n. 29
0
    def checkFiles(self, lst):
        f = QFileInfo()
        newLst = []
        for url in lst:
            _file = url.toLocalFile()
            print("FILE::", url, _file)
            f.setFile(_file)
            if f.suffix() not in ("tar", "exe", "mp3", "mp4", "flv", "zip", "rar", "iso"):
                newLst.append(_file)

        if newLst:
            self.openFiles.emit(newLst)
Esempio n. 30
0
	def getDocumentTitle(self, baseName=False):
		if self.markup and not baseName:
			text = self.editBox.toPlainText()
			try:
				return self.markup.get_document_title(text)
			except Exception:
				self.p.printError()
		if self.fileName:
			fileinfo = QFileInfo(self.fileName)
			basename = fileinfo.completeBaseName()
			return (basename if basename else fileinfo.fileName())
		return self.tr("New document")
Esempio n. 31
0
 def open(self):
     self.offerSave()
     path = (QFileInfo(self.filename).path() if self.filename else ".")
     fname, filetype = QFileDialog.getOpenFileName(
         self, "Page Designer - Open", path, "Page Designer Files (*.pgd)")
     if not fname:
         return
     self.filename = fname
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(str(fh.errorString()))
         items = self.scene.items()
         while items:
             item = items.pop()
             self.scene.removeItem(item)
             del item
         self.addBorders()
         stream = QDataStream(fh)
         stream.setVersion(QDataStream.Qt_5_7)
         magic = stream.readInt32()
         if magic != MagicNumber:
             raise IOError("not a valid .pgd file")
         fileVersion = stream.readInt16()
         if fileVersion != FileVersion:
             raise IOError("unrecognised .pgd file version")
         while not fh.atEnd():
             self.readItemFromStream(stream)
     except IOError as e:
         QMessageBox.warning(
             self, "Page Designer -- Open Error",
             "Failed to open {0}: {1}".format(self.filename, e))
     finally:
         if fh is not None:
             fh.close()
     global Dirty
     Dirty = False
Esempio n. 32
0
def loadProject(filename):
    # clear the map layer registry
    QgsProject.instance().removeAllMapLayers()

    assert os.path.exists(filename), "project file does not exist: " + filename

    # load the project
    QgsProject.instance().read(QFileInfo(filename))
    assert QgsProject.instance().mapLayers(), "no layers in map layer registry"

    doc = QDomDocument()
    with open(filename) as f:
        doc.setContent(f.read())

    # map settings
    mapSettings = QgsMapSettings()
    mapSettings.readXML(doc.elementsByTagName("mapcanvas").at(0))

    # visible layers
    layerIds = []
    nodes = doc.elementsByTagName("legendlayer")
    for i in range(nodes.count()):
        elem = nodes.at(i).toElement().elementsByTagName("legendlayerfile").at(
            0).toElement()
        if elem.attribute("visible") == "1":
            layerIds.append(elem.attribute("layerid"))
    mapSettings.setLayers(getLayersByLayerIds(layerIds))

    # canvas color
    red = int(
        doc.elementsByTagName("CanvasColorRedPart").at(0).toElement().text())
    green = int(
        doc.elementsByTagName("CanvasColorGreenPart").at(0).toElement().text())
    blue = int(
        doc.elementsByTagName("CanvasColorBluePart").at(0).toElement().text())
    mapSettings.setBackgroundColor(QColor(red, green, blue))

    return mapSettings
Esempio n. 33
0
        def convert_font():
            dialog = QFileDialog()
            filename = dialog.getSaveFileName(None, "Chọn thư mục và tên lớp đầu ra / "
                                                    "Choose output directory and output layer name", "",
                                              "Shapefile (*.shp)")
            if filename[0] == '':
                return None

            selected_layer_name = self.dlg3.input_layer.currentText()
            # Classic search :)
            selected_layer = None
            for layer in layers:
                if layer.name() == selected_layer_name:
                    selected_layer = layer
                    break

            font_in = self.dlg3.comboBox_font_in.currentText()
            font_out = self.dlg3.comboBox_font_out.currentText()

            shape_writer = QgsVectorFileWriter(filename[0], "UTF-8", selected_layer.dataProvider().fields()
                                               , selected_layer.dataProvider().wkbType(), selected_layer.crs())

            features = selected_layer.getFeatures()

            textfield = []
            for field in selected_layer.dataProvider().fields():
                if field.type() == 'QString':
                    textfield.append(field.name())

            for f in features:
                for ch in textfield:
                    txt = f[ch]
                    if txt != '' and not font_in == font_out:
                            f[ch] = self.convert_ch(txt, self.encoding_table(font_in), self.encoding_table(font_out))
                shape_writer.addFeature(f)

            layer = QgsVectorLayer(filename[0], QFileInfo(QFile(filename[0])).baseName(), 'ogr')
            layer.setProviderEncoding(u'System')
Esempio n. 34
0
 def loadQDataStream(self):
     error = None
     fh = None
     try:
         fh = QFile(self.__fname)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(unicode(fh.errorString()))
         stream = QDataStream(fh)
         magic = stream.readInt32()
         if magic != MovieContainer.MAGIC_NUMBER:
             raise IOError("unrecognized file type")
         version = stream.readInt32()
         if version < MovieContainer.FILE_VERSION:
             raise IOError("old and unreadable file format")
         elif version > MovieContainer.FILE_VERSION:
             raise IOError("new and unreadable file format")
         stream.setVersion(QDataStream.Qt_4_2)
         self.clear(False)
         while not stream.atEnd():
             title = QString()
             acquired = QDate()
             notes = QString()
             stream >> title
             year = stream.readInt16()
             minutes = stream.readInt16()
             stream >> acquired >> notes
             self.add(Movie(title, year, minutes, acquired, notes))
     except (IOError, OSError) as e:
         error = "Failed to load: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Loaded {0} movie records from {1}".format(
             len(self.__movies),
             QFileInfo(self.__fname).fileName())
Esempio n. 35
0
 def loadImage(self):
     name, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Abrir imagen')
     self.img = QtGui.QPixmap(name)
     self.graphicsView.setPhoto(self.img)
     self.filename = QFileInfo(name).fileName()
     if self.graphicsView.empty == False:
         self.rb_escala.setEnabled(True)
         self.rb_escala.setChecked(True)
         # self.pb_rehacerescala.setEnabled(True)
         self.le_escala.setEnabled(True)
         self.pb_OK.setEnabled(True)
         self.rb_linea.setEnabled(True)
         # self.pb_rehacerlinea.setEnabled(True)
         self.rb_puntos.setEnabled(True)
         self.tabla.setRowCount(0)
         self.tabla.setColumnCount(3)
         self.tabla.setHorizontalHeaderLabels(self.titulos_tabla)
         self.tabla.resizeColumnsToContents()
         self.tabla.setEnabled(True)
         self.tabla.setEditTriggers(QTableWidget.NoEditTriggers)
         self.pb_calcular.setEnabled(True)
         self.actionGuardar_imagen.setEnabled(True)
         self.actionCrear_informe.setEnabled(True)
Esempio n. 36
0
 def readTileset(self, *args):
     l = len(args)
     if l == 2:
         device, path = args
         return self.d.readTileset(device, path)
     elif l == 1:
         tp = type(args[0])
         if tp == QIODevice:
             return self.d.readTileset(device, QString())
         elif tp in [QString, str]:
             fileName = args[0]
             ##
             # Reads a TSX tileset from the given \a fileName.
             # \overload
             ##
             file = QFile(fileName)
             if (not self.d.openFile(file)):
                 return None
             tileset = self.readTileset(file,
                                        QFileInfo(fileName).absolutePath())
             if (tileset):
                 tileset.setFileName(fileName)
             return tileset
Esempio n. 37
0
 def parse_cmdline(self) -> None:
     self.parser = QCommandLineParser()
     self.parser.setApplicationDescription('\nVidCutter - the simplest + fastest media cutter & joiner')
     self.parser.addPositionalArgument('video', 'Preload video file', '[video]')
     self.parser.addPositionalArgument('project', 'Open VidCutter project file (.vcp)', '[project]')
     self.debug_option = QCommandLineOption(['debug'], 'debug mode; verbose console output & logging. '
                                            'This will basically output what is being logged to file to the '
                                            'console stdout. Mainly useful for debugging problems with your '
                                            'system video and/or audio stack and codec configuration.')
     self.parser.addOption(self.debug_option)
     self.parser.addVersionOption()
     self.parser.addHelpOption()
     self.parser.process(qApp)
     self.args = self.parser.positionalArguments()
     if self.parser.isSet(self.debug_option):
         os.environ['DEBUG'] = '1'
     if len(self.args) > 0:
         file_path = QFileInfo(self.args[0]).absoluteFilePath()
         if not os.path.exists(file_path):
             sys.stderr.write('\nERROR: File not found: %s\n' % file_path)
             self.close()
             qApp.exit(1)
         self.video = file_path
Esempio n. 38
0
    def open(self, t_filename=None):
        settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "pySPM",
                             "pySPM")
        if t_filename is None:
            home = QDir.cleanPath(os.getenv("HOMEPATH"))
            path = settings.value("lastPath", home)
            self.filename = QFileDialog.getOpenFileName(
                None, "Choose measurement file", path, "*.ita")[0]
        else:
            self.filename = t_filename
        check_file = QFileInfo(self.filename)
        self.setWindowTitle(check_file.fileName())
        if not check_file.exists() or not check_file.isFile():
            return

        settings.setValue("lastPath", check_file.path())
        self.ita = pySPM.ITA(self.filename, readonly=False)
        self.t, self.S = self.ita.getSpectrum(time=True)
        self.sf, self.k0 = self.ita.get_mass_cal()
        self.mass = pySPM.utils.time2mass(self.t, self.sf, self.k0)
        self.spec = self.ax.plot(self.mass, self.S)[0]
        SatLevel = self.ita.size['pixels']['x'] * self.ita.size['pixels'][
            'y'] * self.ita.Nscan
        self.sat_level = self.ax.axhline(SatLevel, color='r')
        if 'pySPM' in self.ita.root.goto("MassScale"):
            self.MassCal = []
            N = self.ita.root.goto("MassScale/pySPM/N").get_ulong()
            for i in range(N):
                elt = self.ita.root.goto("MassScale/pySPM/" + str(i) +
                                         "/elt").value.decode('utf8')
                mass = self.ita.root.goto("MassScale/pySPM/" + str(i) +
                                          "/mass").get_double()
                time = self.ita.root.goto("MassScale/pySPM/" + str(i) +
                                          "/time").get_double()
                self.MassCal.append(dict(elt=elt, mass=mass, time=time))
        else:
            self.MassCal = []
            for x in self.ita.root.goto("MassScale/calib"):
                if x.name == 'assign':
                    self.MassCal.append({'elt': x.get_string()})
                if x.name == 'mcp':
                    mcp = struct.unpack("<10d", x.value)
                    self.MassCal[-1]['time'] = mcp[0]
                    self.MassCal[-1]['mass'] = mcp[1]
        self.DoMassCal()
Esempio n. 39
0
    def save2output_file(self, fmt):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        TDialog = QFileDialog()
        fileName, _ = TDialog.getSaveFileName(None,"Save file as:", BS.lastdir, self.file_filter, options=options)
        if fileName:
            self.file = QFile(fileName)
            BS.lastdir = QFileInfo(fileName).absolutePath()
            if not self.file.open(QFile.WriteOnly):  # open to write
                mb = QMessageBox(self)
                mb.setTextFormat(Qt.RichText)
                mb.setText("<p style='font-size: 18pt'>Open File error</p>"
                           "<p style='font-size: 14pt; font-weight: normal'> Can't open file <i>{}</i> for writing.<br><br>"
                           " File error was: \"{}\".</p>".format(fileName, self.file.errorString()))
                mb.setIcon(QMessageBox.Warning)
                mb.exec()

                return False
            else:
                self.imageLabel.pixmap().save(self.file, fmt)
                return True
        else:
            return False
Esempio n. 40
0
    def update_recent_file_actions(self):
        """
        Update the actions (menu items) in the recent files list to
        reflect the recent file paths stored in the 'recentFileList' setting

        Returns
        -------
        None
        """
        settings = QSettings('USGS', 'pymdwizard')
        files = settings.value('recentFileList', [])

        num_recent_files = min(len(files), PyMdWizardMainForm.max_recent_files)

        for i in range(num_recent_files):
            stripped_name = QFileInfo(files[i]).fileName()
            text = "&%d %s" % (i + 1, stripped_name)
            self.recent_file_actions[i].setText(text)
            self.recent_file_actions[i].setData(files[i])
            self.recent_file_actions[i].setVisible(True)

        for j in range(num_recent_files, PyMdWizardMainForm.max_recent_files):
            self.recent_file_actions[j].setVisible(False)
Esempio n. 41
0
 def open_output_file(self):
     QApplication.restoreOverrideCursor()
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     TDialog = QFileDialog()
     fileName, _ = TDialog.getSaveFileName(self.parent,"Save file as:", BS.lastdir, self.file_filter, options=options)
     if fileName:
         self.file = QFile(fileName)
         BS.lastdir = QFileInfo(fileName).absolutePath()
         if not self.file.open(QFile.WriteOnly | QFile.Text):  # open to write
             mb = QMessageBox()
             mb.setTextFormat(Qt.RichText)
             mb.setText("<p style='font-size: 18pt'>Open File error</p>"
                        "<p style='font-size: 14pt; font-weight: normal'> Can't open file <i>{}</i> for writing.<br><br>"
                        " File error was: \"{}\".</p>".format(fileName, self.file.errorString()))
             mb.setIcon(QMessageBox.Warning)
             mb.exec()
             return False
         else:
             self.outstream = QTextStream(self.file)
             return True
     else:
         return False
Esempio n. 42
0
 def save2output_file(self, fmt):
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     TDialog = QFileDialog()
     fileName, _ = TDialog.getSaveFileName(None,
                                           "Save file as:",
                                           BS.lastdir,
                                           self.file_filter,
                                           options=options)
     if fileName:
         self.file = QFile(fileName)
         BS.lastdir = QFileInfo(fileName).absolutePath()
         if not self.file.open(QFile.WriteOnly):  # open to write
             QMessageBox.warning(
                 self, "Application",
                 "Cannot open file %s:\n%s. for writing" %
                 (fileName, self.file.errorString()))
             return False
         else:
             self.imageLabel.pixmap().save(self.file, fmt)
             return True
     else:
         return False
Esempio n. 43
0
    def __loadRecent(self):
        """
        Private method to load the recently used file names.
        """
        Preferences.Prefs.rsettings.sync()

        # load recently used file names
        self.fnHistory = []
        self.fnHistory.append('')
        rs = Preferences.Prefs.rsettings.value(recentNameBreakpointFiles)
        if rs is not None:
            recent = [
                f for f in Preferences.toList(rs) if QFileInfo(f).exists()
            ]
            self.fnHistory.extend(
                recent[:Preferences.getDebugger("RecentNumber")])

        # load recently entered condition expressions
        self.condHistory = []
        rs = Preferences.Prefs.rsettings.value(recentNameBreakpointConditions)
        if rs is not None:
            self.condHistory = Preferences.toList(
                rs)[:Preferences.getDebugger("RecentNumber")]
Esempio n. 44
0
    def on_load(self):
        logger.debug("load")
        img_path, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Open image",
                                                            self.path, "Images (*.png *.jpg *.ima)")

        if img_path:
            logger.debug(f"open file {img_path}")
            self.path = QFileInfo(img_path).path()
            logger.debug(self.path)

            valid_images = [".jpg", ".png", ".ima"]
            for f in os.listdir(self.path):
                ext = os.path.splitext(f)[1]
                if ext.lower() not in valid_images:
                    continue
                self.image_list.append(os.path.join(self.path, f).replace("\\", "/"))

            self.reset_btn.setEnabled(True)
            self.save_btn.setEnabled(True)
            self.Next_btn.setEnabled(True)
            self.Previous_btn.setEnabled(True)

            self.load_image(img_path)
Esempio n. 45
0
	def savePdf(self):
		fileName = QFileDialog.getSaveFileName(self,
			self.tr("Export document to PDF"),
			self.currentTab.getBaseName() + ".pdf",
			self.tr("PDF files (*.pdf)"))[0]
		if fileName:
			if not QFileInfo(fileName).suffix():
				fileName += ".pdf"
			title, htmltext, preview = self.currentTab.getDocumentForExport()
			if globalSettings.useWebEngine and hasattr(preview.page(), "printToPdf"):
				pageSize = self.getPageSizeByName(globalSettings.paperSize)
				if pageSize is None:
					pageSize = QPageSize(QPageSize.A4)
				margins = QMarginsF(20, 20, 13, 20)  # left, top, right, bottom (in millimeters)
				layout = QPageLayout(pageSize, QPageLayout.Portrait, margins, QPageLayout.Millimeter)
				preview.page().printToPdf(fileName, layout)  # Available since Qt 5.7
				return
			printer = self.standardPrinter(title)
			printer.setOutputFormat(QPrinter.PdfFormat)
			printer.setOutputFileName(fileName)
			document = self.getDocumentForPrint(title, htmltext, preview)
			if document != None:
				document.print(printer)
Esempio n. 46
0
    def dropEvent(self, e):
        """
        Drop files directly onto the widget
        File locations are stored in fname
        :param e:
        :return:
        """
        if e.mimeData().hasUrls:
            e.setDropAction(Qt.CopyAction)
            e.accept()
            # Workaround for OSx dragging and dropping
            for url in e.mimeData().urls():
                if op_sys == 'Darwin':
                    fname = str(
                        NSURL.URLWithString_(str(
                            url.toString())).filePathURL().path())
                else:
                    fname = str(url.toLocalFile())

            self.lastpath = QFileInfo(fname).path()
            self.load_files(fname)
        else:
            e.ignore()
Esempio n. 47
0
    def __saveImage(self):
        """
        Private slot to handle the Save Image menu action.
        """
        if self.mainWidget is None:
            E5MessageBox.critical(self, self.tr("Save Image"),
                                  self.tr("""There is no UI file loaded."""))
            return

        defaultExt = "PNG"
        filters = ""
        formats = QImageWriter.supportedImageFormats()
        for format in formats:
            filters = "{0}*.{1} ".format(filters,
                                         bytes(format).decode().lower())
        filter = self.tr("Images ({0})").format(filters[:-1])

        fname = E5FileDialog.getSaveFileName(self, self.tr("Save Image"), "",
                                             filter)
        if not fname:
            return

        ext = QFileInfo(fname).suffix().upper()
        if not ext:
            ext = defaultExt
            fname.append(".{0}".format(defaultExt.lower()))

        if qVersion() >= "5.0.0":
            pix = self.mainWidget.grab()
        else:
            pix = QPixmap.grabWidget(self.mainWidget)
        self.__updateChildren(self.lastStyle)
        if not pix.save(fname, str(ext)):
            E5MessageBox.critical(
                self, self.tr("Save Image"),
                self.tr("""<p>The file <b>{0}</b> could not be saved.</p>""").
                format(fname))
Esempio n. 48
0
    def _addView(self, win, fn=None, noName=""):
        """
        Protected method to add a view (i.e. window).
        
        @param win editor assembly to be added
        @param fn filename of this editor (string)
        @param noName name to be used for an unnamed editor (string)
        """
        editor = win.getEditor()
        if fn is None:
            if not noName:
                self.untitledCount += 1
                noName = self.tr("Untitled {0}").format(self.untitledCount)
            self.viewlist.addItem(noName)
            editor.setNoName(noName)
        else:
            txt = os.path.basename(fn)
            if not QFileInfo(fn).isWritable():
                txt = self.tr("{0} (ro)").format(txt)
            itm = QListWidgetItem(txt)
            itm.setToolTip(fn)
            self.viewlist.addItem(itm)
        self.currentStack.addWidget(win)
        self.currentStack.setCurrentWidget(win)
        editor.captionChanged.connect(self.__captionChange)
        editor.cursorLineChanged.connect(self.__cursorLineChanged)

        index = self.editors.index(editor)
        self.viewlist.setCurrentRow(index)
        editor.setFocus()
        if fn:
            self.changeCaption.emit(fn)
            self.editorChanged.emit(fn)
            self.editorLineChanged.emit(fn, editor.getCursorPosition()[0] + 1)
        else:
            self.changeCaption.emit("")
        self.editorChangedEd.emit(editor)
    def createWinShortcutToStartup(self,
                                   shortcutName,
                                   execFileTarget,
                                   arguments=None,
                                   startin=None,
                                   iconPath=None,
                                   enable=False):
        from win32com.client import Dispatch

        shell = Dispatch('WScript.Shell')
        startupPath = shell.SpecialFolders("Startup")
        fullPath = os.path.join("{}\{}.lnk".format(startupPath, shortcutName))

        if QFile.exists(fullPath):
            QFile.remove(fullPath)
            if not enable: return True

        shortcut = shell.CreateShortCut(fullPath)

        shortcut.Targetpath = execFileTarget
        if not execFileTarget.endswith(".exe"):
            arguments = execFileTarget
            shortcut.Targetpath = os.path.join(
                QFileInfo(sys.executable).absolutePath(), "pythonw.exe")

        if arguments:
            shortcut.Arguments = ''' "{}"'''.format(arguments)
        if startin:
            shortcut.WorkingDirectory = startin
        if iconPath:
            shortcut.IconLocation = iconPath
        try:
            shortcut.save()
        except Exception:
            return False
        if QFile.exists(fullPath):
            return True
Esempio n. 50
0
    def loadAvailableChronologies(self):
        self.chronologiesDir = QDir(self.settings.value("APIS/chronology_dir"))
        if self.chronologiesDir.exists():
            chronologiesJsonFiles = self.chronologiesDir.entryList(['*.json'],
                                                                   QDir.Files)
            if len(chronologiesJsonFiles) > 0:
                for chronology in chronologiesJsonFiles:
                    if QFile(
                            os.path.join(self.chronologiesDir.absolutePath(),
                                         chronology)
                    ).exists(
                    ):  # and is chronology json file (find some token to verify)
                        self.uiChronologyCombo.addItem(
                            QFileInfo(chronology).completeBaseName())

                indexCandidate = self.uiChronologyCombo.findText(
                    self.candidateCountry)
                indexDefault = self.uiChronologyCombo.findText(
                    self.settings.value("APIS/default_chronology", "AUT"))
                # QMessageBox.information(self, "Info", "{}, {}, {}".format(self.candidateCountry, indexCandidate, indexDefault))
                if indexCandidate >= 0:
                    self.uiChronologyCombo.setCurrentIndex(indexCandidate)
                elif indexDefault >= 0:
                    self.uiChronologyCombo.setCurrentIndex(indexDefault)
                else:
                    self.uiChronologyCombo.setCurrentIndex(0)
                self.isSetup = True
            else:
                QMessageBox.warning(
                    self, "Keine Chronologien vorhanden",
                    "Im angegebenen Verzeichnis ({0}) sind keine Chronologien vorhanden!"
                    .format(self.chronologiesDir.absolutePath()))
        else:
            QMessageBox.warning(
                self, "Ordner existiert nicht",
                "Das angegebenen Verzeichnis ({0}) existiert nicht!".format(
                    self.chronologiesDir.absolutePath()))
Esempio n. 51
0
 def _addView(self, win, fn=None, noName=""):
     """
     Protected method to add a view (i.e. window).
     
     @param win editor assembly to be added
     @param fn filename of this editor (string)
     @param noName name to be used for an unnamed editor (string)
     """
     editor = win.getEditor()
     if fn is None:
         if not noName:
             self.untitledCount += 1
             noName = self.tr("Untitled {0}").format(self.untitledCount)
         self.currentTabWidget.addTab(win, noName)
         editor.setNoName(noName)
     else:
         if self.filenameOnly:
             txt = os.path.basename(fn)
         else:
             txt = e5App().getObject("Project").getRelativePath(fn)
         if len(txt) > self.maxFileNameChars:
             txt = "...{0}".format(txt[-self.maxFileNameChars:])
         if not QFileInfo(fn).isWritable():
             txt = self.tr("{0} (ro)").format(txt)
         self.currentTabWidget.addTab(win, txt)
         index = self.currentTabWidget.indexOf(win)
         self.currentTabWidget.setTabToolTip(index, fn)
     self.currentTabWidget.setCurrentWidget(win)
     win.show()
     editor.setFocus()
     if fn:
         self.changeCaption.emit(fn)
         self.editorChanged.emit(fn)
         self.editorLineChanged.emit(fn, editor.getCursorPosition()[0] + 1)
     else:
         self.changeCaption.emit("")
     self.editorChangedEd.emit(editor)
    def __init__(self):
        root = QFileInfo(__file__).absolutePath()

        svg_files = os.listdir(root + "/icons/svg/")

        self.images = {}

        for filename in svg_files:
            f = QFile(root + '/icons/svg/' + filename)
            if f.open(QFile.ReadOnly | QFile.Text):
                textStream = QTextStream(f)
                svgData = textStream.readAll().replace('fill="#000000"',
                                                       'fill="#eeeeee"')
                svgData_hover = svgData.replace('fill="#eeeeee"',
                                                'fill="#3daee9"')
                f.close()

            svg = QSvgRenderer(QByteArray().append(svgData))
            svg_hover = QSvgRenderer(QByteArray().append(svgData_hover))

            qim = QImage(76, 76, QImage.Format_RGBA8888)
            qim.fill(0)
            painter = QPainter()
            painter.begin(qim)
            svg.render(painter)
            painter.end()

            qim_hover = QImage(76, 76, QImage.Format_ARGB32)
            qim_hover.fill(0)
            painter = QPainter()
            painter.begin(qim_hover)
            svg_hover.render(painter)
            painter.end()

            self.images[filename.replace("appbar.", "").replace(
                ".svg", "")] = (QIcon(QPixmap.fromImage(qim)),
                                QIcon(QPixmap.fromImage(qim_hover)))
Esempio n. 53
0
	def saveFileMain(self, dlg):
		if (not self.fileNames[self.ind]) or dlg:
			markupClass = self.getMarkupClass()
			if (markupClass is None) or not hasattr(markupClass, 'default_extension'):
				defaultExt = self.tr("Plain text (*.txt)")
				ext = ".txt"
			else:
				defaultExt = self.tr('%s files',
					'Example of final string: Markdown files') \
					% markupClass.name + ' (' + str.join(' ',
					('*'+extension for extension in markupClass.file_extensions)) + ')'
				if markupClass == markups.MarkdownMarkup:
					ext = globalSettings.markdownDefaultFileExtension
				elif markupClass == markups.ReStructuredTextMarkup:
					ext = globalSettings.restDefaultFileExtension
				else:
					ext = markupClass.default_extension
			newFileName = QFileDialog.getSaveFileName(self,
				self.tr("Save file"), "", defaultExt)[0]
			if newFileName:
				if not QFileInfo(newFileName).suffix():
					newFileName += ext
				if self.fileNames[self.ind]:
					self.fileSystemWatcher.removePath(self.fileNames[self.ind])
				self.fileNames[self.ind] = newFileName
				self.actionSetEncoding.setDisabled(self.autoSaveActive())
		if self.fileNames[self.ind]:
			result = self.saveFileCore(self.fileNames[self.ind])
			if result:
				self.setCurrentFile()
				self.editBoxes[self.ind].document().setModified(False)
				self.setWindowModified(False)
				return True
			else:
				QMessageBox.warning(self, '',
				self.tr("Cannot save to file because it is read-only!"))
		return False
Esempio n. 54
0
    def guardarCambios(self):
        homedir = os.path.expanduser("~")
        ruta=homedir+'\Desktop'
        try:
            texto2 = self.ui.cancionTE.toPlainText()
            self.ui.cancionTE.clear()
            escribirCrearArchivo(texto2)
            file_text=abrirAuxiliar()

            for f in file_text:
                if f[0]=='.':                     
                    self.ui.cancionTE.setTextColor(QtGui.QColor("blue"))
                    self.ui.cancionTE.setFontWeight(QtGui.QFont.Bold)
                    self.ui.cancionTE.setFontPointSize(10)
                    self.ui.cancionTE.append(f.strip('\n'))
                if f[0]!='.':
                    if f[0]!=' ':
                        self.ui.cancionTE.setTextColor(QtGui.QColor("black"))
                        self.ui.cancionTE.setFontWeight(QtGui.QFont.Bold)
                        self.ui.cancionTE.setFontPointSize(10)                            
                        self.ui.cancionTE.append(' '+f.strip('\n'))
                    if f[0]==' ':
                        self.ui.cancionTE.setTextColor(QtGui.QColor("black"))
                        self.ui.cancionTE.setFontWeight(QtGui.QFont.Bold)
                        self.ui.cancionTE.setFontPointSize(10)                            
                        self.ui.cancionTE.append(f.strip('\n'))
            
            filename, _ = QFileDialog.getSaveFileName(self, 'Save File', ruta)
            if filename !='':
                if QFileInfo(filename).suffix() == '':
                    filename += '.cec'
            f=open(filename, 'w')
            texto = self.ui.cancionTE.toPlainText()+'\n'+self.ui.cancionTE2.toPlainText()            
            f.write(texto)            
            f.close()            
        except:
            pass
Esempio n. 55
0
 def __exportStyles(self, lexers):
     """
     Private method to export the styles of the given lexers.
     
     @param lexers list of lexer objects for which to export the styles
     """
     fn, selectedFilter = E5FileDialog.getSaveFileNameAndFilter(
         self,
         self.tr("Export Highlighting Styles"),
         "",
         self.tr("Highlighting styles file (*.e4h)"),
         "",
         E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
     
     if not fn:
         return
     
     ext = QFileInfo(fn).suffix()
     if not ext:
         ex = selectedFilter.split("(*")[1].split(")")[0]
         if ex:
             fn += ex
     
     f = QFile(fn)
     if f.open(QIODevice.WriteOnly):
         from E5XML.HighlightingStylesWriter import HighlightingStylesWriter
         HighlightingStylesWriter(f, lexers).writeXML()
         f.close()
     else:
         E5MessageBox.critical(
             self,
             self.tr("Export Highlighting Styles"),
             self.tr(
                 """<p>The highlighting styles could not be exported"""
                 """ to file <b>{0}</b>.</p><p>Reason: {1}</p>""")
             .format(fn, f.errorString())
         )
Esempio n. 56
0
    def __init__(self):
        super(MainWindow, self).__init__()

        self.root = QFileInfo(__file__).absolutePath()
        self.curFile = ''

        self.graphicsView = proj1_imageviewer.ImageViewer()  #QScrollArea()
        self.graphicsView.setMouseTracking(False)
        self.graphicsView.setBackgroundRole(QPalette.Dark)
        #self.graphicsView.setWidget(self.imageLabel)
        self.setCentralWidget(self.graphicsView)

        self.setWindowTitle("iScissor")
        self.setGeometry(100, 100, 480, 300)
        self.setMinimumSize(480, 320)
        self.setWindowIcon(QIcon(self.root + 'iScissor.png'))
        self.curFile = ''
        self.isModified = False

        self.createActions()
        self.createMenus()
        self.createToolBars()
        self.createStatusBar()

        self.iScissorStartAct.setEnabled(False)
        self.iScissorDoneAct.setEnabled(False)
        self.undoAct.setEnabled(False)
        self.normalSizeAct.setEnabled(False)
        self.zoomInAct.setEnabled(False)
        self.zoomOutAct.setEnabled(False)
        self.orignalImgAct.setEnabled(False)
        self.maskedImgAct.setEnabled(False)
        self.imgWithContourAct.setEnabled(False)
        self.costGraphAct.setEnabled(False)
        self.pathTreeAct.setEnabled(False)
        return
Esempio n. 57
0
    def mouseMoveEvent(self, event):
        if QLineF(QPointF(event.screenPos()), QPointF(event.buttonDownScreenPos(Qt.LeftButton))).length() < QApplication.startDragDistance():
            return

        drag = QDrag(event.widget())
        mime = QMimeData()
        drag.setMimeData(mime)

        ColorItem.n += 1
        if ColorItem.n > 2 and qrand() % 3 == 0:
            root = QFileInfo(__file__).absolutePath()

            image = QImage(root + '/images/head.png')
            mime.setImageData(image)
            drag.setPixmap(QPixmap.fromImage(image).scaled(30,40))
            drag.setHotSpot(QPoint(15, 30))
        else:
            mime.setColorData(self.color)
            mime.setText("#%02x%02x%02x" % (self.color.red(), self.color.green(), self.color.blue()))

            pixmap = QPixmap(34, 34)
            pixmap.fill(Qt.white)

            painter = QPainter(pixmap)
            painter.translate(15, 15)
            painter.setRenderHint(QPainter.Antialiasing)
            self.paint(painter, None, None)
            painter.end()

            pixmap.setMask(pixmap.createHeuristicMask())

            drag.setPixmap(pixmap)
            drag.setHotSpot(QPoint(15, 20))

        drag.exec_()
        self.setCursor(Qt.OpenHandCursor)
Esempio n. 58
0
    def save_datastream(self, fname):
        error = None
        fh = None
        try:
            fh = QFile(fname)
            if not fh.open(QIODevice.WriteOnly):
                raise IOError(str(fh.errorString()))

            stream = QDataStream(fh)
            stream.writeQString(self.label)
            stream.writeInt32(self.diameter)
            stream.writeDouble(self.top_elev)
            stream.writeDouble(self.design_load)
            stream.setVersion(QDataStream.Qt_5_12)
        except EnvironmentError as e:
            error = "Failed to save:{0}".format(e)

        finally:
            if fh is not None:
                fh.close()
            if error is not None:
                print(error)
            self.__dirty = False
            print("save to {0}".format(QFileInfo(fname).fileName))
Esempio n. 59
0
 def __showContextMenuRecent(self):
     """
     Private method to set up the recent multi projects menu.
     """
     self.__loadRecent()
     
     self.recentMenu.clear()
     
     idx = 1
     for rp in self.recent:
         if idx < 10:
             formatStr = '&{0:d}. {1}'
         else:
             formatStr = '{0:d}. {1}'
         act = self.recentMenu.addAction(
             formatStr.format(
                 idx,
                 Utilities.compactPath(rp, self.ui.maxMenuFilePathLen)))
         act.setData(rp)
         act.setEnabled(QFileInfo(rp).exists())
         idx += 1
     
     self.recentMenu.addSeparator()
     self.recentMenu.addAction(self.tr('&Clear'), self.__clearRecent)
Esempio n. 60
0
 def saveFileDialog(self):
     fname = self.fileName()
     if fname is None:
         directory = "."
     else:
         directory = QFileInfo(fname).path()
     if util.isWindows():  # required for native looking file window
         fname = QFileDialog.getSaveFileName(
             self.win, "%s - Save As" % QApplication.applicationName(),
             directory, "%s (*.json)" % QApplication.applicationName())
         if isinstance(fname, (list, tuple)):
             fname = fname[0]
         self.writeDocumentToFile(fname)
     else:  # access through non-blocking callback
         fdialog = QFileDialog(
             self.win, "%s - Save As" % QApplication.applicationName(),
             directory, "%s (*.json)" % QApplication.applicationName())
         fdialog.setAcceptMode(QFileDialog.AcceptSave)
         fdialog.setWindowFlags(Qt.Sheet)
         fdialog.setWindowModality(Qt.WindowModal)
         self.filesavedialog = fdialog
         self.filesavedialog.filesSelected.connect(
             self.saveFileDialogCallback)
         fdialog.open()