void ApplicationPlugins::updatePlugins()
{
    qDeleteAll(m_plugins);
    m_plugins.clear();

    for (QString path: m_searchPaths) {
        if (!QDir(path).exists())
        {
            continue;
        }

        QDirIterator dirIterator(path, QDirIterator::FollowSymlinks | QDirIterator::Subdirectories);
        while (dirIterator.hasNext())
        {
            dirIterator.next();
            QFileInfo info = dirIterator.fileInfo();
            if (info.isFile() && info.fileName() == "plugin.ini")
            {
                readPluginFile(info.filePath());
            }
        }
    }

    emit pluginsChanged(QQmlListProperty<ApplicationPluginItem>(this, m_plugins));
}
Esempio n. 2
0
QStringList KateProjectWorker::filesFromDirectory(const QDir &_dir, bool recursive, const QStringList &filters)
{
    QStringList files;

    QDir dir(_dir);
    dir.setFilter(QDir::Files);

    if (!filters.isEmpty()) {
        dir.setNameFilters(filters);
    }

    /**
     * construct flags for iterator
     */
    QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags;
    if (recursive) {
        flags = flags | QDirIterator::Subdirectories;
    }

    /**
     * create iterator and collect all files
     */
    QDirIterator dirIterator(dir, flags);
    while (dirIterator.hasNext()) {
        dirIterator.next();
        files.append(dirIterator.filePath());
    }

    return files;
}
Esempio n. 3
0
QString uavCore::getFolder( const QString &folder, const QString &name )
{
	QDir dir(folder);

	//判断路径是否存在
	if (!dir.exists())
	{
		return "";
	}

	QDirIterator dirIterator(folder, 
		QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot, 
		QDirIterator::Subdirectories);

	while (dirIterator.hasNext())
	{
		dirIterator.next();
		QFileInfo file_info = dirIterator.fileInfo();
		qDebug() << file_info.fileName() << "::" << file_info.baseName();
		if (file_info.baseName() == name)
		{
			return file_info.filePath();
		}
	}

	return "";
}
Esempio n. 4
0
void GenTool::readInFiles(const QString& sourcePath)
{
	QDirIterator dirIterator(sourcePath, cppFilter_, QDir::Files, QDirIterator::Subdirectories);
	auto sources = std::make_shared<std::vector<std::string>>();
	while (dirIterator.hasNext()) sources->push_back(dirIterator.next().toStdString());
	sourcesMap_.insert(sourcePath, sources);
}
Esempio n. 5
0
// Parse all images in the tree and genarate sprite data
void SpriteEditor::onUpdateSpritesSelected()
{
    if (mSpriteData.mResourceDirPath != "")
    {
        QStringList filters;
        filters<<"*.png";
        QDirIterator dirIterator(mSpriteData.mResourceDirPath,
                                 filters,
                                 QDir::Files|QDir::NoSymLinks,
                                 QDirIterator::Subdirectories);

        mSpriteData.refreshSpriteData();
        while(dirIterator.hasNext())
        {
            // make sure to call next, failing todo so will result in infinite loop
            dirIterator.next();

            QString relativeFilepath = dirIterator.filePath();
            relativeFilepath.replace(mSpriteData.mResourceDirPath, "");

            mSpriteData.loadKey(relativeFilepath);
        }

        mChanged = true;
    }
}
Esempio n. 6
0
void Tests::basicTests()
{
    // Some basic tests to save our COMBINE archive either directly or to a
    // different file and checking that its contents is sound

    QString otherFileName = OpenCOR::Core::temporaryFileName();

    doBasicTests();
    doBasicTests(otherFileName);

    // Check that we can load our other COMBINE archive and save it in yet
    // another file

    OpenCOR::COMBINESupport::CombineArchive otherCombineArchive(otherFileName);

    QString yetAnotherFileName = OpenCOR::Core::temporaryFileName();

    QVERIFY(otherCombineArchive.load());
    QVERIFY(otherCombineArchive.isValid());
    QVERIFY(otherCombineArchive.save(yetAnotherFileName));

    // Unzip our two COMBINE archives and make sure that their contents is the
    // same
    // Note: the original plan was to check that the SHA-1 value of the two
    //       files was the same, but the fact is that the ZIP file format
    //       contains various date and time information, so the SHA-1 value of
    //       two files may be different...

    QTemporaryDir temporaryDir;
    QString otherDir = temporaryDir.path()+"/otherDir";
    QString yetAnotherDir = temporaryDir.path()+"/yetAnotherDir";
    OpenCOR::ZIPSupport::QZipReader otherZipReader(otherFileName);
    OpenCOR::ZIPSupport::QZipReader yetAnotherZipReader(yetAnotherFileName);

    QVERIFY(otherZipReader.extractAll(otherDir));
    QVERIFY(yetAnotherZipReader.extractAll(yetAnotherDir));

    QDirIterator dirIterator(otherDir, QStringList() << "*",
                             QDir::Files, QDirIterator::Subdirectories);

    while (dirIterator.hasNext()) {
        QString otherFileName = dirIterator.next();
        QString yetAnotherFileName = otherFileName.replace(otherDir, yetAnotherDir);
        QByteArray otherFileContents;
        QByteArray yetAnotherFileContents;

        QVERIFY(OpenCOR::Core::readFileContentsFromFile(otherFileName, otherFileContents));
        QVERIFY(OpenCOR::Core::readFileContentsFromFile(yetAnotherFileName, yetAnotherFileContents));

        QCOMPARE(OpenCOR::Core::sha1(otherFileContents),
                 OpenCOR::Core::sha1(yetAnotherFileContents));
    }

    // Clean up after ourselves

    QFile::remove(otherFileName);
    QFile::remove(yetAnotherFileName);
}
Esempio n. 7
0
File: main.cpp Progetto: Suneal/qt
void traverse(const QString &path)
{
    QDirIterator dirIterator(path, QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files | QDir::NoSymLinks);

    while (dirIterator.hasNext()) {
        QString filePath = dirIterator.next();
        if (filePath.endsWith(".cpp"))
            check(filePath);
        else if (QFileInfo(filePath).isDir())
            traverse(filePath); // recurse
    }
}
/** Reimplemented with a QDirIterator to quick count tracks. */
int FileSystemTreeView::countAll(const QModelIndexList &indexes) const
{
	int files = 0;
	for (QModelIndex index : indexes) {
		QDirIterator dirIterator(_fileSystemModel->fileInfo(index).absoluteFilePath(), QDirIterator::Subdirectories);
		while (dirIterator.hasNext()) {
			if (QFileInfo(dirIterator.next()).isFile()) {
				files++;
			}
		}
	}
	return files;
}
Esempio n. 9
0
/// Internal (potentially recursive) implementation of get_file_list.
static void get_file_list_subdir(const SkString& rootDir, const SkString& subDir,
                                 const StringArray& matchSubstrings,
                                 const StringArray& nomatchSubstrings,
                                 bool recurseIntoSubdirs, FileArray *files) {
    bool isSubDirEmpty = subDir.isEmpty();
    SkString dir(rootDir);
    if (!isSubDirEmpty) {
        dir.append(PATH_DIV_STR);
        dir.append(subDir);
    }

    // Iterate over files (not directories) within dir.
    SkOSFile::Iter fileIterator(dir.c_str());
    SkString fileName;
    while (fileIterator.next(&fileName, false)) {
        if (fileName.startsWith(".")) {
            continue;
        }
        SkString pathRelativeToRootDir(subDir);
        if (!isSubDirEmpty) {
            pathRelativeToRootDir.append(PATH_DIV_STR);
        }
        pathRelativeToRootDir.append(fileName);
        if (string_contains_any_of(pathRelativeToRootDir, matchSubstrings) &&
            !string_contains_any_of(pathRelativeToRootDir, nomatchSubstrings)) {
            files->push(new SkString(pathRelativeToRootDir));
        }
    }

    // Recurse into any non-ignored subdirectories.
    if (recurseIntoSubdirs) {
        SkOSFile::Iter dirIterator(dir.c_str());
        SkString dirName;
        while (dirIterator.next(&dirName, true)) {
            if (dirName.startsWith(".")) {
                continue;
            }
            SkString pathRelativeToRootDir(subDir);
            if (!isSubDirEmpty) {
                pathRelativeToRootDir.append(PATH_DIV_STR);
            }
            pathRelativeToRootDir.append(dirName);
            if (!string_contains_any_of(pathRelativeToRootDir, nomatchSubstrings)) {
                get_file_list_subdir(rootDir, pathRelativeToRootDir,
                                     matchSubstrings, nomatchSubstrings, recurseIntoSubdirs,
                                     files);
            }
        }
    }
}
Esempio n. 10
0
void
FsWatcher::ScanDirectory_NotifyUpdates_Execute(QString dirPath)
{
  _LOG_TRACE(" >> ScanDirectory_NotifyUpdates_Execute");

  // exclude working only on last component, not the full path; iterating through all directories,
  // even excluded from monitoring
  QRegExp exclude("^(\\.|\\.\\.|\\.chronoshare|.*~|.*\\.swp)$");

  QDirIterator dirIterator(dirPath, QDir::Dirs | QDir::Files | /*QDir::Hidden |*/ QDir::NoSymLinks |
                                      QDir::NoDotAndDotDot,
                           QDirIterator::Subdirectories); // directory iterator(recursive)

  // iterate through directory recursively
  while (dirIterator.hasNext()) {
    dirIterator.next();

    // Get FileInfo
    QFileInfo fileInfo = dirIterator.fileInfo();

    QString name = fileInfo.fileName();
    _LOG_DEBUG("+++ Scanning: " << name.toStdString());

    if (!exclude.exactMatch(name)) {
      _LOG_DEBUG("Not excluded file/dir: " << fileInfo.absoluteFilePath().toStdString());
      QString absFilePath = fileInfo.absoluteFilePath();

      // _LOG_DEBUG("Attempt to add path to watcher: " << absFilePath.toStdString());
      m_watcher->removePath(absFilePath);
      m_watcher->addPath(absFilePath);

      if (fileInfo.isFile()) {
        QString relFile = absFilePath;
        relFile.remove(0, m_dirPath.size());
        fs::path aFile(relFile.toStdString());

        if (
          //!m_fileState->LookupFile(aFile.relative_path().generic_string())
          ///* file does not exist there, but exists locally: added */)
          !fileExists(aFile.relative_path()) /*file does not exist in db, but exists in fs: add */) {
          addFile(aFile.relative_path());
          DidFileChanged(absFilePath);
        }
      }
    }
    else {
      // _LOG_DEBUG("Excluded file/dir: " << fileInfo.filePath().toStdString());
    }
  }
}
Esempio n. 11
0
//?х??
void Photos::scanFile(QString path)
{
    QDirIterator dirIterator(path,QDir::Files|QDir::NoSymLinks);
    while (dirIterator.hasNext())
    {
        QString tmpFile = dirIterator.next();
        QStringList list = tmpFile.split(".");
        QString expandedName = list.takeLast();
        if("jpg" == expandedName || "JPG" == expandedName)
        imageList << tmpFile;

    }
    getPosition();

}
Esempio n. 12
0
/**
Récupèrer tous les fichiers de catgeories.
Conditions : fichiers avec l'extension DB_SNIPPET_FORMAT
             et pas plus de DB_FILE_MAXLEN caractères de long.
**/
QStringList Category::getAll() {
     Log::put("Recuperation des noms de catégories",2);
     QStringList result =  QStringList();
     QStringList listFilter;
     listFilter << "*" << DB_SNIPPET_FORMAT;
     QDirIterator dirIterator(DB_PATH, listFilter, QDir::Files | QDir::NoSymLinks);

     while ( dirIterator.hasNext() ) {
         QString name = QFileInfo(dirIterator.next()).baseName();
         if ( name.toStdString().length() < DB_FILE_MAXLEN ) {
             result << name;
         }
     }
     return result;
}
ImageProvider::ImageProvider (ros::NodeHandle& nodeHandle, const ImageProviderConfiguration::ConstPtr& configuration)
        : nodeHandle(nodeHandle), imgTransport(nodeHandle), configuration(configuration), numberOfImages(0), imagePos(configuration->startPos) {
    // setup the file pattern to be used for all files
    boost::regex re(configuration->filePattern);
    // iterate the configurations and retrieve matching files
    runtimeData.reserve(configuration->cameraConfigs.size());
    if (configuration->cameraConfigs.size() > 0) {
        for (CameraConfigEntry::ConstPtrList::const_iterator it = configuration->cameraConfigs.begin(); it != configuration->cameraConfigs.end(); ++it) {
            bfs::path imageDir ((*it)->directoryName);
            if (!imageDir.is_absolute()) { imageDir = bfs::path(configuration->sourceDir) / imageDir; }
            if (!bfs::exists(imageDir)) {
                throw ImageProviderException(std::string("Image directory '") + imageDir.string() + std::string("' does not exist"));
            }
            if (!bfs::is_directory(imageDir)) {
                throw ImageProviderException(std::string("Image directory '") + imageDir.string() + std::string("' is not a directory"));
            }
            FileListPtr fileList = boost::make_shared<FileListPtr::element_type>();
            for (bfs::directory_iterator dirIterator (imageDir); dirIterator != bfs::directory_iterator(); ++dirIterator) {
                bfs::path fileName = dirIterator->path().filename();
                if (boost::regex_match(fileName.string(), re)) {
                    fileList->push_back(fileName);
                }
            }
            std::sort(fileList->begin(), fileList->end());
            ImageProviderRuntimeData rtData;
            rtData.cameraConfiguration = *it;
            rtData.directory = imageDir;
            rtData.fileList = fileList;
            runtimeData.push_back(rtData);
        }
        // validate the file lists
        FlagErrorReturnValue retVal = validateFileLists(runtimeData);
        if (boost::get<0>(retVal)) {
            for (ImageProviderRuntimeData::List::iterator it = runtimeData.begin(); it != runtimeData.end(); ++it) {
                it->pubImage = boost::make_shared<image_transport::Publisher>();
                *it->pubImage = imgTransport.advertise(configuration->topicPrefix + "/" + it->cameraConfiguration->cameraName, it->cameraConfiguration->bufferSize);
            }
            numberOfImages = runtimeData[0].fileList->size();
        }
        else {
            throw ImageProviderException("Validation of file lists: " + boost::get<1>(retVal));
        }
    }
    else {
        throw ImageProviderException("No camera configuration available");
    }
}
bool DomainContentBackupManager::getMostRecentBackup(const QString& format,
                                                     QString& mostRecentBackupFileName,
                                                     QDateTime& mostRecentBackupTime) {
    QRegExp formatRE { AUTOMATIC_BACKUP_PREFIX + QRegExp::escape(format) + "\\-(" + DATETIME_FORMAT_RE + ")" + "\\.zip" };

    QStringList filters;
    filters << AUTOMATIC_BACKUP_PREFIX + format + "*.zip";

    bool bestBackupFound = false;
    QString bestBackupFile;
    QDateTime bestBackupFileTime;

    // Iterate over all of the backup files in the persist location
    QDirIterator dirIterator(_backupDirectory, filters, QDir::Files | QDir::NoSymLinks, QDirIterator::NoIteratorFlags);
    while (dirIterator.hasNext()) {
        dirIterator.next();
        auto fileName = dirIterator.fileInfo().fileName();

        if (formatRE.exactMatch(fileName)) {
            auto datetime = formatRE.cap(1);
            auto createdAt = QDateTime::fromString(datetime, DATETIME_FORMAT);

            if (!createdAt.isValid()) {
                qDebug() << "Skipping backup with invalid timestamp: " << datetime;
                continue;
            }

            qDebug() << "Checking " << dirIterator.fileInfo().filePath();

            // Based on last modified date, track the most recently modified file as the best backup
            if (createdAt > bestBackupFileTime) {
                bestBackupFound = true;
                bestBackupFile = dirIterator.filePath();
                bestBackupFileTime = createdAt;
            }
        } else {
            qDebug() << "NO match: " << fileName << formatRE;
        }
    }

    // If we found a backup then return the results
    if (bestBackupFound) {
        mostRecentBackupFileName = bestBackupFile;
        mostRecentBackupTime = bestBackupFileTime;
    }
    return bestBackupFound;
}
/** Reimplemented with a QDirIterator to gather informations about tracks. */
void FileSystemTreeView::findAll(const QModelIndex &index, QStringList &tracks) const
{
	QFileInfo fileInfo = _fileSystemModel->fileInfo(index);
	if (fileInfo.isFile()) {
		tracks << "file://" + fileInfo.absoluteFilePath();
	} else {
		QDirIterator dirIterator(fileInfo.absoluteFilePath(), QDirIterator::Subdirectories);
		while (dirIterator.hasNext()) {
			QString entry = dirIterator.next();
			QFileInfo fileInfo(entry);
			if (fileInfo.isFile() && FileHelper::suffixes(FileHelper::All).contains(fileInfo.suffix())) {
				tracks << "file://" + fileInfo.absoluteFilePath();
			}
		}
	}
	tracks.sort(Qt::CaseInsensitive);
	tracks.removeDuplicates();
}
Esempio n. 16
0
//-----------------------------------------------------------------------------------------
void FormatConverterApp::onBrowseClicked()
{
    bool bIsFile = sender() == ui.actionSelect_files;

    m_FilePathNameList.clear();

    ui.listWidget->clear();

    if (bIsFile)
    {
        QString inDirectory = m_Settings.value("InDirectory", QCoreApplication::applicationDirPath()).toString();
        m_FilePathNameList << QFileDialog::getOpenFileNames(this, tr("Open 3D Model"), inDirectory, tr("*.*"));

        if (!m_FilePathNameList.isEmpty())
        {
            m_Settings.setValue("InDirectory", QFileInfo(m_FilePathNameList[0]).canonicalPath());
        }
    }
    else // Directory
    {
        QString inDirectory = m_Settings.value("InDirectory", QCoreApplication::applicationDirPath()).toString();
        QString strPath = QFileDialog::getExistingDirectory(this, tr("Open Directory"), inDirectory);

        if (!strPath.isEmpty())
        {
            m_Settings.setValue("InDirectory", QFileInfo(strPath).canonicalPath());
            QStringList listFilter;
            listFilter << "*.*";

            QDirIterator dirIterator(strPath, listFilter, QDir::Files);

            while (dirIterator.hasNext())
            {
                m_FilePathNameList << dirIterator.next();
            }
        }
    }

    foreach (const QString& filePathName, m_FilePathNameList)
    {
        ui.listWidget->addItem(filePathName);
    }
Esempio n. 17
0
void ReplayLoadingThread::run() {
	QDirIterator dirIterator(_folder, QDirIterator::Subdirectories);
	int counter = 0;
	while(dirIterator.hasNext()) {
		QString fileName = dirIterator.next();
		if(counter >= _startFrom && counter < _startFrom + REPLAYS_PER_THREAD) {
			if(fileName.right(REPLAY_FILE_EXT.length()) == REPLAY_FILE_EXT) {
				Replay *replay = new Replay(fileName, _vehicleNames);
				if(replay->load()) {
					_replays->append(replay);
				} else {
					delete replay;
				}
			}
		} else if(counter > _startFrom + REPLAYS_PER_THREAD) {
			break;
		}
		counter++;
	}
}
Esempio n. 18
0
void MainWindow::recup_Fichier()
{
    // On sélectionne le répertoire à partir duquel on va rechercher les fichiers AVI et MP3

    QString selectDir = QFileDialog::getExistingDirectory
    (
        this,
       tr("Ouvrir un répertoire"),
        "",
        QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks
    );

    // On remplit une QStringList avec chacun des filtres désirés ici "*.mp3" et "*.aac".
    QStringList listFilter;
    listFilter << "*.aac";
    listFilter << "*.mp3";

    // On déclare un QDirIterator dans lequel on indique que l'on souhaite parcourir un répertoire et ses sous-répertoires.
    // De plus, on spécifie le filtre qui nous permettra de récupérer uniquement les fichiers du type souhaité.
    //QDirIterator dirIterator("C:/Users/Mathieu/Music", listFilter ,QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);
   QDirIterator dirIterator(selectDir, listFilter ,QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);

    // Variable qui contiendra tous les fichiers correspondant à notre recherche
    QStringList fileList;
    // Tant qu'on n'est pas arrivé à la fin de l'arborescence...


    while(dirIterator.hasNext())
    {

        // ...on va au prochain fichier correspondant à notre filtre
        fileList << dirIterator.next();
        //Titre unTitre = new Titre(dirIterator.next());

        ui->listWidget->addItem(dirIterator.next());

    }
}
Esempio n. 19
0
/** ***************************************************************************/
void Files::Indexer::run() {

    // Notification
    QString msg("Indexing files ...");
    emit statusInfo(msg);
    qDebug() << "[Files]" << msg;


    // Prepare the iterator properties
    QDir::Filters filters = QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot;
    if (_extension->_indexHidden)
        filters |= QDir::Hidden;
    QDirIterator::IteratorFlags flags;
    if (_extension->_followSymlinks)
        flags = QDirIterator::FollowSymlinks;


    // Get a new index
    std::vector<shared_ptr<File>> newIndex;
    std::set<QString> indexedDirs;


    // Anonymous function that implemnents the index recursion
    std::function<void(const QFileInfo&)> indexRecursion =
            [this, &newIndex, &indexedDirs, &filters, &flags, &indexRecursion](const QFileInfo& fileInfo){
        if (_abort) return;

        QString canonicalPath = fileInfo.canonicalFilePath();


        if (fileInfo.isFile()) {

            // If the file matches the index options, index it
            QMimeType mimetype = _mimeDatabase.mimeTypeForFile(canonicalPath);
            QString mimeName = mimetype.name();
            if ((_extension->_indexAudio && mimeName.startsWith("audio"))
                    ||(_extension->_indexVideo && mimeName.startsWith("video"))
                    ||(_extension->_indexImage && mimeName.startsWith("image"))
                    ||(_extension->_indexDocs &&
                       (mimeName.startsWith("application") || mimeName.startsWith("text")))) {
                newIndex.push_back(std::make_shared<File>(canonicalPath, mimetype));
            }
        } else if (fileInfo.isDir()) {

            emit statusInfo(QString("Indexing %1.").arg(canonicalPath));

            // Skip if this dir has already been indexed
            if (indexedDirs.find(canonicalPath)!=indexedDirs.end()){
                return;
            }

            // If the dir matches the index options, index it
            if (_extension->_indexDirs) {
                QMimeType mimetype = _mimeDatabase.mimeTypeForFile(canonicalPath);
                newIndex.push_back(std::make_shared<File>(canonicalPath, mimetype));
            }

            // Ignore ignorefile by default
            std::vector<QRegExp> ignores;
            ignores.push_back(QRegExp(_extension->IGNOREFILE, Qt::CaseSensitive, QRegExp::Wildcard));

            // Read the ignore file, see http://doc.qt.io/qt-5/qregexp.html#wildcard-matching
            QFile file(QDir(canonicalPath).filePath(_extension->IGNOREFILE));
            if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QTextStream in(&file);
                while (!in.atEnd())
                    ignores.push_back(QRegExp(in.readLine().trimmed(), Qt::CaseSensitive, QRegExp::Wildcard));
                file.close();
            }

            // Index all children in the dir
            QDirIterator dirIterator(canonicalPath, filters, flags);
            while (dirIterator.hasNext()) {
                dirIterator.next();

                // Skip if this file matches one of the ignore patterns
                for (QRegExp& ignore : ignores){
                    QString s = dirIterator.fileName(); // This is insane works only if its a lvalue
                    if(ignore.exactMatch(s))
                        goto SKIP_THIS;
                }

                // Index this file
                indexRecursion(dirIterator.fileInfo());
                SKIP_THIS:;
            }

            // Remember that this dir has been indexed to avoid loops
            indexedDirs.insert(canonicalPath);
        }
    };


    // Start the indexing
    for (const QString& rootDir : _extension->_rootDirs) {
        indexRecursion(QFileInfo(rootDir));
        if (_abort) return;
    }


    // Sort the new index for linear usage copy [O(n*log(n))]
    emit statusInfo("Sorting ... ");
    std::sort(newIndex.begin(), newIndex.end(), [](const shared_ptr<File> &lhs, const shared_ptr<File> &rhs) {
                  return QString::compare(lhs->path(), rhs->path(), Qt::CaseInsensitive) < 0;
              });


    // Copy the usagecounters  [O(n)]
    emit statusInfo("Copy usage statistics ... ");
    size_t i=0, j=0;
    while (i < _extension->_fileIndex.size() && j < newIndex.size()) {
        if (_extension->_fileIndex[i]->path_ == newIndex[j]->path_) {
            newIndex[j]->usage_ = _extension->_fileIndex[i]->usage_;
            ++i;++j;
        } else if (_extension->_fileIndex[i]->path_ < newIndex[j]->path_) {
            ++i;
        } else {// if ((*_fileIndex)[i]->path > (*newIndex)[j]->path) {
            ++j;
        }
    }

    /*
     *  ▼ CRITICAL ▼
     */

    // Lock the access
    _extension->_indexAccess.lock();

    // Set the new index
    _extension->_fileIndex = std::move(newIndex);

    // Reset the offline index
    emit statusInfo("Build offline index... ");
    _extension->_searchIndex.clear();

    // Build the new offline index
    for (shared_ptr<IIndexable> i : _extension->_fileIndex)
        _extension->_searchIndex.add(i);

    // Unlock the accress
    _extension->_indexAccess.unlock();

    /*
     *  ▲ CRITICAL ▲
     */


    // Notification
    msg = QString("Indexed %1 files.").arg(_extension->_fileIndex.size());
    emit statusInfo(msg);
    qDebug() << "[Files]" << msg;
}
Esempio n. 20
0
void GenTool::setSubDirPath(const QString& path)
{
	QDirIterator dirIterator(path, QDir::Dirs | QDir::NoDot | QDir::NoDotDot);
	while (dirIterator.hasNext()) initPath(dirIterator.next());
}
Esempio n. 21
0
/** ***************************************************************************/
void Files::Extension::Indexer::run() {

    // Notification
    qDebug("[%s] Start indexing in background thread", extension_->name_);
    emit statusInfo("Indexing files ...");

    // Prepare the iterator properties
    QDir::Filters filters = QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot;
    if (extension_->indexHidden_)
        filters |= QDir::Hidden;

    // Get a new index
    std::vector<shared_ptr<File>> newIndex;
    std::set<QString> indexedDirs;


    // Anonymous function that implemnents the index recursion
    std::function<void(const QFileInfo&)> indexRecursion =
            [this, &newIndex, &indexedDirs, &filters, &indexRecursion](const QFileInfo& fileInfo){
        if (abort_) return;

        const QString canonicalPath = fileInfo.canonicalFilePath();


        if (fileInfo.isFile()) {

            // If the file matches the index options, index it
            QMimeType mimetype = mimeDatabase_.mimeTypeForFile(canonicalPath);
            const QString mimeName = mimetype.name();
            if ((extension_->indexAudio_ && mimeName.startsWith("audio"))
                    ||(extension_->indexVideo_ && mimeName.startsWith("video"))
                    ||(extension_->indexImage_ && mimeName.startsWith("image"))
                    ||(extension_->indexDocs_ &&
                       (mimeName.startsWith("application") || mimeName.startsWith("text")))) {
                newIndex.push_back(std::make_shared<File>(canonicalPath, mimetype));
            }
        } else if (fileInfo.isDir()) {

            emit statusInfo(QString("Indexing %1.").arg(canonicalPath));

            // Skip if this dir has already been indexed
            if (indexedDirs.find(canonicalPath)!=indexedDirs.end())
                return;

            // Remember that this dir has been indexed to avoid loops
            indexedDirs.insert(canonicalPath);

            // If the dir matches the index options, index it
            if (extension_->indexDirs_) {
                QMimeType mimetype = mimeDatabase_.mimeTypeForFile(canonicalPath);
                newIndex.push_back(std::make_shared<File>(canonicalPath, mimetype));
            }

            // Ignore ignorefile by default
            std::vector<QRegExp> ignores;
            ignores.push_back(QRegExp(extension_->IGNOREFILE, Qt::CaseSensitive, QRegExp::Wildcard));

            // Read the ignore file, see http://doc.qt.io/qt-5/qregexp.html#wildcard-matching
            QFile file(QDir(canonicalPath).filePath(extension_->IGNOREFILE));
            if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QTextStream in(&file);
                while (!in.atEnd())
                    ignores.push_back(QRegExp(in.readLine().trimmed(), Qt::CaseSensitive, QRegExp::Wildcard));
                file.close();
            }

            // Index all children in the dir
            QDirIterator dirIterator(canonicalPath, filters, QDirIterator::NoIteratorFlags);
            while (dirIterator.hasNext()) {
                const QString fileName = dirIterator.next();

                // Skip if this file matches one of the ignore patterns
                for (const QRegExp& ignore : ignores)
                    if(ignore.exactMatch(fileName))
                        goto SKIP_THIS;

                // Skip if this file is a symlink and we shoud skip symlinks
                if (dirIterator.fileInfo().isSymLink() && !extension_->followSymlinks_)
                    goto SKIP_THIS;

                // Index this file
                indexRecursion(dirIterator.fileInfo());
                SKIP_THIS:;
            }
        }
    };


    // Start the indexing
    for (const QString &rootDir : extension_->rootDirs_) {
        indexRecursion(QFileInfo(rootDir));
        if (abort_) return;
    }


    // Sort the new index for linear usage copy [O(n*log(n))]
    emit statusInfo("Sorting ... ");
    std::sort(newIndex.begin(), newIndex.end(), [](const shared_ptr<File> &lhs, const shared_ptr<File> &rhs) {
                  return QString::compare(lhs->path(), rhs->path(), Qt::CaseInsensitive) < 0;
              });


    // Copy the usagecounters  [O(n)]
    emit statusInfo("Copy usage statistics ... ");
    size_t i=0, j=0;
    while (i < extension_->index_.size() && j < newIndex.size()) {
        if (extension_->index_[i]->path() == newIndex[j]->path()) {
            newIndex[j]->setUsage(extension_->index_[i]->usage());
            ++i;++j;
        } else if (extension_->index_[i]->path() < newIndex[j]->path()) {
            ++i;
        } else {// if ((*_fileIndex)[i]->path > (*newIndex)[j]->path) {
            ++j;
        }
    }

    /*
     *  ▼ CRITICAL ▼
     */

    // Lock the access
    QMutexLocker locker(&extension_->indexAccess_);

    // Abortion requested while block
    if (abort_)
        return;

    // Set the new index (use swap to shift destruction out of critical area)
    std::swap(extension_->index_, newIndex);

    // Rebuild the offline index
    extension_->offlineIndex_.clear();
    for (auto &item : extension_->index_)
        extension_->offlineIndex_.add(item);

    // Notification
    qDebug("[%s] Indexing done (%d items)", extension_->name_, static_cast<int>(extension_->index_.size()));
    emit statusInfo(QString("Indexed %1 files").arg(extension_->index_.size()));
}
Esempio n. 22
0
void MediaFrame::add(const QString &path, AddOption option)
{
    if(isAdded(path)) {
        qWarning() << "Path" << path << "already added";
        return;
    }

    QUrl url = QUrl(path);
    QString localPath = url.toString(QUrl::PreferLocalFile);
    //qDebug() << "Local path" << localPath << "Path" << path;

    QStringList paths;
    QString filePath;

    if(isDir(localPath)) {

        if(!isDirEmpty(localPath))
        {
            QDirIterator dirIterator(localPath, m_filters, QDir::Files, (option == AddOption::RECURSIVE ? QDirIterator::Subdirectories | QDirIterator::FollowSymlinks : QDirIterator::NoIteratorFlags));

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

                filePath = dirIterator.filePath();
                paths.append(filePath);
                m_allFiles.append(filePath);
                //qDebug() << "Appended" << filePath;
                emit countChanged();
            }
            if(paths.count() > 0)
            {
                m_pathMap.insert(path, paths);
                qDebug() << "Added" << paths.count() << "files from" << path;
            }
            else
            {
                qWarning() << "No images found in directory" << path;
            }
        }
        else
        {
            qWarning() << "Not adding empty directory" << path;
        }

        // the pictures have to be sorted before adding them to the list,
        // because the QDirIterator sorts them in a different way than QDir::entryList
        //paths.sort();

    }
    else if(isFile(localPath))
    {
        paths.append(path);
        m_pathMap.insert(path, paths);
        m_allFiles.append(path);
        qDebug() << "Added" << paths.count() << "files from" << path;
        emit countChanged();
    }
    else
    {
        if (url.isValid() && !url.isLocalFile())
        {
            qDebug() << "Adding" << url.toString() << "as remote file";
            paths.append(path);
            m_pathMap.insert(path, paths);
            m_allFiles.append(path);
            emit countChanged();
        }
        else
        {
            qWarning() << "Path" << path << "is not a valid file url or directory";
        }
    }

}
Esempio n. 23
0
bool CmdExorcise::exec(CmdHelper* ch)
{
  if(!init(ch)) return false;

  mCmd->regStdOpts("del-omen save-omen");

  if(mCmd->isMissingParms())
  {
    mCmd->inOptBrief("del-omen", "[<Devil>]", "Delete the config file and home directory of <Devil>");
    mCmd->inOptBrief("save-omen", "Don't delete the config file and home directory of <Devil>");

    if(mCmd->printThisWay("[<Devil>]")) return true;

    mCmd->printComment(tr(
      "Switch in any case back to the productive version by restoring the "
      "productive user config file and delete (if given) the development "
      "schema <Devil>. At default is the devil config file and home directory saved."));
    mCmd->printNote(tr(
      "You could set in your productive config file 'DeleteDevilConfig=true' to auto "
      "remove the devil config file and home directory. See doc/config-file.txt."));
    mCmd->printForInst("mylastidea", tr(
      "Remove the DB schema but keep the config file and home directory."));
    mCmd->printForInst("--del-omen mygoodidea", tr(
      "Only delete the config file and home directory, keep the DB untouched."));
    mCmd->printForInst("mybadidea --del-omen", tr(
      "Delete DB schema, config file and home directory."));
    mCmd->aided();
    return true;
  }

  QString configFile  = mRcFile->fileName();
  QString devil       = FTool::makeValidWord(mRcFile->getST("Devil"));
  QString killDevil   = FTool::makeValidWord(mCmd->argStr(1, ""));
  QString devilFile   = configFile + ".Devil." + devil;
  QString proFile     = configFile + ".Productive";
  bool    configSaved = false;

  if(!devil.isEmpty())
  {
    verbose(FUNC, tr("I renunciate the devil '%1'").arg(devil));

    QFile::remove(devilFile);
    QFile::rename(configFile, devilFile);

    configSaved = true;

    if(QFile::exists(proFile))
    {
      QFile::rename(proFile, configFile);

      mRcFile->sync();
      mRcFile->remove("Devil"); // Be sure we are no longer devilish
      mRcFile->checkFiluHome();
      verbose(FUNC, tr("Productive config file restored."));
    }
    else
    {
      mRcFile->checkConfigFile();
      mRcFile->checkFiluHome();
    }

    verbose(FUNC, tr("SqlPath is now: %1").arg(mRcFile->getPath("SqlPath")));
    verbose(FUNC, tr("ProviderPath is now: %1").arg(mRcFile->getPath("ProviderPath")));
    mFilu->closeDB();
    mFilu->openDB();
  }

  QString user = qgetenv("USER");

  mFilu->setSqlParm(":username", user);
  QSqlQuery* query = mFilu->execSql("GetDevils");

  QSet<QString> devils;
  const QString devilPrefix = QString("user_%1_").arg(user);
  while(query->next())
  {
    QString devil = query->value(0).toString();
    devil.remove(devilPrefix);
    devils.insert(devil);
  }

  if(     (mCmd->has("del-omen") or mRcFile->getBL("DeleteDevilConfig"))
      and !mCmd->has("save-omen") )
  {
    QString devil = killDevil.isEmpty() ? mCmd->optStr("del-omen") : killDevil;
    devilFile = configFile + ".Devil." + devil;

    if(!devil.isEmpty())
    {
      if(QFile::exists(devilFile))
      {
        FTool::removeDir(SettingsFile(devilFile).getPath("FiluHome"));
        verbose(FUNC, tr("FiluHome of devil '%1' removed.").arg(devil));

        QFile::remove(devilFile);
        verbose(FUNC, tr("Config file for devil '%1' removed.").arg(devil));
        configSaved = false;
      }
      else
      {
        error(FUNC, tr("No config file for devil '%1' found to remove.").arg(devil));
      }
    }
  }

  const QString filuDevil = "%1_%2_%3";
  const QString userDevil = "user_%1_%2";

//   Out commentetd because I run in my own trap.
//   It is not possible to execute a SQL more than one time with static
//   parameters. What we need is a "execute once" function wich release the SQL
//   after executen, or a "release <sql>" function, or a "execStatic" function
//   wich works with normal setSqlParm() but does not use query-bind() but
//   replace the paramater by his own
//   if("+++" == killDevil) // Exorcise all devils
//   {
//     foreach(const QString& d, devils)
//     {
//       verbose(FUNC, tr("Devil '%1'.").arg(d));
//       mFilu->setStaticSqlParm(":filuDevil", filuDevil.arg(mRcFile->getST("FiluSchema"), user, d));
//       mFilu->setStaticSqlParm(":userDevil", userDevil.arg(user, d));
//       mFilu->execSql("BackToHell");
//
// //       devils.remove(d);
//
//       if(!mFilu->hasError())
//       {
//         verbose(FUNC, tr("Devil '%1' is banned back to hell.").arg(d));
//       }
//       else
//       {
//         return;
//       }
//     }
//
//     devils.clear();
//   }
//   else

  if(!killDevil.isEmpty())
  {
    if(devils.contains(killDevil))
    {
      mFilu->setStaticSqlParm(":filuDevil", filuDevil.arg("filu", user, killDevil));
      mFilu->setStaticSqlParm(":userDevil", userDevil.arg(user, killDevil));
      mFilu->execSql("BackToHell");

      devils.remove(killDevil);

      if(!mFilu->hasError())
      {
        verbose(FUNC, tr("Devil '%1' is banned back to hell.").arg(killDevil));
      }
    }
    else
    {
      error(FUNC, tr("No devil '%1' is amongst us.").arg(killDevil));
    }
  }
  else if(configSaved)
  {
    verbose(FUNC, tr("Config file for devil '%1' saved.").arg(devil));
  }

  if(verboseLevel(eInfo))
  {
    if(!devils.size())
    {
      verbose(FUNC, tr("No devils out of hell."));
    }
    else if(devils.size() == 1)
    {
      verbose(FUNC, tr("The devil is still amongst us:"));
      verbose(FUNC, QString("  %1").arg(devils.toList().at(0)));
    }
    else
    {
      verbose(FUNC, tr("These devils are still amongst us:"));
      foreach(const QString& d, devils) verbose(FUNC, QString("  %1").arg(d));
    }

    // FIXME: Looks ugly, find and print omen in a  more nicely way
    QString path = mRcFile->fileName();
    path.remove(QRegExp("[\\w\\.]+$"));
    QDirIterator dirIterator(path);
    bool infoTxt = false;
    while(dirIterator.hasNext())
    {
      dirIterator.next();
      QString omen = dirIterator.fileName();
      if(!omen.startsWith("Filu.conf.Devil.")) continue;

      omen.remove("Filu.conf.Devil.");
      if(devils.contains(omen)) continue;
      if(!infoTxt)
      {
        verbose(FUNC, tr("There are devil omen:"));
        infoTxt = true;
      }
      verbose(FUNC, QString("  %1").arg(omen));
    }
  }

  return !hasError();
}