コード例 #1
0
    def checkFileNameAndTemp(self, name, path):
        # 分离文件名和后缀名
        info = list()
        index = name.rfind('.')
        if index <= 0:
            info = [name, ""]
        else:
            info = [name[0:index], name[index + 1:]]

        dirList = QDir(path).entryList()
        filename = name
        tempname = filename + '.tmp'
        cfgname = tempname + '.cfg'
        if not filename in dirList and not tempname in dirList and not cfgname in dirList:
            return filename
        num = 1
        filename = info[0] + ('.' if len(info[1]) != 0 else '') + info[1]
        while filename in dirList or tempname in dirList or cfgname in dirList:
            filename = info[0] + "(" + str(num) + ")" + (
                '.' if len(info[1]) != 0 else '') + info[1]
            tempname = filename + '.tmp'
            cfgname = tempname + '.cfg'
            num += 1

        return filename
コード例 #2
0
    def saveSettings(self):
        sessionDir = QDir(DataPaths.path(DataPaths.Sessions))

        settings = Settings()
        settings.beginGroup('Web-Browser-Settings')
        settings.setValue('lastActiveSessionPath', sessionDir.relativeFilePath(self._lastActiveSessionPath))
        settings.endGroup()
コード例 #3
0
    def setDirectory(self, dirPath: str):
        self.currentDir = QDir(dirPath)
        self.sortingParser = EntrySortingFile(
            self.currentDir.filePath('.sorting'))
        self.entryProvider.setContext(dirPath)
        self.refreshListViewEntries()

        self.onDirectoryChanged.emit(self.currentDir.absolutePath())
コード例 #4
0
    def importBookmarks(self):
        '''
        @brief: Import bookmarks (it must return root folder)
        '''
        root = BookmarkItem(BookmarkItem.Folder)
        root.setTitle('Internet Explorer Import')

        self._readDir(QDir(self._path), root)
        return root
コード例 #5
0
ファイル: AppTools.py プロジェクト: zy-sunshine/falkon-pyqt5
 def copyRecursively(self, sourcePath, targetPath):
     srcFileInfo = QFileInfo(sourcePath)
     if srcFileInfo.isDir() and not srcFileInfo.isSymLink():
         targetDir = QDir(targetPath)
         targetDir.cdUp()
         if not targetDir.mkdir(QFileInfo(targetPath).fileName()):
             return False
         fileNames = QDir(sourcePath).entryList(QDir.Files | QDir.Dirs | QDir.NoDotAndDotDot |
                 QDir.Hidden | QDir.System)
         for fileName in fileNames:
             newSourcePath = sourcePath + '/' + fileName
             newTargetPath = targetPath + '/' + fileName
             if not self.copyRecursively(newSourcePath, newTargetPath):
                 return False
     elif not const.OS_WIN and srcFileInfo.isSymLink():
         linkPath = readlink(sourcePath)
         return QFile.link(linkPath, targetPath)
     elif not QFile.copy(sourcePath, targetPath):
         return False
     return True
コード例 #6
0
    def show_item(self):
        self.clear_content()
        info_path = self.path + QDir.separator() + self.name
        self.ui.nameInfoLabel.setText(self.name)
        self.ui.locationINfoLabel.setText(info_path)

        for img in QDir(info_path).entryList(self.filters, QDir.Files):
            full_path = info_path + QDir.separator() + img
            label = QLabel(self.ui.contentWidget)
            self.ui.contenLayout.addWidget(label)
            qimg = QImage(full_path)
            label.setPixmap(QPixmap.fromImage(qimg))
コード例 #7
0
    def loadSettings(self):
        sessionDir = QDir(DataPaths.path(DataPaths.Sessions))

        settings = Settings()
        settings.beginGroup('Web-Browser-Settings')
        self._lastActiveSessionPath = settings.value('lastActiveSessionPath', self.defaultSessionPath())
        settings.endGroup()

        if QDir.isRelativePath(self._lastActiveSessionPath):
            self._lastActiveSessionPath = sessionDir.absoluteFilePath(self._lastActiveSessionPath)

        # Fallback to default session
        if not RestoreManager.validateFile(self._lastActiveSessionPath):
            self._lastActiveSessionPath = self.defaultSessionPath()
コード例 #8
0
ファイル: qt_util.py プロジェクト: allen-marshall/scriptaseq
def make_multires_icon(path):
    """Makes a multi-resolution QIcon using images from the specified path.
  This function assumes that all files in the specified directory contain images that should be loaded into the QIcon.
  path -- Path to the directory containing the images from which the icon should be constructed. Should start with ":"
    if referencing a resource inside a packaged Qt resource file.
  """
    icon = QIcon()

    # For each file found in the specified directory, add a pixmap of the file's contents to the icon.
    for file_info in QDir(path).entryInfoList(sort=QDir.Name):
        if file_info.isFile():
            icon.addPixmap(QPixmap(file_info.absoluteFilePath()))

    return icon
コード例 #9
0
ファイル: MainWidget.py プロジェクト: 42Vision/MusicPlayer
 def open_file(self, current_index):
     filenames = []
     file_types = '*mp3 *wma *wav *asf *aac *mp3pro *vqf *flac *ape *mid *ogg' \
                  ' *MP3 *WMA *WAV *ASF *AAC *MP3PRO *VQF *FLAC *APE *MID *OGG'
     if current_index == 0:
         filenames = QFileDialog.getOpenFileNames(self, '选择音乐文件', 'G:/',
                                                  file_types)[0]
     elif current_index == 1:
         dir_path = QFileDialog.getExistingDirectory(self, '选择音乐文件', 'G:/')
         filenames = [
             '%s/%s' % (dir_path, file_name)
             for file_name in QDir(dir_path).entryList()
             if file_name != '.' and file_name != '..'
             and file_name.split('.')[-1] in file_types
         ]
     self.__musicList.add_music_item(filenames)
コード例 #10
0
    def __init__(self, parent, preferences):
        '''
        @param: parent QWidget
        @param: preferences Preferences
        '''
        super().__init__()
        self._ui = uic.loadUi('mc/preferences/ThemeManager.ui', self)
        self._preferences = preferences  # Preferences

        self._activeTheme = ''
        self._themeHash = {}  # QHash<QString, Theme>

        self._ui.listWidget.setLayoutDirection(Qt.LeftToRight)
        self._ui.license.hide()

        settings = Settings()
        settings.beginGroup('Themes')
        self._activeTheme = settings.value('activeTheme',
                                           const.DEFAULT_THEME_NAME)
        settings.endGroup()

        themePaths = DataPaths.allPaths(DataPaths.Themes)

        for path in themePaths:
            dir_ = QDir(path)
            list_ = dir_.entryList(QDir.AllDirs | QDir.NoDotAndDotDot)
            for name in list_:
                # Theme
                themeInfo = self._parseTheme(
                    dir_.absoluteFilePath(name) + '/', name)
                if not themeInfo.isValid:
                    continue

                item = QListWidgetItem(self._ui.listWidget)
                item.setText(themeInfo.name)
                item.setIcon(themeInfo.icon)
                item.setData(Qt.UserRole, name)

                if self._activeTheme == name:
                    self._ui.listWidget.setCurrentItem(item)

                self._ui.listWidget.addItem(item)

        self._ui.listWidget.currentItemChanged.connect(self._currentChanged)
        self._ui.license.clicked.connect(self._showLicense)

        self._currentChanged()
コード例 #11
0
ファイル: AppTools.py プロジェクト: zy-sunshine/falkon-pyqt5
    def resolveFromPath(self, name):
        '''
        @param: name QString
        @return: QString
        '''
        path = environ['PATH'].strip()

        if not path:
            return ''

        for item in path.split(pathsep):
            item = item.strip()
            if not item: continue
            d = QDir(item)
            if d.exists(name):
                return d.absoluteFilePath(name)

        return ''
コード例 #12
0
ファイル: DataPaths.py プロジェクト: zy-sunshine/falkon-pyqt5
    def setPortableVersion(cls):
        ''' Set Config path to $AppData/data '''
        d = cls.instance()
        appDir = pathjoin(const.BASE_DIR, 'data')
        d._paths[cls.AppData] = [
            appDir,
        ]
        d._paths[cls.Config] = [pathjoin(appDir, 'config')]
        d._paths[cls.Cache] = [pathjoin(appDir, 'cache')]
        d._paths[cls.Profiles] = [pathjoin(appDir, 'config', 'profiles')]

        d._paths[cls.Themes].clear()
        d._paths[cls.Themes] = [pathjoin(appDir, 'themes')]
        d._paths[cls.Plugins].clear()
        d._paths[cls.Plugins] = [pathjoin(appDir, 'plugins')]
        d.initAssertIn(appDir)

        # Make sure Temp path exists
        QDir().mkpath(d._paths[cls.Temp][0])
コード例 #13
0
    def checkFileName(self, name, path):
        # 分离文件名和后缀名
        info = list()
        index = name.rfind('.')
        if index <= 0:
            info = [name, ""]
        else:
            info = [name[0:index], name[index + 1:]]

        dirList = QDir(path).entryList()
        filename = name
        if not filename in dirList:
            return filename
        num = 1
        filename = info[0] + ('.' if len(info[1]) != 0 else '') + info[1]
        while filename in dirList:
            filename = info[0] + "(" + str(num) + ")" + (
                '.' if len(info[1]) != 0 else '') + info[1]
            num += 1

        return filename
コード例 #14
0
ファイル: AppTools.py プロジェクト: zy-sunshine/falkon-pyqt5
 def removeRecursively(self, filePath):
     '''
     @param: filePath QString
     '''
     fileInfo = QFileInfo(filePath)
     if not fileInfo.exists() and not fileInfo.isSymLink():
         return
     if fileInfo.isDir() and not fileInfo.isSymLink():
         dir_ = QDir(filePath)
         dir_ = dir_.canonicalPath()
         if dir_.isRoot() or dir_.path() == QDir.home().canonicalPath():
             print('CRITICAL: Attempt to remove root/home directory', dir_)
             return False
         fileNames = dir_.entryList(QDir.Files | QDir.Dirs | QDir.NoDotAndDotDot |
                 QDir.Hidden | QDir.System)
         for fileName in fileNames:
             if not self.removeRecursively(filePath + '/' + fileName):
                 return False
         if not QDir.root().rmdir(dir_.path()):
             return False
     elif not QFile.remove(filePath):
         return False
     return True
コード例 #15
0
    def _readDir(self, dir_, parent):
        '''
        @param: dir_ QDir
        @param: parent BookmarkItem
        '''
        for file_ in dir_.entryInfoList(QDir.Dirs | QDir.Files
                                        | QDir.NoDotAndDotDot):
            # file_ QFileInfo
            if file_.isDir():
                folder = BookmarkItem(BookmarkItem.Folder, parent)
                folder.setTitle(file_.baseName())

                folderDir = QDir(dir_)
                folderDir.cd(file_.baseName())
                self._readDir(folderDir, folder)
            elif file_.isFile():
                urlFile = QSettings(file_.absoluteFilePath(),
                                    QSettings.IniFormat)
                url = urlFile.value('InternetShortcut/URL', type=QUrl)

                item = BookmarkItem(BookmarkItem.Url, parent)
                item.setTitle(file_.baseName())
                item.setUrl(url)
コード例 #16
0
ファイル: DataPaths.py プロジェクト: zy-sunshine/falkon-pyqt5
    def init(self):
        from .MainApplication import MainApplication
        appDir = QCoreApplication.applicationDirPath()
        self._paths[self.AppData].extend(
            QStandardPaths.standardLocations(QStandardPaths.AppDataLocation))
        self._paths[self.Plugins].append(pathjoin(appDir, 'plugins'))
        for location in self._paths[self.AppData]:
            self.initAssertIn(location)
        if MainApplication.isTestModeEnabled():
            self._paths[self.Config].append(
                pathjoin(QDir().tempPath(), '%s-test' % const.APPNAME))
        else:
            self._paths[self.Config].append(
                QStandardPaths.writableLocation(
                    QStandardPaths.AppConfigLocation))

        self._paths[self.Profiles].append(
            pathjoin(self._paths[self.Config][0], 'profiles'))
        # We also allow to load data from Config path
        self.initAssertIn(self._paths[self.Config][0])

        # if PLUGIN_PATH is set, only load plugins from there
        pluginPath = environ.get('PLUGIN_PATH', '')
        if pluginPath:
            self._paths[self.Plugins] = [
                pluginPath,
            ]

        self._tmpdir = QTemporaryDir()
        self._paths[self.Temp].append(self._tmpdir.path())
        if not self._tmpdir.isValid():
            print('Failed to create temporary directory %s' %
                  self._tmpdir.path(),
                  file=stderr)

        self._paths[self.Cache].append(
            QStandardPaths.writableLocation(QStandardPaths.CacheLocation))
コード例 #17
0
    def _fillSessionsMetaDataListIfNeeded(self):
        '''
        @brief: load all session meta info from sessions directory include default session file
        '''
        if self._sessionsMetaDataList:
            return

        dir_ = QDir(DataPaths.path(DataPaths.Sessions))

        sessionFiles = []
        sessionFiles.append(QFileInfo(self.defaultSessionPath()))
        sessionFiles.extend(dir_.entryInfoList(['*.*'], QDir.Files, QDir.Time))

        fileNames = []

        defaultFileInfo = QFileInfo(self.defaultSessionPath())
        for fileInfo in sessionFiles:
            if not RestoreManager.validateFile(fileInfo.absoluteFilePath()):
                continue

            metaData = self.SessionMetaData()
            metaData.name = baseName = fileInfo.completeBaseName()

            if fileInfo == defaultFileInfo:
                metaData.name = _('Default session')
                metaData.isDefault = True
            elif baseName in fileNames:
                metaData.name = fileInfo.fileName()

            if self._isActive(fileInfo):
                metaData.isActive = True

            fileNames.append(metaData.name)
            metaData.filePath = fileInfo.canonicalFilePath()

            self._sessionsMetaDataList.append(metaData)
コード例 #18
0
 def availableProfiles(cls):
     '''
     @brief: Name of available profiles
     '''
     dir_ = QDir(DataPaths.path(DataPaths.Profiles))
     return dir_.entryList(QDir.Dirs | QDir.NoDotAndDotDot)
コード例 #19
0
 def isDirExist(self, fullPath):
     dir = QDir(fullPath)
     if dir.exists():
         return True
     else:
         return dir.mkpath(fullPath)
コード例 #20
0
 def isFileExist(self, path, filename):
     dir = QDir(path)
     return filename in dir.entryList()
コード例 #21
0
 def to_start_item(self):
     self.iter = iter(QDir(self.path).entryList(QDir.Dirs | QDir.NoDotAndDotDot))
     try:
         self.name = next(self.iter)
     except StopIteration:
         self.name = ""