Beispiel #1
0
/* Return the first file matching the pattern
 * "extensions/<id>/<id><extension-apiversion-mejor>.*". For the
 * "dummy" extension using API version 1.2, this means
 * "extensions/dummy/dummy1.*".  In other words: Extensions must
 * provide exactly one file matching this pattern, and that file must
 * contain root class/function of the extension.
 *
 * Scripted extensions with the root class inlined in the XML file are
 * not affected by this restriction.
 *
 * Returns QFileInfo() if no such file was found.
 */
QFileInfo
Configuration::extensionRootFile(const QString &id,
				 const VersionNumber &apiVersion) const
{
    QFileInfoList candidateFiles;
    QString pattern = id + QString::number(apiVersion.majorVersion()) + ".*";

    // Check the user extension repository first.
    QDir base = PlatformDependent::p()->extensionsDir(PlatformDependent::User);
    base.cd(id);
    candidateFiles = base.entryInfoList(QStringList(pattern),
                                        QDir::Files | QDir::Readable);

    // If there were no such files in the user extension repository,
    // check the system repository.
    if (candidateFiles.isEmpty())
    {
        base = PlatformDependent::p()->extensionsDir(PlatformDependent::System);
        base.cd(id);
        candidateFiles = base.entryInfoList(QStringList(pattern),
                                            QDir::Files | QDir::Readable);
    }

    if (candidateFiles.isEmpty())
        return QFileInfo();
    else
        return candidateFiles.first();
}
Beispiel #2
0
void scanDirectory(FileInfoList &fileEntries, const QString &name, const QString &strDir)
{
   QDir dir(strDir);
   if (!dir.exists()) return;

   QFileInfoList *newEntries = (QFileInfoList *) dir.entryInfoList();

   if (!newEntries) return; // Directory not accessible ??

   for(QFileInfo *qFileInfo = newEntries->first();
       qFileInfo;
       qFileInfo = newEntries->next())
   {
       if (qFileInfo->isFile())
       {
          FileInfo *fileInfo = readEntry( strDir + "/" + qFileInfo->fileName());
          if (fileInfo)
          {
             fileInfo->name = name + "/" + qFileInfo->fileName();
             fileInfo->size = (qFileInfo->size() + 1023) / 1024;
             fileEntries.append(fileInfo);
          }
       }
   }
}
Beispiel #3
0
/*
  Called when the "upload" action is triggered.
  Build the current project and upload the resulting .bin to the board.
*/
void MainWindow::onUpload( )
{
  if(currentProject.isEmpty())
    return statusBar()->showMessage( "Open a project to upload, or create a new one from the File menu.", 3500 );
  QDir projectDir(currentProject);
  projectDir.cd("build");
  projectDir.setNameFilters(QStringList() << "*.bin");
  QFileInfoList bins = projectDir.entryInfoList();
  if(bins.count())
    uploadFile(bins.first().filePath());
  else
    return statusBar()->showMessage( "Couldn't find the file to upload for this project.", 3500 );
}
Beispiel #4
0
QIcon MainMenu::getPrefixIcon(const QString &prefixHash) const
{
    QString iconPath = FS::prefix(prefixHash).absoluteFilePath(".icon");
    if (!QFile::exists(iconPath))
    {
        QFileInfoList iList = FS::icons(prefixHash).entryInfoList(QDir::Files);
        if (!iList.isEmpty())
        {
            QFile::copy(iList.first().absoluteFilePath(), iconPath);
            return QIcon(iconPath);
        }
        return style()->standardIcon(QStyle::SP_DirIcon);
    }
    return QIcon(iconPath);
}
	void LogTraceListener::deleteFiles(int days)
	{
		if(qApp == NULL)
			return;

		QDir dir(qApp->tr(_logPath.c_str()));
		if(dir.exists())
		{
			string filter = "*.log";

#if WIN32
			WIN32_FIND_DATA ffd;
			HANDLE hFind = INVALID_HANDLE_VALUE;
			// Find the first file in the directory.
			hFind = FindFirstFile((_logPath + "/" + filter).c_str(), &ffd);
			if (INVALID_HANDLE_VALUE != hFind) 
			{
				// List all the files in the directory with some info about them.
				do
				{
					if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
					{
					}
					else
					{
						removeFile(dir, ffd.cFileName, days);
					}
				}
				while (FindNextFile(hFind, &ffd) != 0);
				FindClose(hFind);
			}
#else
			dir.setNameFilter(filter.c_str());
			QFileInfoList* list = (QFileInfoList*)dir.entryInfoList();
			if(list != NULL)
			{
				QFileInfo *fi;
				for ( fi=list->first(); fi != 0; fi=list->next() )
				{
					removeFile(dir, Convert::convertStr(fi->fileName()), days);
				}
			}
#endif
		}
	}
//! [4]
QXmlNodeModelIndex
FileTree::nextFromSimpleAxis(SimpleAxis axis, const QXmlNodeModelIndex &nodeIndex) const
{
    const QFileInfo fi(toFileInfo(nodeIndex));
    const Type type = Type(nodeIndex.additionalData());

    if (type != File && type != Directory) {
        Q_ASSERT_X(axis == Parent, Q_FUNC_INFO, "An attribute only has a parent!");
        return toNodeIndex(fi, Directory);
    }

    switch (axis) {
    case Parent:
        return toNodeIndex(QFileInfo(fi.path()), Directory);

    case FirstChild:
    {
        if (type == File) // A file has no children.
            return QXmlNodeModelIndex();
        else {
            Q_ASSERT(type == Directory);
            Q_ASSERT_X(fi.isDir(), Q_FUNC_INFO, "It isn't really a directory!");
            const QDir dir(fi.absoluteFilePath());
            Q_ASSERT(dir.exists());

            const QFileInfoList children(dir.entryInfoList(QStringList(),
                                         m_filterAllowAll,
                                         m_sortFlags));
            if (children.isEmpty())
                return QXmlNodeModelIndex();
            const QFileInfo firstChild(children.first());
            return toNodeIndex(firstChild);
        }
    }

    case PreviousSibling:
        return nextSibling(nodeIndex, fi, -1);

    case NextSibling:
        return nextSibling(nodeIndex, fi, 1);
    }

    Q_ASSERT_X(false, Q_FUNC_INFO, "Don't ever get here!");
    return QXmlNodeModelIndex();
}
Beispiel #7
0
void SysStatus::checkSystem(bool checkjails){
  complete = QFile::exists("/tmp/.rebootRequired");
  if(!complete){ 
    //Get all the possible flag files and only take the most recent (latest flag - they overwrite each other)
    QStringList upinfo = pcbsd::Utils::runShellCommand("syscache needsreboot isupdating");
    if(upinfo.length() < 2 || upinfo.join("").contains("[ERROR]") ){
      //Fallback method in case syscache is not working for some reason
      QDir procdir(UPDATE_PROC_DIR);
      QFileInfoList files = procdir.entryInfoList(QStringList() << UPDATE_PROC_FLAG_FILE_FILTER, QDir::Files, QDir::Time);
      QStringList tmp; for(int i=0; i<files.length(); i++){ tmp << files[i].absoluteFilePath(); }
      QString flag;
      if(!files.isEmpty()){ flag = pcbsd::Utils::readTextFile(files.first().absoluteFilePath()).simplified().toLower(); }
      //qDebug() << "No syscache running - use flags:" << tmp << flag;
      complete = (UPDATE_PROC_FINISHED == flag );
      updating = (UPDATE_PROC_WORKING == flag );
    }else{
      //Use the syscache info
      complete = (upinfo[0]=="true");
      updating = (upinfo[1]=="true");
    }
    if(!updating && !complete){
      //Run syscache to probe for updates that are available
      QString cmd = "syscache hasmajorupdates hassecurityupdates haspcbsdupdates \"pkg #system hasupdates\" \"jail list\"";
      QStringList info = pcbsd::Utils::runShellCommand(cmd);
      if(info.length() < 5){ return; } //no info from syscache
      sys = (info[0] == "true");
      sec = (info[1] == "true") || (info[2] == "true"); //combine security updates with pcbsd patches for notifications
      pkg = (info[3] == "true");
      //Now look for jail updates
      if(checkjails && !info[4].simplified().isEmpty() ){
	QStringList jls = info[4].split(", ");
	cmd = "syscache";
	for(int i=0; i<jls.length(); i++){
	  cmd.append(" \"pkg "+jls[i]+" hasupdates\"");
	}
	QStringList jinfo = pcbsd::Utils::runShellCommand(cmd);
	jail = jinfo.contains("true");
      }
    }
  }
}
QString FolderListModel::sdcardFolder() const
{
    QString sdcardfolder;

    if(QFile::exists("/media/sdcard"))
        sdcardfolder = "/media/sdcard";

    if(QFile::exists("/run/user/100000/media/sdcard"))
        sdcardfolder = "/run/user/100000/media/sdcard";

    if(sdcardfolder.isEmpty())
        return QString();

    QDir dir(sdcardfolder);
    QFileInfoList fileinfolist = dir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks, QDir::DirsFirst);

    if(fileinfolist.isEmpty())
        return QString();

    return fileinfolist.first().filePath();
}
Beispiel #9
0
void StrainPipeData::init()
{
    QFileInfo recipefi(directory.absoluteFilePath() + "/logdir/1.RECIPEFILE");
    recipefi.exists() ? recipie.reset(new RecipieList(recipefi))
    : recipie.reset(new RecipieList());

    base_dir.setNameFilters(QStringList("metric_*quast.csv"));
    QFileInfoList quastFiles=base_dir.entryInfoList();
    quastFiles.empty() ? questMetrics.reset(new QuastMetrics())
    : questMetrics.reset(new QuastMetrics(quastFiles.first()));


    base_dir.setNameFilters(QStringList("metric_*cgal.csv"));
    QFileInfoList cgalFiles = base_dir.entryInfoList();
    cgalFiles.empty() ? cgalMetrics.reset(new CgalMetrics())
    : cgalMetrics.reset(new CgalMetrics(cgalFiles.first()));

    base_dir.setNameFilters(QStringList("metric_*ale.csv"));
    QFileInfoList aleFiles=base_dir.entryInfoList();
    aleFiles.empty() ? aleMetrics.reset(new AleMetrics())
    : aleMetrics.reset(new AleMetrics(aleFiles.first()));


    QString timesFilename = base_dir.absolutePath()
                            + "/logdir/1stats/allstats.csv";
    QFileInfo tfi(timesFilename);
    tfi.exists() ? runTimes.reset(new RunTimes(tfi
                                  , base_dir.dirName()
                                  , directory.absolutePath()))
    : runTimes.reset(new RunTimes());


    // register the plot document object (only needed once, no matter how many
    // plots will be in the QTextDocument):
    QCPDocumentObject *plotObjectHandler = new QCPDocumentObject();
    QTextDocument::documentLayout()->
    registerHandler(QCPDocumentObject::PlotTextFormat, plotObjectHandler);

}
void InitAacEncTask::initAacEncImpl(const char *const toolName, const char *const fileNames[], const quint32 &toolMinVersion, const quint32 &verDigits, const quint32 &verShift, const char *const verStr, QRegExp &regExpVer, QRegExp &regExpSig)
{
	static const size_t MAX_FILES = 8;
	const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
	
	QFileInfoList fileInfo;
	for(size_t i = 0; fileNames[i] && (fileInfo.count() < MAX_FILES); i++)
	{
		fileInfo.append(QFileInfo(QString("%1/%2").arg(appPath, QString::fromLatin1(fileNames[i]))));
	}
	
	for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++)
	{
		if(!(iter->exists() && iter->isFile()))
		{
			qDebug("%s encoder binaries not found -> Encoding support will be disabled!\n", toolName);
			return;
		}
		if((iter->suffix().compare("exe", Qt::CaseInsensitive) == 0) && (!MUtils::OS::is_executable_file(iter->canonicalFilePath())))
		{
			qDebug("%s executable is invalid -> %s support will be disabled!\n", MUTILS_UTF8(iter->fileName()), toolName);
			return;
		}
	}

	qDebug("Found %s encoder binary:\n%s\n", toolName, MUTILS_UTF8(fileInfo.first().canonicalFilePath()));

	//Lock the encoder binaries
	QScopedPointer<LockedFile> binaries[MAX_FILES];
	try
	{
		size_t index = 0;
		for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++)
		{
			binaries[index++].reset(new LockedFile(iter->canonicalFilePath()));
		}
	}
	catch(...)
	{
		qWarning("Failed to get excluive lock to encoder binary -> %s support will be disabled!", toolName);
		return;
	}

	QProcess process;
	MUtils::init_process(process, fileInfo.first().absolutePath());

	process.start(fileInfo.first().canonicalFilePath(), QStringList() << "-help");

	if(!process.waitForStarted())
	{
		qWarning("%s process failed to create!", toolName);
		qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
		process.kill();
		process.waitForFinished(-1);
		return;
	}

	quint32 toolVersion = 0;
	bool sigFound = regExpSig.isEmpty() ? true : false;

	while(process.state() != QProcess::NotRunning)
	{
		if(!process.waitForReadyRead())
		{
			if(process.state() == QProcess::Running)
			{
				qWarning("%s process time out -> killing!", toolName);
				process.kill();
				process.waitForFinished(-1);
				return;
			}
		}
		while(process.canReadLine())
		{
			QString line = QString::fromUtf8(process.readLine().constData()).simplified();
			if((!sigFound) && regExpSig.lastIndexIn(line) >= 0)
			{
				sigFound = true;
				continue;
			}
			if(sigFound && (regExpVer.lastIndexIn(line) >= 0))
			{
				quint32 tmp[8];
				if(MUtils::regexp_parse_uint32(regExpVer, tmp, qMin(verDigits, 8U)))
				{
					toolVersion = 0;
					for(quint32 i = 0; i < verDigits; i++)
					{
						toolVersion = (toolVersion * verShift) + qBound(0U, tmp[i], (verShift - 1));
					}
				}
			}
		}
	}

	if(toolVersion <= 0)
	{
		qWarning("%s version could not be determined -> Encoding support will be disabled!", toolName);
		return;
	}
	else if(toolVersion < toolMinVersion)
	{
		qWarning("%s version is too much outdated (%s) -> Encoding support will be disabled!", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion,    "N/A")));
		qWarning("Minimum required %s version currently is: %s\n",                             toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolMinVersion, "N/A")));
		return;
	}

	qDebug("Enabled %s encoder %s.\n", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion, "N/A")));

	size_t index = 0;
	for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++)
	{
		lamexp_tools_register(iter->fileName(), binaries[index++].take(), toolVersion);
	}
}
Beispiel #11
0
bool PackageJobThread::installPackage(const QString &src, const QString &dest, OperationType operation)
{
    QDir root(dest);
    if (!root.exists()) {
        QDir().mkpath(dest);
        if (!root.exists()) {
            d->errorMessage = i18n("Could not create package root directory: %1", dest);
            d->errorCode = Package::JobError::RootCreationError;
            //qWarning() << "Could not create package root directory: " << dest;
            return false;
        }
    }

    QFileInfo fileInfo(src);
    if (!fileInfo.exists()) {
        d->errorMessage = i18n("No such file: %1", src);
        d->errorCode = Package::JobError::PackageFileNotFoundError;
        return false;
    }

    QString path;
    QTemporaryDir tempdir;
    bool archivedPackage = false;

    if (fileInfo.isDir()) {
        // we have a directory, so let's just install what is in there
        path = src;
        // make sure we end in a slash!
        if (!path.endsWith('/')) {
            path.append('/');
        }
    } else {
        KArchive *archive = 0;
        QMimeDatabase db;
        QMimeType mimetype = db.mimeTypeForFile(src);
        if (mimetype.inherits(QStringLiteral("application/zip"))) {
            archive = new KZip(src);
        } else if (mimetype.inherits(QStringLiteral("application/x-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-bzip-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-xz")) ||
                   mimetype.inherits(QStringLiteral("application/x-lzma"))) {
            archive = new KTar(src);
        } else {
            //qWarning() << "Could not open package file, unsupported archive format:" << src << mimetype.name();
            d->errorMessage = i18n("Could not open package file, unsupported archive format: %1 %2", src, mimetype.name());
            d->errorCode = Package::JobError::UnsupportedArchiveFormatError;
            return false;
        }

        if (!archive->open(QIODevice::ReadOnly)) {
            //qWarning() << "Could not open package file:" << src;
            delete archive;
            d->errorMessage = i18n("Could not open package file: %1", src);
            d->errorCode = Package::JobError::PackageOpenError;
            return false;
        }

        archivedPackage = true;
        path = tempdir.path() + '/';

        d->installPath = path;

        const KArchiveDirectory *source = archive->directory();
        source->copyTo(path);

        QStringList entries = source->entries();
        if (entries.count() == 1) {
            const KArchiveEntry *entry = source->entry(entries[0]);
            if (entry->isDirectory()) {
                path.append(entry->name()).append("/");
            }
        }

        delete archive;
    }

    QDir packageDir(path);
    QFileInfoList entries = packageDir.entryInfoList(*metaDataFiles);
    KPluginMetaData meta;
    if (!entries.isEmpty()) {
        const QString metadataFilePath = entries.first().filePath();
        if (metadataFilePath.endsWith(QLatin1String(".desktop")))
            meta = KPluginMetaData(metadataFilePath);
        else {
            QFile f(metadataFilePath);
            if(!f.open(QIODevice::ReadOnly)){
                qWarning() << "Couldn't open metadata file" << src << path;
                d->errorMessage = i18n("Could not open metadata file: %1", src);
                d->errorCode = Package::JobError::MetadataFileMissingError;
                return false;
            }
            QJsonObject metadataObject = QJsonDocument::fromJson(f.readAll()).object();
            meta = KPluginMetaData(metadataObject, QString(), metadataFilePath);
        }
    }

    if (!meta.isValid()) {
        qDebug() << "No metadata file in package" << src << path;
        d->errorMessage = i18n("No metadata file in package: %1", src);
        d->errorCode = Package::JobError::MetadataFileMissingError;
        return false;
    }


    QString pluginName = meta.pluginId();
    qDebug() << "pluginname: " << meta.pluginId();
    if (pluginName.isEmpty()) {
        //qWarning() << "Package plugin name not specified";
        d->errorMessage = i18n("Package plugin name not specified: %1", src);
        d->errorCode = Package::JobError::PluginNameMissingError;
        return false;
    }

    // Ensure that package names are safe so package uninstall can't inject
    // bad characters into the paths used for removal.
    QRegExp validatePluginName("^[\\w-\\.]+$"); // Only allow letters, numbers, underscore and period.
    if (!validatePluginName.exactMatch(pluginName)) {
        //qDebug() << "Package plugin name " << pluginName << "contains invalid characters";
        d->errorMessage = i18n("Package plugin name %1 contains invalid characters", pluginName);
        d->errorCode = Package::JobError::PluginNameInvalidError;
        return false;
    }

    QString targetName = dest;
    if (targetName[targetName.size() - 1] != '/') {
        targetName.append('/');
    }
    targetName.append(pluginName);

    if (QFile::exists(targetName)) {
        if (operation == Update) {
            KPluginMetaData oldMeta(targetName + QLatin1String("/metadata.desktop"));

            if (oldMeta.serviceTypes() != meta.serviceTypes()) {
                d->errorMessage = i18n("The new package has a different type from the old version already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::UpdatePackageTypeMismatchError;
            } else if (isVersionNewer(oldMeta.version(), meta.version())) {
                const bool ok = uninstallPackage(targetName);
                if (!ok) {
                    d->errorMessage = i18n("Impossible to remove the old installation of %1 located at %2. error: %3", pluginName, targetName, d->errorMessage);
                    d->errorCode = Package::JobError::OldVersionRemovalError;
                }
            } else {
                d->errorMessage = i18n("Not installing version %1 of %2. Version %3 already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::NewerVersionAlreadyInstalledError;
            }
        } else {
            d->errorMessage = i18n("%1 already exists", targetName);
            d->errorCode = Package::JobError::PackageAlreadyInstalledError;
        }

        if (d->errorCode != KJob::NoError) {
            d->installPath = targetName;
            return false;
        }
    }

    //install dependencies
    const QStringList dependencies = KPluginMetaData::readStringList(meta.rawData(), QStringLiteral("X-KPackage-Dependencies"));
    for(const QString &dep : dependencies) {
        QUrl depUrl(dep);
        if (!installDependency(depUrl)) {
            d->errorMessage = i18n("Could not install dependency: %1", dep);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // it's in a temp dir, so just move it over.
        const bool ok = copyFolder(path, targetName);
        removeFolder(path);
        if (!ok) {
            //qWarning() << "Could not move package to destination:" << targetName;
            d->errorMessage = i18n("Could not move package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageMoveError;
            return false;
        }
    } else {
        // it's a directory containing the stuff, so copy the contents rather
        // than move them
        const bool ok = copyFolder(path, targetName);
        if (!ok) {
            //qWarning() << "Could not copy package to destination:" << targetName;
            d->errorMessage = i18n("Could not copy package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // no need to remove the temp dir (which has been successfully moved if it's an archive)
        tempdir.setAutoRemove(false);
    }


    indexDirectory(dest, QStringLiteral("kpluginindex.json"));


    d->installPath = targetName;

    //qWarning() << "Not updating kbuildsycoca4, since that will go away. Do it yourself for now if needed.";
    return true;
}
Beispiel #12
0
FileList *Computer::getFileList(QString filter)
{
    FileList *fileList = new FileList;
    QFileInfoList list = this->directory.entryInfoList();
    QFileIconProvider *provider;

    QStringList date;
    QString tmp;
    while (!list.isEmpty())
    {
        date=list.first().lastModified().toString().split(" ");
        tmp=date.at(2)+" "+date.at(1)+" "+date.at(4);
        tmp.remove(".");
        fileList->date.append(tmp);
        fileList->name.append(list.first().fileName());
        fileList->size.append(QString::number(list.first().size()));
        provider=new QFileIconProvider;
        fileList->icon.append(provider->icon(list.first()));
        if (list.first().isDir())
            fileList->type.append("dir");
        else
        {
            if (!fileList->name.last().contains(filter))
            {
                fileList->date.removeLast();
                fileList->name.removeLast();
                fileList->size.removeLast();
                fileList->icon.removeLast();
            }
            fileList->type.append("file");
        }
        delete provider;
        list.removeFirst();
    }
    if (fileList->name.length()==0)
        return  fileList;
    //usun . i ..
    if (fileList->name.count()>0)
    {
//        if (fileList.name.first()==".")
//        {
        int x=fileList->name.indexOf(".");
        if (x!=-1)
        {
            fileList->date.removeAt(x);
            fileList->name.removeAt(x);
            fileList->size.removeAt(x);
            fileList->type.removeAt(x);
            fileList->icon.removeAt(x);
        }

        x=fileList->name.indexOf("..");
        if (x!=-1)
        {
            fileList->date.removeAt(x);
            fileList->name.removeAt(x);
            fileList->size.removeAt(x);
            fileList->type.removeAt(x);
            fileList->icon.removeAt(x);
        }
    }
    return fileList;
}