Пример #1
0
bool LevelService::loadAllLevels()
{
    boost::unique_lock<boost::mutex> lock(mMutex);
    fs::path loadPath("data/levels");
    fs::directory_iterator endIt;

    if (!fs::exists(loadPath) || !fs::is_directory(loadPath)) return false;

    for (fs::directory_iterator dirIt(loadPath); dirIt != endIt; ++dirIt) {
        fs::path dirPath = *dirIt;
        if (fs::is_directory(dirPath)) {
            std::string levelId = dirPath.filename().string();
            fs::path levelFilePath = dirPath / (levelId + ".level");
            if (fs::exists(levelFilePath) && fs::is_regular_file(levelFilePath)) {
                try {
                    loadLevelNoLock(levelId, true);
                }
                catch (const SerializationException &e) {
                    std::cerr << "Loading " << levelId << " failed\n";
                    std::cerr << e.what() << std::endl;
                }
            }
        }
    }

    for (auto &idLevelPair : mLevels) {
        idLevelPair.second->resolveRoomExits();
    }

    return true;
}
Пример #2
0
void QtStyleManager::GetIconThemes(IconThemeList& iconThemes) const
{
  iconThemes.clear();
  iconThemes.push_back(IconTheme(QString( "<<default>>" )));

  QStringList iconSearchPaths = QIcon::themeSearchPaths();

  for(QStringList::Iterator pathIt = iconSearchPaths.begin(); pathIt != iconSearchPaths.end(); ++pathIt)
  {
    QDirIterator dirIt(*pathIt);
    while (dirIt.hasNext())
    {
      QString current = dirIt.next();
      QFileInfo info = dirIt.fileInfo();
      if (info.isDir() && info.isReadable())
      {
        QFileInfo themeFile( info.filePath() + QString("/index.theme") );
        if( themeFile.exists() && themeFile.isFile() && themeFile.isReadable() )
        {
          QString fileName = info.fileName();
          iconThemes.push_back( IconTheme(fileName) );
        }
      }
    }
  }
}
Пример #3
0
void suiPluginManager::loadPluginsFromDir(const QString &dirPath, bool subdirs)
{
    if (!QDir(dirPath).exists()) SuiExcept(SuiExceptionFileNotFound,
                                           QString("Directory '%1' doesn't exist").arg(dirPath),
                                           "void suiPluginManager::loadPluginsFromDir(const QString &dirPath)");
    QDir pluginsDir(dirPath);

    QDirIterator dirIt(pluginsDir, subdirs ? QDirIterator::Subdirectories : QDirIterator::NoIteratorFlags);

    while (dirIt.hasNext())
    {
        QString fileName = dirIt.next();
        QFileInfo fionfo(fileName);

        // skip non file objetcs
        if (!fionfo.isFile()) continue;

        try
        {
            loadPlugin(fileName);
        }catch (...)
        {
            qDebug() << "Can't load plugin from " << pluginsDir.absoluteFilePath(fileName);
        }
    }
}
Пример #4
0
bool CharacterService::loadAllCharacters()
{
    UNIQUE_LOCK(mMutex);
    fs::path loadPath("data/characters");
    fs::directory_iterator endIt;

    if (!fs::exists(loadPath) || !fs::is_directory(loadPath)) return false;

    for (fs::directory_iterator dirIt(loadPath); dirIt != endIt; ++dirIt) {
        fs::path filePath = *dirIt;
        if (fs::is_regular_file(filePath)) {
            if (filePath.extension().string() == ".json") {
                try {
                    Json::Value characterJson = RS->readJsonFile(filePath.string());
                    std::shared_ptr<Character> character = std::make_shared<Character>();
                    Json::deserialize(characterJson, character);
                    if (mCharacters[character->id()]) {
                        std::cerr << "Duplicated character id " << character->id() << std::endl;
                        std::cerr << "Ignored";
                        continue;
                    }
                    mCharacters[character->id()] = character;
                }
                catch (const SerializationException &e) {
                    std::cerr << "Loading " << filePath.string() << " failed" << std::endl;
                    std::cerr << e.what();
                }
            }
        }
    }
    return true;
}
Пример #5
0
void LoadChemStationDataDialog::singleSelected(const QModelIndex &index)
{
  QVector<ChemStationFileInfoModel::Entry> entries;

  m_currentDirPath = m_fsModel->filePath(index);
  QDir dir(m_currentDirPath);

  if (!dir.exists())
    return;

  QDirIterator dirIt(m_currentDirPath, QDir::Files | QDir::NoSymLinks, QDirIterator::NoIteratorFlags);

  while (dirIt.hasNext()) {
    QString fileName = dirIt.next();
    QString absoluteFilePath = dir.absoluteFilePath(fileName);
    QString name = QFileInfo(absoluteFilePath).fileName();

    ChemStationFileLoader::Data chData = ChemStationFileLoader::loadHeader(absoluteFilePath);
    if (!chData.isValid())
      entries.push_back(ChemStationFileInfoModel::Entry(name, "", "", false));
    else
      entries.push_back(ChemStationFileInfoModel::Entry(name, createFileType(chData.type), createAdditionalInfo(chData), true));
  }

  m_finfoModel->setNewData(entries);
  m_finfoModel->sort(0, Qt::AscendingOrder);
}
Пример #6
0
static QString iconFromDirectoryFile(const QString &path)
{
    const QString filePath = path + QLatin1String("/.directory");
    if (!QFileInfo(filePath).isFile()) { // exists -and- is a file
        return QString();
    }

    KDesktopFile cfg(filePath);
    QString icon = cfg.readIcon();

    const KConfigGroup group = cfg.desktopGroup();
    const QString emptyIcon = group.readEntry("EmptyIcon");
    if (!emptyIcon.isEmpty()) {
        bool isDirEmpty = true;
        QDirIterator dirIt(path, QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
        while (dirIt.hasNext()) {
            dirIt.next();
            if (dirIt.fileName() != QLatin1String(".directory")) {
                isDirEmpty = false;
                break;
            }
        }
        if (isDirEmpty) {
            icon = emptyIcon;
        }
    }

    if (icon.startsWith(QLatin1String("./"))) {
        // path is relative with respect to the location
        // of the .directory file (#73463)
        return path + icon.mid(1);
    }
    return icon;
}
Пример #7
0
void PluginManager::initialize(QString const & _dirPath)
{

    //! TODO: reutrn error
    if (!QDir(_dirPath).exists())
        return;

    QDir pluginsDir(_dirPath);

    QDirIterator dirIt(_dirPath, QDirIterator::Subdirectories);

    while (dirIt.hasNext())
    {
        QString fileName = dirIt.next();
        QFileInfo fionfo(fileName);

        // skip non file objetcs
        if (!fionfo.isFile()) continue;

        try
        {
            loadPlugin(fileName);
        }catch (...)
        {
            qDebug() << "Can't load plugin from " << pluginsDir.absoluteFilePath(fileName);
        }
    }
}
Пример #8
0
void MusicLibrary::_scanFiles(QList<QString> *foundFiles, QString path) {
    QDirIterator dirIt(path,QDirIterator::Subdirectories);
    QFileInfo qfi;
    QString fpath;
    QString ext;
    int x;

    while( dirIt.hasNext() ) {
        dirIt.next();

        fpath = dirIt.filePath();
        qfi =QFileInfo(fpath);
        if( qfi.isFile() ) {
            x = fpath.lastIndexOf('.');
            ext = fpath.left(x);

            if( fpath.right(fpath.length()-x) == ".mp3" && QFileInfo(QString(ext).append(".cdg")).exists() ) {
                foundFiles->append(fpath);
            }
        } else if( qfi.isDir() && qfi.fileName() != "." && qfi.fileName() != ".." ) {
            qDebug() << "Scan directory" << qfi.fileName();
            _scanFiles(foundFiles,dirIt.filePath());
        }
    }
}
Пример #9
0
QStringList fs::list(const QString &path){
    QDirIterator dirIt(path,QDirIterator::Subdirectories);
    QStringList list;
    while (dirIt.hasNext()) {
        dirIt.next();
        list.push_front(dirIt.filePath());
    }
    return list;
}
Пример #10
0
/*
    Get specific file info's, batch the files so update when we have 100
    items and every 200ms after that
 */
void RemoteFileInfoGatherer::getFileInfos(const QString &path, const QStringList &files)
{
    // List drives
    if (path.isEmpty()) {
#ifdef QT_BUILD_INTERNAL
        fetchedRoot.store(true);
#endif
        QFileInfoList infoList;
        if (files.isEmpty()) {
            infoList = QDir::drives();
        } else {
            infoList.reserve(files.count());
            for (const auto &file : files)
                infoList << QFileInfo(file);
        }
        for (int i = infoList.count() - 1; i >= 0; --i) {
            QString driveName = translateDriveName(infoList.at(i));
            QVector<QPair<QString,FileInfo> > updatedFiles;
            updatedFiles.append(QPair<QString,FileInfo>(driveName, toFileInfo(infoList.at(i))));
            emit updates(path, updatedFiles);
        }
        return;
    }

    QElapsedTimer base;
    base.start();
    QFileInfo fileInfo;
    bool firstTime = true;
    QVector<QPair<QString, FileInfo> > updatedFiles;
    QStringList filesToCheck = files;

    QStringList allFiles;
    if (files.isEmpty()) {
        QDirIterator dirIt(path, QDir::AllEntries | QDir::System | QDir::Hidden);
        while (!abort.load() && dirIt.hasNext()) {
            dirIt.next();
            fileInfo = dirIt.fileInfo();
            allFiles.append(fileInfo.fileName());
            fetch(fileInfo, base, firstTime, updatedFiles, path);
        }
    }
    if (!allFiles.isEmpty())
        emit newListOfFiles(path, allFiles);

    QStringList::const_iterator filesIt = filesToCheck.constBegin();
    while (!abort.load() && filesIt != filesToCheck.constEnd()) {
        fileInfo.setFile(path + QDir::separator() + *filesIt);
        ++filesIt;
        fetch(fileInfo, base, firstTime, updatedFiles, path);
    }
    if (!updatedFiles.isEmpty())
        emit updates(path, updatedFiles);
    emit directoryLoaded(path);
}
Пример #11
0
/** ***************************************************************************/
void Terminal::Extension::rebuildIndex() {
    index_.clear();
    QStringList paths = QString(::getenv("PATH")).split(':', QString::SkipEmptyParts);
    for (const QString &path : paths) {
        QDirIterator dirIt(path);
        while (dirIt.hasNext()) {
            QFileInfo file(dirIt.next());
            if ( file.isExecutable() )
                index_.insert(file.fileName());
        }
    }
}
Пример #12
0
StrList	FileSystemManager::getWorkingDirectoryContents(QString filter)
{
	if (!scnManager->getCurrentLibrary())
		return getDirectoryContents(native(scnManager->getWorkingDirectory()), filter);
	
	StrList files;
	QListIterator<QString> dirIt(scnManager->getCurrentLibrary()->getFolderPaths());
	while (dirIt.hasNext())
	{
		StrList list = getDirectoryContents(dirIt.next(), filter);
		files.insert(files.end(), list.begin(), list.end());
	}
	return files;
}
Пример #13
0
void DecodeValidator::decodeAllImagesInForderWithValidator(QZXing::DecoderFormat enabledDecoder, const QString &folderPath)
{
    QDirIterator dirIt(folderPath, QDirIterator::NoIteratorFlags);

    while (dirIt.hasNext()) {
        dirIt.next();
        QFileInfo fileInfo(dirIt.filePath());
        if (fileInfo.isFile() && fileInfo.suffix() != "txt") {
            QString imagePath = dirIt.filePath();
            QString expectedOutputTextFile = fileInfo.absoluteDir().absolutePath() + "/" + fileInfo.baseName() + ".txt";

            testResults[enabledDecoder].push_back(testDecodeWithExpectedOutput(enabledDecoder, imagePath, expectedOutputTextFile));
        }
    }
}
Пример #14
0
void Professional::writeCategoryImageFiles(QString katigoria){
    StringUtils stringUtils;
    QString categoryImagesPath = categoriesPath + "/" + stringUtils.removeAccents(katigoria).toUpper();
    if(QDir(categoryImagesPath).exists()){
        QDirIterator dirIt(categoryImagesPath,QDirIterator::NoIteratorFlags);
        while (dirIt.hasNext()) {
            dirIt.next();
            if (QFileInfo(dirIt.filePath()).isFile())
                if (QFileInfo(dirIt.filePath()).suffix() == "tif"){
                    professionalFinalXMLWriter.writeEmptyElement("image");
                    professionalFinalXMLWriter.writeAttribute("href","file:///" + dirIt.fileName());
                }
        }
    }
}
Пример #15
0
 bool findFilesRecursive( std::string const& extension, std::string const& path, std::vector<std::string> & results )
 {
   bool found = false;
   boost::filesystem::path searchPath( path );
   DP_ASSERT( directoryExists( searchPath.string() ) );
   for ( boost::filesystem::recursive_directory_iterator dirIt( searchPath ) ; dirIt != boost::filesystem::recursive_directory_iterator() ; ++dirIt )
   {
     if ( _stricmp( dirIt->path().extension().string().c_str(), extension.c_str() ) == 0 )
     {
       results.push_back( dirIt->path().string() );
       found = true;
     }
   }
   return( found );
 }
Пример #16
0
void suiKnowBase::loadSourceDirectory(const QDir& path, bool recursively)
{
    // check if path exist
    if (!path.exists())     SuiExcept(SuiExceptionFileNotFound,
                                      QString("Can't find directory '%1'").arg(path.absolutePath()),
                                      "void suiKnowBase::loadSourceDirectory(const QDir& path, bool recursively)");

    QDirIterator dirIt(path, recursively ? QDirIterator::Subdirectories : QDirIterator::NoIteratorFlags);
    while (dirIt.hasNext())
    {
        QFileInfo finfo(dirIt.next());

        if (availableFormats().contains(finfo.suffix(), Qt::CaseInsensitive))
            loadSourceFile(finfo.absoluteFilePath());
    }

}
Пример #17
0
/**
 * @brief TokenMenu::initTokenMenuPush Initializes the TokenMenu and the database with resources
 * coming from the "resource/TokenMenu/" folder.
 */
void TokenMenu::initTokenMenuPush() {
    QDirIterator dirIt("resource/TokenMenu", QDirIterator::Subdirectories);

    while(dirIt.hasNext()) {
        QString filePath = dirIt.next();
        QString suffix = dirIt.fileInfo().suffix();

        if (!suffix.isEmpty()) {
            QString name = dirIt.fileInfo().baseName();
            bool special = filePath.contains("Special");

            // TODO hard coded size
            TokenItem *item = addToken(name, filePath, 1, special);

            item->setHidden(special);
        }
    }
}
Пример #18
0
void ResultsParser::run()
{
    boost::filesystem::directory_iterator dirItEnd;
    for(boost::filesystem::directory_iterator dirIt(DEFAULT_RESULTS_DIR); dirIt != dirItEnd; ++dirIt)
    {
        if(!boost::filesystem::is_regular_file(dirIt->status()))
            continue;

        std::string filename = dirIt->path().string();
        if(filename.find(REPORT_STRING) == std::string::npos)
            continue;

        processOneFile(filename);
    }

    printResults();
    LOG_INFO("====================== FINISHED ======================");
}
Пример #19
0
void QtStyleManager::AddStyles(const QString& path)
{
  QDirIterator dirIt(path);
  while (dirIt.hasNext())
  {
    QString current = dirIt.next();
    QFileInfo info = dirIt.fileInfo();
    if (info.isFile() && info.isReadable())
    {
      QString fileName = info.fileName();
      if (fileName.endsWith("-tab.qss") || fileName.endsWith("-activetab.qss"))
        continue;

      if (fileName.endsWith(".qss"))
        AddStyle(current);
    }
  }
}
Пример #20
0
void DataSet::LoadData(unsigned int dim,QString parent_folder)
{
    QStringList all_paths;
    QDirIterator dirIt(parent_folder,QDirIterator::Subdirectories);
    while (dirIt.hasNext()) {
        dirIt.next();
        if (QFileInfo(dirIt.filePath()).isFile())
           all_paths <<dirIt.filePath();
    }

    _data_count = all_paths.size();
    _data.resize(_data_count);

    for (int i = 0; i<_data_count; i++){
        _data[i] = Data();
        _data[i].LoadData(all_paths[i],dim);
    }
}
void ViewOtherFiles::setOtherFileList()
{
    QString createOtherFilePath=basicPath;
    createOtherFilePath.append("Other");
    qDebug()<<createOtherFilePath<<"dddddddddd";
    QDirIterator dirIt(createOtherFilePath,QDirIterator::Subdirectories);
    while (dirIt.hasNext()) {
        dirIt.next();
        if (QFileInfo(dirIt.filePath()).isFile())
        {
            ui->lWFileList->addItem(dirIt.filePath().mid(dirIt.filePath().lastIndexOf("/")+1));

        }
            //if (QFileInfo(dirIt.filePath()).suffix() == "txt")
            //    qDebug()<<dirIt.filePath();
    }

}
Пример #22
0
//
// service for directory file list
//
QStringList getFileList(QString folder, QString suffix, bool recursive)
{
  QStringList fileList;
  QString path(QDir(folder).absolutePath());
  QDirIterator dirIt(path, QDirIterator::Subdirectories);
  while (dirIt.hasNext())
  {
    dirIt.next();
    if ((recursive) || (dirIt.fileInfo().absolutePath() == path))
    {
      QString file(dirIt.fileInfo().absoluteFilePath());
      if (QFileInfo(dirIt.filePath()).isFile())
        if (QFileInfo(dirIt.filePath()).suffix() == suffix)
          fileList.append(dirIt.filePath());
    }
  }
  qSort(fileList);
  return fileList;
}
Пример #23
0
bool LuaList::loadAll()
{
    std::cout << "[Lua] loading all script files from " << _filePath.toStdString() << std::endl;
    // get everything with ".lua"
    QStringList files;
    QDirIterator dirIt(_filePath);
    while (dirIt.hasNext()) {
        dirIt.next();
        if (QFileInfo(dirIt.filePath()).isFile())
            if (QFileInfo(dirIt.filePath()).suffix() == "lua")
                files.append(dirIt.fileName());
    }
	std::cout << "[Lua] loading all script files from " << _templateFilePath.toStdString() << std::endl;
	// get everything with ".lua"
	QDirIterator dirIt2(_templateFilePath);
	while (dirIt2.hasNext()) {
		dirIt2.next();
		if (QFileInfo(dirIt2.filePath()).isFile())
			if (QFileInfo(dirIt2.filePath()).suffix() == "lua")
				if(!files.contains(dirIt2.fileName(), Qt::CaseInsensitive))
					files.append(dirIt2.fileName());
	}


    if(!_luaList.empty())
        // clear list before loading
        clearList();

    // load lua files
    for( QStringList::iterator it = files.begin(); it != files.end(); ++it)
    {
        LuaContainer* c = new LuaContainer();
        std::cout << "[Lua] loading file " << it->toStdString() << " ..." << std::endl;
        if(load((*it), c))
            _luaList.push_back(c);
        else
            std::cerr << "[Lua] can't load file " << it->toStdString() << std::endl;
    }
    if(_luaList.empty())
        return false;
    else
        return true;
}
Пример #24
0
void KNotePrintSelectThemeComboBox::loadThemes()
{
    clear();
    const QString defaultTheme = KNotesGlobalConfig::self()->theme();

    const QString relativePath = QStringLiteral("knotes/print/themes/");
    QStringList themesDirectories = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, relativePath, QStandardPaths::LocateDirectory);
    if (themesDirectories.count() < 2) {
        //Make sure to add local directory
        const QString localDirectory = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + relativePath;
        if (!themesDirectories.contains(localDirectory)) {
            themesDirectories.append(localDirectory);
        }
    }

    Q_FOREACH (const QString &directory, themesDirectories) {
        QDirIterator dirIt(directory, QStringList(), QDir::AllDirs | QDir::NoDotAndDotDot);
        QStringList alreadyLoadedThemeName;
        while (dirIt.hasNext()) {
            dirIt.next();
            const QString themeInfoFile = dirIt.filePath() + QDir::separator() + QLatin1String("theme.desktop");
            KConfig config(themeInfoFile);
            KConfigGroup group(&config, QStringLiteral("Desktop Entry"));
            QString name = group.readEntry("Name", QString());
            if (name.isEmpty()) {
                continue;
            }
            if (alreadyLoadedThemeName.contains(name)) {
                int i = 2;
                const QString originalName(name);
                while (alreadyLoadedThemeName.contains(name)) {
                    name = originalName + QStringLiteral(" (%1)").arg(i);
                    ++i;
                }
            }
            const QString printThemePath(dirIt.filePath() + QDir::separator());
            if (!printThemePath.isEmpty()) {
                alreadyLoadedThemeName << name;
                addItem(name, printThemePath);
            }
        }
    }
Пример #25
0
void
Directory::scan() {
	reset();

	Poco::DirectoryIterator dirIt(_directoryPath);
	Poco::DirectoryIterator dirEnd;
	for (; dirIt != dirEnd; ++dirIt) {
		if (dirIt->isFile()) {
			File* foundFile = new File(*dirIt);
			_files.push_back(foundFile);
		} else if (dirIt->isDirectory()) {
			Directory* foundDir = new Directory(*dirIt);
			foundDir->scan();
			_subDirectories.push_back(foundDir);
		} else {
			TITANIC_WARN(Log, "Object is not a file or directory [" << dirIt->path() << "]");
		}
	}

}
Пример #26
0
void DecodeValidator::executeTests(const QString &folderPath)
{
    QDirIterator dirIt(folderPath, QDirIterator::NoIteratorFlags);

    while (dirIt.hasNext()) {
        dirIt.next();
        QFileInfo fileInfo(dirIt.filePath());
        if (fileInfo.isDir()) {
            QString subfolderPath = dirIt.filePath();
            QString subfolderName = dirIt.fileName();

            QZXing::DecoderFormat decoderFormat = getDecoderForFolder(subfolderName);

            qDebug() << "Decoding folder: " << subfolderPath;
            if(decoderFormat != QZXing::DecoderFormat_None)
                decodeAllImagesInForderWithValidator(decoderFormat, subfolderPath);
        }
    }

    printResults();
}
// Read a directory and return the entries as a string list
fileNameList readDir
(
    const fileName& directory,
    const fileName::Type type,
    const bool filtergz
)
{
    // Initial filename list size
    // also used as increment if initial size found to be insufficient
    const int maxNnames = 100;

    if (MSwindows::debug)
    {
        Info<< "readDir(const fileName&, const fileType, const bool filtergz)"
            << " : reading directory " << directory << endl;
    }

    // Setup empty string list MAXTVALUES long
    fileNameList dirEntries(maxNnames);

    // Temporary variables and counters
    label nEntries = 0;

    MSwindows::DirectoryIterator dirIt(directory);

    if (dirIt.isValid())
    {
        while (dirIt.hasNext())
        {
            const fileName & fName = dirIt.next();

            // ignore files begining with ., i.e. '.', '..' and '.*'
            if (fName.size() > 0 && fName[size_t(0)] != '.')
            {
                word fileNameExt = fName.ext();

                if
                (
                    (type == fileName::DIRECTORY)
                    ||
                    (
                        type == fileName::FILE
                        && fName[fName.size()-1] != '~'
                        && fileNameExt != "bak"
                        && fileNameExt != "BAK"
                        && fileNameExt != "old"
                        && fileNameExt != "save"
                    )
                )
                {
                    if ((directory/fName).type() == type)
                    {
                        if (nEntries >= dirEntries.size())
                        {
                            dirEntries.setSize(dirEntries.size() + maxNnames);
                        }

                        if (filtergz && fileNameExt == "gz")
                        {
                            dirEntries[nEntries++] = fName.lessExt();
                        }
                        else
                        {
                            dirEntries[nEntries++] = fName;
                        }
                    }
                }
            }
        }
    }
    else if (MSwindows::debug)
    {
        Info<< "readDir(const fileName&, const fileType, "
            "const bool filtergz) : cannot open directory "
            << directory << endl;
    }

    // Reset the length of the entries list
    dirEntries.setSize(nEntries);

    return dirEntries;
}
Пример #28
0
std::vector<FileData> getFileDataFrom(const FS_NAMESPACE::path & inPath, const FS_NAMESPACE::path & outPath, const FS_NAMESPACE::path & parentDir, const bool recurse)
{
	// get all files from directory
	std::vector<FileData> files;
	// check for infinite symlinks
	if (FS_NAMESPACE::is_symlink(inPath))
	{
		// check if the symlink points somewhere in the path. this would recurse
		if (inPath.string().find(FS_NAMESPACE::canonical(inPath).string()) == 0)
		{
			std::cout << "Warning: Path " << inPath << " contains recursive symlink! Skipping." << std::endl;
			return files;
		}
	}
	// iterate through source directory searching for files
	const FS_NAMESPACE::directory_iterator dirEnd;
	for (FS_NAMESPACE::directory_iterator fileIt(inPath); fileIt != dirEnd; ++fileIt)
	{
		FS_NAMESPACE::path filePath = (*fileIt).path();
		if (!FS_NAMESPACE::is_directory(filePath))
		{
			if (beVerbose)
			{
				std::cout << "Found input file " << filePath << std::endl;
			}
			// add file to list
			FileData temp;
			temp.inPath = filePath;
			// replace dots in file name with '_' and add a .c/.cpp extension
			std::string newFileName = filePath.filename().generic_string();
			std::replace(newFileName.begin(), newFileName.end(), '.', '_');
			if (useC)
			{
				newFileName.append(".c");
			}
			else
			{
				newFileName.append(".cpp");
			}
			// remove parent directory of file from path for internal name. This could surely be done in a safer way
			FS_NAMESPACE::path subPath(filePath.generic_string().substr(parentDir.generic_string().size() + 1));
			// add a ":/" before the name to mark internal resources (Yes. Hello Qt!)
			temp.internalName = ":/" + subPath.generic_string();
			// add subdir below parent path to name to enable multiple files with the same name
			std::string subDirString(subPath.remove_filename().generic_string());
			if (!subDirString.empty())
			{
				// replace dir separators by underscores
				std::replace(subDirString.begin(), subDirString.end(), '/', '_');
				// add in front of file name
				newFileName = subDirString + "_" + newFileName;
			}
			// build new output file name
			temp.outPath = outPath / newFileName;
			if (beVerbose)
			{
				std::cout << "Internal name will be \"" << temp.internalName << "\"" << std::endl;
				std::cout << "Output path is " << temp.outPath << std::endl;
			}
			// get file size
			try
			{
				temp.size = static_cast<uint64_t>(FS_NAMESPACE::file_size(filePath));
				if (beVerbose)
				{
					std::cout << "Size is " << temp.size << " bytes." << std::endl;
				}
			}
			catch (...)
			{
				std::cout << "Error: Failed to get size of " << filePath << "!" << std::endl;
				temp.size = 0;
			}
			// add file to list
			files.push_back(temp);
		}
	}
	// does the user want subdirectories?
	if (recurse)
	{
		// iterate through source directory again searching for directories
		for (FS_NAMESPACE::directory_iterator dirIt(inPath); dirIt != dirEnd; ++dirIt)
		{
			FS_NAMESPACE::path dirPath = (*dirIt).path();
			if (FS_NAMESPACE::is_directory(dirPath))
			{
				if (beVerbose)
				{
					std::cout << "Found subdirectory " << dirPath << std::endl;
				}
				// subdirectory found. recurse.
				std::vector<FileData> subFiles = getFileDataFrom(dirPath, outPath, parentDir, recurse);
				// add returned result to file list
				files.insert(files.end(), subFiles.cbegin(), subFiles.cend());
			}
		}
	}
	// return result
	return files;
}
// Remove a dirctory and it's contents
bool rmDir(const fileName& directory)
{
    if (MSwindows::debug)
    {
        Info<< "rmdir(const fileName&) : "
            << "removing directory " << directory << endl;
    }

    bool success = true;

    // Need to destroy DirectorIterator prior to
    // removing directory otherwise fails on Windows XP
    {
        MSwindows::DirectoryIterator dirIt(directory);

        while (success && dirIt.hasNext())
        {
            const fileName & fName = dirIt.next();

            if (fName != "." && fName != "..")
            {
                fileName path = directory/fName;

                if (path.type() == fileName::DIRECTORY)
                {
                    success = rmDir(path);

                    if (!success)
                    {
                        WarningIn("rmdir(const fileName&)")
                                << "failed to remove directory " << fName
                                << " while removing directory " << directory
                                << endl;
                    }
                }
                else
                {
                    success = rm(path);

                    if (!success)
                    {
                        WarningIn("rmdir(const fileName&)")
                                << "failed to remove file " << fName
                                << " while removing directory " << directory
                                << endl;
                    }
                }
            }
        }
    }

    if (success)
    {
        success = ::RemoveDirectory(directory.c_str());

        if (!success)
        {
            WarningIn("rmdir(const fileName&)")
                    << "failed to remove directory " << directory << endl;
        }
    }

    return success;
}
Пример #30
0
// We return the UserSettings here because we have to make changes to the
// configuration and the location of the file may change between releases.
UserSettingsPointer Upgrade::versionUpgrade(const QString& settingsPath) {

/*  Pre-1.7.0:
*
*   Since we didn't store version numbers in the config file prior to 1.7.0,
*   we check to see if the user is upgrading if his config files are in the old location,
*   since we moved them in 1.7.0. This code takes care of moving them.
*/

    QDir oldLocation = QDir(QDir::homePath());
#ifdef __WINDOWS__
    QFileInfo* pre170Config = new QFileInfo(oldLocation.filePath("mixxx.cfg"));
#else
    QFileInfo* pre170Config = new QFileInfo(oldLocation.filePath(".mixxx.cfg"));
#endif

    if (pre170Config->exists()) {

        // Move the files to their new location
        QDir newLocation = QDir(settingsPath);

        if (!newLocation.exists()) {
            qDebug() << "Creating new settings directory" << newLocation.absolutePath();
            newLocation.mkpath(".");
        }

        QString errorText = "Error moving your %1 file %2 to the new location %3: \n";

#ifdef __WINDOWS__
        QString oldFilePath = oldLocation.filePath("mixxxtrack.xml");
#else
        QString oldFilePath = oldLocation.filePath(".mixxxtrack.xml");
#endif

        QString newFilePath = newLocation.filePath("mixxxtrack.xml");
        QFile* oldFile = new QFile(oldFilePath);
        if (oldFile->exists()) {
            if (oldFile->copy(newFilePath)) {
                oldFile->remove();
            }
            else {
                if (oldFile->error()==14) qDebug() << errorText.arg("library", oldFilePath, newFilePath) << "The destination file already exists.";
                else qDebug() << errorText.arg("library", oldFilePath, newFilePath) << "Error #" << oldFile->error();
            }
        }
        delete oldFile;

#ifdef __WINDOWS__
        oldFilePath = oldLocation.filePath("mixxxbpmschemes.xml");
#else
        oldFilePath = oldLocation.filePath(".mixxxbpmscheme.xml");
#endif
        newFilePath = newLocation.filePath("mixxxbpmscheme.xml");
        oldFile = new QFile(oldFilePath);
        if (oldFile->exists()) {
            if (oldFile->copy(newFilePath))
                oldFile->remove();
            else {
                if (oldFile->error()==14) qDebug() << errorText.arg("settings", oldFilePath, newFilePath) << "The destination file already exists.";
                else qDebug() << errorText.arg("settings", oldFilePath, newFilePath) << "Error #" << oldFile->error();
            }
        }
        delete oldFile;
#ifdef __WINDOWS__
        oldFilePath = oldLocation.filePath("MixxxMIDIBindings.xml");
#else
        oldFilePath = oldLocation.filePath(".MixxxMIDIBindings.xml");
#endif
        newFilePath = newLocation.filePath("MixxxMIDIBindings.xml");
        oldFile = new QFile(oldFilePath);
        if (oldFile->exists()) {
            qWarning() << "The MIDI mapping file format has changed in this version of Mixxx. You will need to reconfigure your MIDI controller. See the Wiki for full details on the new format.";
            if (oldFile->copy(newFilePath))
                oldFile->remove();
            else {
                if (oldFile->error()==14) qDebug() << errorText.arg("MIDI mapping", oldFilePath, newFilePath) << "The destination file already exists.";
                else qDebug() << errorText.arg("MIDI mapping", oldFilePath, newFilePath) << "Error #" << oldFile->error();
            }
        }
        // Tidy up
        delete oldFile;
#ifdef __WINDOWS__
        QFile::remove(oldLocation.filePath("MixxxMIDIDevice.xml")); // Obsolete file, so just delete it
#else
        QFile::remove(oldLocation.filePath(".MixxxMIDIDevice.xml")); // Obsolete file, so just delete it
#endif

#ifdef __WINDOWS__
        oldFilePath = oldLocation.filePath("mixxx.cfg");
#else
        oldFilePath = oldLocation.filePath(".mixxx.cfg");
#endif
        newFilePath = newLocation.filePath(SETTINGS_FILE);
        oldFile = new QFile(oldFilePath);
        if (oldFile->copy(newFilePath))
            oldFile->remove();
        else {
                if (oldFile->error()==14) qDebug() << errorText.arg("configuration", oldFilePath, newFilePath) << "The destination file already exists.";
                else qDebug() << errorText.arg("configuration", oldFilePath, newFilePath) << "Error #" << oldFile->error();
            }
        delete oldFile;

    }
    // Tidy up
    delete pre170Config;
    // End pre-1.7.0 code


/***************************************************************************
*                           Post-1.7.0 upgrade code
*
*   Add entries to the IF ladder below if anything needs to change from the
*   previous to the current version. This allows for incremental upgrades
*   in case a user upgrades from a few versions prior.
****************************************************************************/

    // Read the config file from home directory
    UserSettingsPointer config(new ConfigObject<ConfigValue>(
        QDir(settingsPath).filePath(SETTINGS_FILE)));

    QString configVersion = config->getValueString(ConfigKey("[Config]","Version"));

    if (configVersion.isEmpty()) {

#ifdef __APPLE__
        qDebug() << "Config version is empty, trying to read pre-1.9.0 config";
        // Try to read the config from the pre-1.9.0 final directory on OS X (we moved it in 1.9.0 final)
        QScopedPointer<QFile> oldConfigFile(new QFile(QDir::homePath().append("/").append(".mixxx/mixxx.cfg")));
        if (oldConfigFile->exists() && ! CmdlineArgs::Instance().getSettingsPathSet()) {
            qDebug() << "Found pre-1.9.0 config for OS X";
            // Note: We changed SETTINGS_PATH in 1.9.0 final on OS X so it must be hardcoded to ".mixxx" here for legacy.
            config = UserSettingsPointer(new ConfigObject<ConfigValue>(
                QDir::homePath().append("/.mixxx/mixxx.cfg")));
            // Just to be sure all files like logs and soundconfig go with mixxx.cfg
            // TODO(XXX) Trailing slash not needed anymore as we switches from String::append
            // to QDir::filePath elsewhere in the code. This is candidate for removal.
            CmdlineArgs::Instance().setSettingsPath(QDir::homePath().append("/.mixxx/"));
            configVersion = config->getValueString(ConfigKey("[Config]","Version"));
        }
        else {
#elif __WINDOWS__
        qDebug() << "Config version is empty, trying to read pre-1.12.0 config";
        // Try to read the config from the pre-1.12.0 final directory on Windows (we moved it in 1.12.0 final)
        QScopedPointer<QFile> oldConfigFile(new QFile(QDir::homePath().append("/Local Settings/Application Data/Mixxx/mixxx.cfg")));
        if (oldConfigFile->exists() && ! CmdlineArgs::Instance().getSettingsPathSet()) {
            qDebug() << "Found pre-1.12.0 config for Windows";
            // Note: We changed SETTINGS_PATH in 1.12.0 final on Windows so it must be hardcoded to "Local Settings/Application Data/Mixxx/" here for legacy.
            config = UserSettingsPointer(new ConfigObject<ConfigValue>(
                QDir::homePath().append("/Local Settings/Application Data/Mixxx/mixxx.cfg")));
            // Just to be sure all files like logs and soundconfig go with mixxx.cfg
            // TODO(XXX) Trailing slash not needed anymore as we switches from String::append
            // to QDir::filePath elsewhere in the code. This is candidate for removal.
            CmdlineArgs::Instance().setSettingsPath(QDir::homePath().append("/Local Settings/Application Data/Mixxx/"));
            configVersion = config->getValueString(ConfigKey("[Config]","Version"));
        }
        else {
#endif
            // This must have been the first run... right? :)
            qDebug() << "No version number in configuration file. Setting to" << MIXXX_VERSION;
            config->set(ConfigKey("[Config]","Version"), ConfigValue(MIXXX_VERSION));
            m_bFirstRun = true;
            return config;
#ifdef __APPLE__
        }
#elif __WINDOWS__
        }
#endif
    }

    // If it's already current, stop here
    if (configVersion == MIXXX_VERSION) {
        qDebug() << "Configuration file is at the current version" << MIXXX_VERSION;
        return config;
    }

    // Allows for incremental upgrades in case someone upgrades from a few versions prior
    // (I wish we could do a switch on a QString.)
    /*
    // Examples, since we didn't store the version number prior to v1.7.0
    if (configVersion.startsWith("1.6.0")) {
        qDebug() << "Upgrading from v1.6.0 to 1.6.1...";
        // Upgrade tasks go here
        configVersion = "1.6.1";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.6.1"));
    }
    if (configVersion.startsWith("1.6.1")) {
        qDebug() << "Upgrading from v1.6.1 to 1.7.0...";
        // Upgrade tasks go here
        configVersion = "1.7.0";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.7.0"));
    }
    */

    // We use the following blocks to detect if this is the first time
    // you've run the latest version of Mixxx. This lets us show
    // the promo tracks stats agreement stuff for all users that are
    // upgrading Mixxx.

    if (configVersion.startsWith("1.7")) {
        qDebug() << "Upgrading from v1.7.x...";
        // Upgrade tasks go here
        // Nothing to change, really
        configVersion = "1.8.0";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.8.0"));
    }

    if (configVersion.startsWith("1.8.0~beta1") ||
        configVersion.startsWith("1.8.0~beta2")) {
        qDebug() << "Upgrading from v1.8.0~beta...";
        // Upgrade tasks go here
        configVersion = "1.8.0";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.8.0"));
    }
    if (configVersion.startsWith("1.8") || configVersion.startsWith("1.9.0beta1")) {
        qDebug() << "Upgrading from" << configVersion << "...";
        // Upgrade tasks go here
#ifdef __APPLE__
        QString OSXLocation180 = QDir::homePath().append("/").append(".mixxx");
        QString OSXLocation190 = settingsPath;
        QDir newOSXDir(OSXLocation190);
        newOSXDir.mkpath(OSXLocation190);

        QList<QPair<QString, QString> > dirsToMove;
        dirsToMove.push_back(QPair<QString, QString>(OSXLocation180, OSXLocation190));
        dirsToMove.push_back(QPair<QString, QString>(OSXLocation180 + "/midi", OSXLocation190 + "midi"));
        dirsToMove.push_back(QPair<QString, QString>(OSXLocation180 + "/presets", OSXLocation190 + "presets"));

        QListIterator<QPair<QString, QString> > dirIt(dirsToMove);
        QPair<QString, QString> curPair;
        while (dirIt.hasNext())
        {
            curPair = dirIt.next();
            qDebug() << "Moving" << curPair.first << "to" << curPair.second;
            QDir oldSubDir(curPair.first);
            QDir newSubDir(curPair.second);
            newSubDir.mkpath(curPair.second); // Create the new destination directory

            QStringList contents = oldSubDir.entryList(QDir::Files | QDir::NoDotAndDotDot);
            QStringListIterator it(contents);
            QString cur;
            // Iterate over all the files in the source directory and copy them to the dest dir.
            while (it.hasNext())
            {
                cur = it.next();
                QString src = curPair.first + "/" + cur;
                QString dest = curPair.second + "/" + cur;
                qDebug() << "Copying" << src << "to" << dest;
                if (!QFile::copy(src, dest))
                {
                    qDebug() << "Failed to move file during upgrade.";
                }
            }

            // Rename the old directory.
            newOSXDir.rename(OSXLocation180, OSXLocation180 + "-1.8");
        }
        // Reload the configuration file from the new location.
        // (We want to make sure we save to the new location...)
        config = UserSettingsPointer(new ConfigObject<ConfigValue>(
            QDir(settingsPath).filePath(SETTINGS_FILE)));
#endif
        configVersion = "1.9.0";
        config->set(ConfigKey("[Config]","Version"), ConfigValue("1.9.0"));
    }
    if (configVersion.startsWith("1.9") || configVersion.startsWith("1.10")) {
        qDebug() << "Upgrading from v1.9.x/1.10.x...";

        bool successful = true;

        qDebug() << "Copying midi/ to controllers/";
        QString midiPath = legacyUserPresetsPath(config);
        QString controllerPath = userPresetsPath(config);
        QDir oldDir(midiPath);
        QDir newDir(controllerPath);
        newDir.mkpath(controllerPath);  // create the new directory

        QStringList contents = oldDir.entryList(QDir::Files | QDir::NoDotAndDotDot);
        QStringListIterator it(contents);
        QString cur;
        // Iterate over all the files in the source directory and copy them to the dest dir.
        while (it.hasNext()) {
            cur = it.next();
            if (newDir.exists(cur)) {
                qDebug() << cur << "already exists in"
                         << controllerPath << "Skipping.";
                continue;
            }
            QString src = oldDir.absoluteFilePath(cur);
            QString dest = newDir.absoluteFilePath(cur);
            qDebug() << "Copying" << src << "to" << dest;
            if (!QFile::copy(src, dest)) {
                qDebug() << "Failed to copy file during upgrade.";
                successful = false;
            }
        }

        bool reanalyze_choice = askReanalyzeBeats();
        BeatDetectionSettings bpmSettings(config);
        bpmSettings.setReanalyzeWhenSettingsChange(reanalyze_choice);

        if (successful) {
            qDebug() << "Upgrade Successful";
            configVersion = "1.11.0";
            config->set(ConfigKey("[Config]","Version"),
                        ConfigValue(configVersion));
        } else {
            qDebug() << "Upgrade Failed";
        }
    }

    if (configVersion.startsWith("1.11")) {
        qDebug() << "Upgrading from v1.11.x...";
        bool successful = false;
        {
            MixxxDb mixxxDb(config);
            const mixxx::DbConnectionPooler dbConnectionPooler(
                    mixxxDb.connectionPool());
            if (dbConnectionPooler.isPooling()) {
                QSqlDatabase dbConnection = mixxx::DbConnectionPooled(mixxxDb.connectionPool());
                DEBUG_ASSERT(dbConnection.isOpen());
                if (MixxxDb::initDatabaseSchema(dbConnection)) {
                    TrackCollection tc(config);
                    tc.connectDatabase(dbConnection);

                    // upgrade to the multi library folder settings
                    QString currentFolder = config->getValueString(PREF_LEGACY_LIBRARY_DIR);
                    // to migrate the DB just add the current directory to the new
                    // directories table
                    // NOTE(rryan): We don't have to ask for sandbox permission to this
                    // directory because the normal startup integrity check in Library will
                    // notice if we don't have permission and ask for access. Also, the
                    // Sandbox isn't setup yet at this point in startup because it relies on
                    // the config settings path and this function is what loads the config
                    // so it's not ready yet.
                    successful = tc.getDirectoryDAO().addDirectory(currentFolder);

                    tc.disconnectDatabase();
                }
            }
        }

        // ask for library rescan to activate cover art. We can later ask for
        // this variable when the library scanner is constructed.
        m_bRescanLibrary = askReScanLibrary();

        // Versions of mixxx until 1.11 had a hack that multiplied gain by 1/2,
        // which was compensation for another hack that set replaygain to a
        // default of 6.  We've now removed all of the hacks, so subtracting
        // 6 from everyone's replay gain should keep things consistent for
        // all users.
        int oldReplayGain = config->getValue(
                ConfigKey("[ReplayGain]", "InitialReplayGainBoost"), 6);
        int newReplayGain = math_max(-6, oldReplayGain - 6);
        config->set(ConfigKey("[ReplayGain]", "InitialReplayGainBoost"),
                    ConfigValue(newReplayGain));

        // if everything until here worked fine we can mark the configuration as
        // updated
        if (successful) {
            configVersion = MIXXX_VERSION;
            config->set(ConfigKey("[Config]","Version"), ConfigValue(MIXXX_VERSION));
        }
        else {
            qDebug() << "Upgrade failed!\n";
        }
    }

    if (configVersion.startsWith("1.12") ||
        configVersion.startsWith("2.0") ||
        configVersion.startsWith("2.1.0")) {
        // No special upgrade required, just update the value.
        configVersion = MIXXX_VERSION;
        config->set(ConfigKey("[Config]","Version"), ConfigValue(MIXXX_VERSION));
    }

    if (configVersion == MIXXX_VERSION) qDebug() << "Configuration file is now at the current version" << MIXXX_VERSION;
    else {
        qWarning() << "Configuration file is at version" << configVersion
                   << "instead of the current" << MIXXX_VERSION;
    }

    return config;
}