def __init__(self):
        """
        Constructor
        """
        super(WebBrowserSpellCheckingPage, self).__init__()
        self.setupUi(self)
        self.setObjectName("WebBrowserSpellCheckingPage")

        # set initial values
        self.spellCheckEnabledCheckBox.setChecked(
            Preferences.getWebBrowser("SpellCheckEnabled"))
        self.on_spellCheckEnabledCheckBox_clicked()

        if Globals.isMacPlatform():
            self.__dictionaryDirectories = {
                QDir.cleanPath(QCoreApplication.applicationDirPath() +
                               "/../Resources/qtwebengine_dictionaries"),
                QDir.cleanPath(QCoreApplication.applicationDirPath() +
                               "/../Frameworks/QtWebEngineCore.framework"
                               "/Resources/qtwebengine_dictionaries"),
            }
        else:
            self.__dictionaryDirectories = {
                QDir.cleanPath(QCoreApplication.applicationDirPath() +
                               "/qtwebengine_dictionaries"),
                QDir.cleanPath(
                    QLibraryInfo.location(QLibraryInfo.DataPath) +
                    "/qtwebengine_dictionaries"),
            }
        self.spellCheckDictionaryDirectoriesEdit.setPlainText("\n".join(
            self.__dictionaryDirectories))
        # try to create these directories, if they don't exist
        for directory in self.__dictionaryDirectories:
            if not os.path.exists(directory):
                try:
                    os.makedirs(directory)
                except os.error:
                    # ignore it
                    pass

        self.__writeableDirectories = []
        for directory in self.__dictionaryDirectories:
            if os.access(directory, os.W_OK):
                self.__writeableDirectories.append(directory)
        self.manageDictionariesButton.setEnabled(
            bool(self.__writeableDirectories))

        self.__populateDictionariesList()
Пример #2
0
    def parseInDocRules(self):
        oldRules = self.inDocRules
        self.inDocRules = []

        t = self.thisDocument.toPlainText()

        # Get all conf files
        confs = []
        lines = t.split("\n")
        for l in lines:
            r = QRegExp(r'^%!includeconf:\s*([^\s]*)\s*')
            if r.indexIn(l) != -1:
                confs.append(r.cap(1))

        # Try to load conf files
        for c in confs:
            try:
                import codecs
                f = self.editor.fileWidget.file
                d = QDir.cleanPath(QFileInfo(f).absoluteDir().absolutePath() + "/" + c)
                file = codecs.open(d, 'r', "utf-8")
            except:
                print(("Error: cannot open {}.".format(c)))
                continue
                # We add the content to the current lines of the current document
            lines += file.readlines()  # lines.extend(file.readlines())

        # b = self.thisDocument.firstBlock()
        lastColor = ""

        # while b.isValid():
        for l in lines:
            text = l  # b.text()
            r = QRegExp(r'^%!p[or][se]t?proc[^\s]*\s*:\s*(\'[^\']*\'|\"[^\"]*\")\s*(\'[^\']*\'|\"[^\"]*\")')
            if r.indexIn(text) != -1:
                rule = r.cap(1)[1:-1]
                # Check if there was a color-comment above that post/preproc bloc
                if lastColor:
                    self.inDocRules.append((str(rule), lastColor))
                # Check if previous block is a comment like it should
                else:
                    previousText = lines[lines.indexOf(l) - 1]  # b.previous().text()
                    r = QRegExp(r'^%.*\s\((.*)\)')
                    if r.indexIn(previousText) != -1:
                        lastColor = r.cap(1)
                        self.inDocRules.append((str(rule), lastColor))
            else:
                lastColor = ""
                # b = b.next()

        if oldRules != self.inDocRules:
            # Rules have changed, we need to rehighlight
            # print("Rules have changed.", len(self.inDocRules))
            # self.rehighlight()  # Doesn't work (seg fault), why?
            pass
Пример #3
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
Пример #4
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
Пример #5
0
 def onLocationButtonClicked(self):
     dialog = QFileDialog(self)
     new_location = dialog.getExistingDirectory(
         self, "Location", self.plutoVariables.projectHome,
         QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
     if new_location:
         self.projectLocation = new_location
         if self.projectName:
             self.locationEdit.setText(
                 QDir.cleanPath(self.projectLocation + '/' +
                                self.projectName))
         else:
             self.locationEdit.setText(self.projectLocation)
def directory(app):
    #app = QApplication(sys.argv)

    QCoreApplication.setApplicationVersion(QT_VERSION_STR)
    parser = QCommandLineParser()
    parser.setApplicationDescription("File Directory")
    parser.addHelpOption()
    parser.addVersionOption()

    dontUseCustomDirectoryIconsOption = QCommandLineOption(
        'C', "Set QFileIconProvider.DontUseCustomDirectoryIcons")
    parser.addOption(dontUseCustomDirectoryIconsOption)
    parser.addPositionalArgument('', "The directory to start in.")
    parser.process(app)
    try:
        rootPath = parser.positionalArguments().pop(0)
    except IndexError:
        rootPath = None

    model = QFileSystemModel()
    model.setRootPath('')
    filter = ['*.db']  #filtering out just by db
    model.setNameFilters(filter)
    model.setNameFilterDisables(0)  #Only show the filtered .db paths
    #filename = model.filePath()
    #print(filename)

    if parser.isSet(dontUseCustomDirectoryIconsOption):
        model.iconProvider().setOptions(
            QFileIconProvider.DontUseCustomDirectoryIcons)
    tree = QTreeView()
    tree.setModel(model)
    if rootPath is not None:
        rootIndex = model.index(QDir.cleanPath(rootPath))
        if rootIndex.isValid():
            tree.setRootIndex(rootIndex)

    # Demonstrating look and feel features.
    tree.setAnimated(False)
    tree.setIndentation(20)
    tree.setSortingEnabled(True)

    availableSize = QApplication.desktop().availableGeometry(tree).size()
    tree.resize(availableSize / 2)
    tree.setColumnWidth(0, tree.width() / 3)

    tree.setWindowTitle("Directory View")
    tree.show()

    sys.exit(app.exec_())
Пример #7
0
    def add_recent_project(self, project_full_path):
        absolute_file_path = QDir.cleanPath(
            QFileInfo(project_full_path).absoluteFilePath())

        if not absolute_file_path:
            return

        recent_pros = self.recent_projects()
        if absolute_file_path in recent_pros:
            recent_pros.remove(absolute_file_path)
        recent_pros.insert(0, absolute_file_path)

        while len(recent_pros) > self.max_recent_project:
            recent_pros.pop()

        self._settings.setValue("RecentFiles/ProjectName", recent_pros)
Пример #8
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")
        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)
        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()
Пример #9
0
def processResourceFile(filenamesIn, filenameOut, listFiles):
    if verbose:
        sys.stderr.write("PyQt5 resource compiler\n")

    # Setup.
    library = RCCResourceLibrary()
    library.setInputFiles(filenamesIn)
    library.setInitName(initName)
    library.setVerbose(verbose)
    library.setCompressLevel(compressLevel)
    library.setCompressThreshold(compressThreshold)
    library.setResourceRoot(resourceRoot)

    if not library.readFiles():
        return False

    if filenameOut == '-':
        filenameOut = ''

    if listFiles:
        # Open the output file or use stdout if not specified.
        if filenameOut:
            try:
                out_fd = open(filenameOut, 'w')
            except Exception:
                sys.stderr.write(
                        "Unable to open %s for writing\n" % filenameOut)
                return False
        else:
            out_fd = sys.stdout

        for df in library.dataFiles():
            out_fd.write("%s\n" % QDir.cleanPath(df))

        if out_fd is not sys.stdout:
            out_fd.close()

        return True

    return library.output(filenameOut)
Пример #10
0
def processResourceFile(filenamesIn, filenameOut, listFiles):
    if verbose:
        sys.stderr.write("PyQt5 resource compiler\n")

    # Setup.
    library = RCCResourceLibrary()
    library.setInputFiles(filenamesIn)
    library.setInitName(initName)
    library.setVerbose(verbose)
    library.setCompressLevel(compressLevel)
    library.setCompressThreshold(compressThreshold)
    library.setResourceRoot(resourceRoot)

    if not library.readFiles():
        return False

    if filenameOut == '-':
        filenameOut = ''

    if listFiles:
        # Open the output file or use stdout if not specified.
        if filenameOut:
            try:
                out_fd = open(filenameOut, 'w')
            except Exception:
                sys.stderr.write("Unable to open %s for writing\n" %
                                 filenameOut)
                return False
        else:
            out_fd = sys.stdout

        for df in library.dataFiles():
            out_fd.write("%s\n" % QDir.cleanPath(df))

        if out_fd is not sys.stdout:
            out_fd.close()

        return True

    return library.output(filenameOut)
Пример #11
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")
     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)
     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()                    
Пример #12
0
    def _downloadAndUnzip(self, itemid):
        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimum(0)
        self.progress_bar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.progess_message_bar = self.iface.messageBar().createMessage(
            tr("Downloading..."))
        self.progess_message_bar.layout().addWidget(self.progress_bar)

        self.iface.messageBar().pushWidget(self.progess_message_bar, Qgis.Info)

        # FIXME: the signal is always emitted
        # self.iface.messageBar().widgetRemoved.connect(self.widget_removed)

        def extract_data(tmpPath, itemid):
            LOG.debug("Extract data")
            try:
                targetFolder = DataCatalogueClient.folderForDataItem(itemid)
                QDir(targetFolder).removeRecursively()
                unzip.unzip(tmpPath, targetFolder)
                QFile(tmpPath).remove()
            except Exception as e:
                LOG.debug("Error on extracting data %s" % e)

        url = f"{self.url}/content/items/{itemid}/data"
        tmpDir = QDir.tempPath()
        filename = f"{itemid}.zip"
        tmpPath = QDir.cleanPath(os.path.join(tmpDir, filename))
        loop = QEventLoop()
        self.downloader = QgsFileDownloader(QUrl(url), tmpPath)
        self.downloader.downloadProgress.connect(self.update_progress)
        self.downloader.downloadCompleted.connect(self.download_finished)
        self.downloader.downloadCompleted.connect(
            partial(extract_data, tmpPath, itemid))
        self.downloader.downloadCanceled.connect(self.download_canceled)
        self.downloader.downloadExited.connect(loop.quit)
        loop.exec_()
Пример #13
0
parser.addPositionalArgument("directory", "The directory to start in.")
parser.process(app)
try:
    rootPath = parser.positionalArguments().pop(0)
except IndexError:
    rootPath = None

model = QFileSystemModel()
model.setRootPath("")
if parser.isSet(dontUseCustomDirectoryIconsOption):
    model.iconProvider().setOptions(
        QFileIconProvider.DontUseCustomDirectoryIcons)
tree = QTreeView()
tree.setModel(model)
if rootPath is not None:
    rootIndex = model.index(QDir.cleanPath(rootPath))
    if rootIndex.isValid():
        tree.setRootIndex(rootIndex)

# Demonstrating look and feel features.
tree.setAnimated(False)
tree.setIndentation(20)
tree.setSortingEnabled(True)

availableSize = QApplication.desktop().availableGeometry(tree).size()
tree.resize(availableSize / 2)
tree.setColumnWidth(0, tree.width() / 3)

tree.setWindowTitle("Dir View")
tree.show()
Пример #14
0
def resolvePath(dir, variant):
    fileName = variant
    if (QDir.isRelativePath(fileName)):
        fileName = QDir.cleanPath(dir.absoluteFilePath(fileName))
    return fileName
Пример #15
0
parser.addPositionalArgument('directory', "The directory to start in.")
parser.process(app)
try:
    rootPath = parser.positionalArguments().pop(0)
except IndexError:
    rootPath = None

model = QFileSystemModel()
model.setRootPath('')
if parser.isSet(dontUseCustomDirectoryIconsOption):
    model.iconProvider().setOptions(
            QFileIconProvider.DontUseCustomDirectoryIcons)
tree = QTreeView()
tree.setModel(model)
if rootPath is not None:
    rootIndex = model.index(QDir.cleanPath(rootPath))
    if rootIndex.isValid():
        tree.setRootIndex(rootIndex)

# Demonstrating look and feel features.
tree.setAnimated(False)
tree.setIndentation(20)
tree.setSortingEnabled(True)

availableSize = QApplication.desktop().availableGeometry(tree).size()
tree.resize(availableSize / 2)
tree.setColumnWidth(0, tree.width() / 3)

tree.setWindowTitle("Dir View")
tree.show()
Пример #16
0
def main():
    # Parse the command line.  Note that this mimics the original C++ (warts
    # and all) in order to preserve backwards compatibility.
    global verbose
    global compressLevel
    global compressThreshold
    global resourceRoot

    outFilename = ''
    helpRequested = False
    listFiles = False
    files = []

    errorMsg = None
    argc = len(sys.argv)
    i = 1

    while i < argc:
        arg = sys.argv[i]
        i += 1

        if arg[0] == '-':
            opt = arg[1:]

            if opt == "o":
                if i >= argc:
                    errorMsg = "Missing output name"
                    break

                outFilename = sys.argv[i]
                i += 1

            elif opt == "root":
                if i >= argc:
                    errorMsg = "Missing root path"
                    break

                resourceRoot = QDir.cleanPath(sys.argv[i])
                i += 1

                if resourceRoot == '' or resourceRoot[0] != '/':
                    errorMsg = "Root must start with a /"
                    break

            elif opt == "compress":
                if i >= argc:
                    errorMsg = "Missing compression level"
                    break

                compressLevel = int(sys.argv[i])
                i += 1

            elif opt == "threshold":
                if i >= argc:
                    errorMsg = "Missing compression threshold"
                    break

                compressThreshold = int(sys.argv[i])
                i += 1

            elif opt == "verbose":
                verbose = True

            elif opt == "list":
                listFiles = True

            elif opt == "version":
                sys.stderr.write("pyrcc5 v%s\n" % PYQT_VERSION_STR)
                sys.exit(1)

            elif opt == "help" or opt == "h":
                helpRequested = True

            elif opt == "no-compress":
                compressLevel = -2

            else:
                errorMsg = "Unknown option: '%s'" % arg
                break
        else:
            if not QFile.exists(arg):
                sys.stderr.write(
                        "%s: File does not exist '%s'\n" % (sys.argv[0], arg))
                sys.exit(1)

            files.append(arg)

    # Handle any errors or a request for help.
    if len(files) == 0 or errorMsg is not None or helpRequested:
        showHelp(errorMsg)
        sys.exit(1)

    if not processResourceFile(files, outFilename, listFiles):
        sys.exit(1)
Пример #17
0
def main():
    # Parse the command line.  Note that this mimics the original C++ (warts
    # and all) in order to preserve backwards compatibility.
    global verbose
    global compressLevel
    global compressThreshold
    global resourceRoot

    outFilename = ''
    helpRequested = False
    listFiles = False
    files = []

    errorMsg = None
    argc = len(sys.argv)
    i = 1

    while i < argc:
        arg = sys.argv[i]
        i += 1

        if arg[0] == '-':
            opt = arg[1:]

            if opt == "o":
                if i >= argc:
                    errorMsg = "Missing output name"
                    break

                outFilename = sys.argv[i]
                i += 1

            elif opt == "root":
                if i >= argc:
                    errorMsg = "Missing root path"
                    break

                resourceRoot = QDir.cleanPath(sys.argv[i])
                i += 1

                if resourceRoot == '' or resourceRoot[0] != '/':
                    errorMsg = "Root must start with a /"
                    break

            elif opt == "compress":
                if i >= argc:
                    errorMsg = "Missing compression level"
                    break

                compressLevel = int(sys.argv[i])
                i += 1

            elif opt == "threshold":
                if i >= argc:
                    errorMsg = "Missing compression threshold"
                    break

                compressThreshold = int(sys.argv[i])
                i += 1

            elif opt == "verbose":
                verbose = True

            elif opt == "list":
                listFiles = True

            elif opt == "version":
                sys.stderr.write("pyrcc5 v%s\n" % PYQT_VERSION_STR)
                sys.exit(1)

            elif opt == "help" or opt == "h":
                helpRequested = True

            elif opt == "no-compress":
                compressLevel = -2

            else:
                errorMsg = "Unknown option: '%s'" % arg
                break
        else:
            if not QFile.exists(arg):
                sys.stderr.write(
                        "%s: File does not exist '%s'\n" % (sys.argv[0], arg))
                sys.exit(1)

            files.append(arg)

    # Handle any errors or a request for help.
    if len(files) == 0 or errorMsg is not None or helpRequested:
        showHelp(errorMsg)
        sys.exit(1)

    if not processResourceFile(files, outFilename, listFiles):
        sys.exit(1)
Пример #18
0
def resolvePath(dir, variant):
    fileName = variant
    if (QDir.isRelativePath(fileName)):
        fileName = QDir.cleanPath(dir.absoluteFilePath(fileName))
    return fileName
Пример #19
0
 def resolveReference(self, reference, mapPath):
     resolved = super().resolveReference(reference, mapPath)
     return QDir.cleanPath(resolved)