Example #1
0
void ThumbGenerator::loadDir(QImage& image, const QFileInfo& fi)
{
    QDir dir(fi.absoluteFilePath());
    dir.setFilter(QDir::Files);

    QFileInfoList list = dir.entryInfoList();
    QFileInfoList::const_iterator it = list.begin();
    const QFileInfo *f;

    bool found = false;
    while (it != list.end())
    {
        f = &(*it);
        QImageReader testread(f->absoluteFilePath());
        testread.setAutoDetectImageFormat(false);
        if (testread.canRead())
        {
            found = true;
            break;
        }
        ++it;
    }

    if (found)
    {
        loadFile(image, *f);
        return;
    }
    else
    {
        // if we didn't find the image yet
        // go into subdirs and keep looking
        dir.setFilter(QDir::Dirs);
        QFileInfoList dirlist = dir.entryInfoList();
        if (dirlist.isEmpty())
            return;

        QFileInfoList::const_iterator it = dirlist.begin();
        const QFileInfo *f;

        while (it != dirlist.end() && image.isNull() )
        {

            f = &(*it);
            ++it;

            if (f->fileName() == "." || f->fileName() == "..")
                continue;

            loadDir(image, *f);
        }
    }
}
quint64 RecursiveDirJobHelper::calculateDirSize(const QString & dir)
{
    QDir currentDir(dir);
    if ( !currentDir.exists() ) {
        emit errorOccured(Error(Error::NoSuchFileOrDirectory, dir));
        return 0;
    }

    QFileInfoList currentList = currentDir.entryInfoList(dirFilters);
    QFileInfo currentItem;
    QStack<QFileInfoList> stack;
    quint64 totalSize = 0;
    int refreshCounter = 0;

    if ( m_reportProgress ) {
        //show busy waiting indicator
        emit setMaximum(0);
        emit setValue(0);
    }

    while(1){
        if ( !currentList.isEmpty() ){
            currentItem = currentList.takeFirst();
            totalSize += stat_size(currentItem.absoluteFilePath());

            if ( currentItem.isDir() && !currentItem.isSymLink() ) {
                if ( !currentDir.cd(currentItem.fileName()) ) {
                    emit errorOccured(Error(Error::AccessDenied, currentItem.absoluteFilePath()));
                } else {
                    stack.push(currentList);
                    currentList = currentDir.entryInfoList(dirFilters);
                }
            }

            if ( m_reportProgress && (++refreshCounter % 100 == 0) )
                emit setLabelText( tr("Calculating the size of \"%1\"... %2")
                                    .arg(dir).arg(DirOperations::bytesToString(totalSize)) );

        } else { // list is empty
            if ( !stack.isEmpty() ){
                currentList = stack.pop();
                currentDir.cdUp();
            } else
                break;
        }
    }

    totalSize += stat_size(dir);
    qDebug() << "calculateDirSize" << dir << totalSize;
    return totalSize;
}
Example #3
0
void NewFormWidget::loadFrom(const QString &path, bool resourceFile, const QString &uiExtension,
                       const QString &selectedItem, QTreeWidgetItem *&selectedItemFound)
{
    const QDir dir(path);

    if (!dir.exists())
        return;

    // Iterate through the directory and add the templates
    const QFileInfoList list = dir.entryInfoList(QStringList(QLatin1String("*.") + uiExtension),
                                                 QDir::Files);

    if (list.isEmpty())
        return;

    const QChar separator = resourceFile ? QChar(QLatin1Char('/'))
                                         : QDir::separator();
    QTreeWidgetItem *root = new QTreeWidgetItem(m_ui->treeWidget);
    root->setFlags(root->flags() & ~Qt::ItemIsSelectable);
    // Try to get something that is easy to read.
    QString visiblePath = path;
    int index = visiblePath.lastIndexOf(separator);
    if (index != -1) {
        // try to find a second slash, just to be a bit better.
        const int index2 = visiblePath.lastIndexOf(separator, index - 1);
        if (index2 != -1)
            index = index2;
        visiblePath = visiblePath.mid(index + 1);
        visiblePath = QDir::toNativeSeparators(visiblePath);
    }

    const QChar underscore = QLatin1Char('_');
    const QChar blank = QLatin1Char(' ');
    root->setText(0, visiblePath.replace(underscore, blank));
    root->setToolTip(0, path);

    const QFileInfoList::const_iterator lcend = list.constEnd();
    for (QFileInfoList::const_iterator it = list.constBegin(); it != lcend; ++it) {
        if (!it->isFile())
            continue;

        QTreeWidgetItem *item = new QTreeWidgetItem(root);
        const QString text = it->baseName().replace(underscore, blank);
        if (selectedItemFound == 0 && text == selectedItem)
            selectedItemFound = item;
        item->setText(0, text);
        item->setData(0, TemplateNameRole, it->absoluteFilePath());
    }
}
Example #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);
}
Example #5
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
//    QDir * _dir=new QDir();
//   // _dir->mkdir("tmp//audio");
//    _dir->mkpath("tmp/audio");

  /**/
    QDir directory(this->getPath());
    qDebug()<<"getIOSFilePath,m    :"<<this->getPath();
    QFileInfoList fileInfoList;
    if (this->hiddenFiles)
    {
        fileInfoList = directory.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
    }
    else
    {
        fileInfoList = directory.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
    }
    QFileInfo fileInfo;
    File file;
    QList<File> *fileList = new QList<File>;
    QFileIconProvider *provider = new QFileIconProvider;
    while (!fileInfoList.isEmpty())
    {
        if (this->procesEvents)
            qApp->processEvents();
        fileInfo = fileInfoList.takeFirst();

        file.fileIcon = provider->icon(fileInfo);
        file.fileName = fileInfo.fileName();
        qDebug()<<"IOSFileName:"<<file.fileName;
        file.fileSize = QString::number(fileInfo.size());
        file.fileDate = fileInfo.lastModified().toString("MMM dd yyyy");
        file.filePath = fileInfo.absoluteFilePath();
        file.filePermissions = "";
        file.fileOwner = fileInfo.owner();
        if (fileInfo.isDir())
            file.fileType = "dir";
        else
            file.fileType = "file";

        fileList->append(file);
    }
    delete provider;
    return fileList;
    return a.exec();
}
Example #6
0
/**
 * @brief QgsServer::defaultProjectFile
 * @return the default project file
 */
QFileInfo QgsServer::defaultProjectFile()
{
  QDir currentDir;
  fprintf( FCGI_stderr, "current directory: %s\n", currentDir.absolutePath().toUtf8().constData() );
  QStringList nameFilterList;
  nameFilterList << QStringLiteral( "*.qgs" );
  QFileInfoList projectFiles = currentDir.entryInfoList( nameFilterList, QDir::Files, QDir::Name );
  for ( int x = 0; x < projectFiles.size(); x++ )
  {
    QgsMessageLog::logMessage( projectFiles.at( x ).absoluteFilePath(), QStringLiteral( "Server" ), QgsMessageLog::INFO );
  }
  if ( projectFiles.isEmpty() )
  {
    return QFileInfo();
  }
  return projectFiles.at( 0 );
}
//! [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();
}
Example #8
0
void ImportMusicDialog::scanDirectory(QString &directory, vector<TrackInfo*> *tracks)
{
    QDir d(directory);

    if (!d.exists())
        return;

    const QFileInfoList list = d.entryInfoList();
    if (list.isEmpty())
        return;

    QFileInfoList::const_iterator it = list.begin();
    const QFileInfo *fi;

    while (it != list.end())
    {
        fi = &(*it);
        ++it;
        if (fi->fileName() == "." || fi->fileName() == "..")
            continue;
        QString filename = fi->absoluteFilePath();
        if (fi->isDir())
            scanDirectory(filename, tracks);
        else
        {
            Decoder *decoder = Decoder::create(filename, NULL, NULL, true);
            if (decoder)
            {
                Metadata *metadata = decoder->getMetadata();
                if (metadata)
                {
                    TrackInfo * track = new TrackInfo;
                    track->metadata = metadata;
                    track->isNewTune = Ripper::isNewTune(metadata->Artist(),
                            metadata->Album(), metadata->Title());
                    track->metadataHasChanged = false;
                    tracks->push_back(track);
                    m_sourceFiles.append(filename);
                }

                delete decoder;
            }
        }
    }
}
/**********
*返回值:0成功
*1原包名不存在
*2创建包出错
*3目的包名已经存在
*4替换包名过程出错
***********/
int PathManager::RenamePak(QString &path, QString &oldPakName, QString &newPakName)
{
	QString oldName = oldPakName;
	QString newName = newPakName;
	oldName.replace(".", "/");
	newName.replace(".", "/");

	QString srcDir = path + "/" + oldName;
	QString destDir = path + "/" + newName;
	QDir dirSrc(srcDir);
	QDir dirDest(destDir);
	if (!dirSrc.exists()){
		return 1;
	}

	dirSrc.setFilter(QDir::NoDotAndDotDot | QDir::Files);
	QFileInfoList allFiles = dirSrc.entryInfoList();
	if (allFiles.isEmpty()){
		return 1;
	}

	if (!dirDest.exists() && !dirDest.mkpath(destDir)){
		return 2;
	}
	dirDest.setFilter(QDir::NoDotAndDotDot | QDir::Files);
	if (!dirDest.entryInfoList().isEmpty()){
		return 3;
	}

	for (QFileInfoList::iterator ite = allFiles.begin(); ite != allFiles.end(); ite++){
		QString tmpName = ite->absoluteFilePath();
		tmpName = tmpName.mid(tmpName.lastIndexOf("/") + 1);
		if (!dirDest.exists()){
			if (dirDest.mkpath(destDir)){
				return 4;
			}
		}
		if (!CopyFile(ite->absoluteFilePath(), destDir + "/" + tmpName, true) || !QFile::remove(ite->absoluteFilePath())){
			return 4;
		}
	}

	RemoveEmptyDirFromDeepest(srcDir);
	return 0;
}
Example #10
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    moded = false;

    home.setPath(QDir::homePath().append(QDir::separator()).append(".qnotes"));
    if (!home.exists()) {
        home.setPath(QDir::homePath());
        home.mkdir(".qnotes");
        home.cd(".qnotes");
    }
    home.setFilter(QDir::Files | QDir::NoSymLinks);
    home.setSorting(QDir::Time);
    QFileInfoList list = home.entryInfoList();

    if (list.isEmpty()) {
        ui->listWidget->addItem(tr("Vítejte"));
        ui->listWidget->setCurrentRow(0);
        cur_note = tr("Vítejte");
        ui->plainTextEdit->setPlainText(tr("Tuto poznámku můžete klidně smazat."));
        save();
    } else {
        for (int i = 0; i < list.size(); ++i) {
            QFileInfo fileInfo = list.at(i);

            ui->listWidget->addItem(fileInfo.fileName());
        }
        ui->listWidget->setCurrentRow(0);
        cur_note = ui->listWidget->item(0)->text();
        load();
    }

    connect(ui->actionUlozit, SIGNAL(triggered()), this, SLOT(save()));
    connect(ui->actionVypnout, SIGNAL(triggered()), this, SLOT(squit()));
    connect(ui->actionPridat, SIGNAL(triggered()), this, SLOT(add()));
    connect(ui->actionSmazat, SIGNAL(triggered()), this, SLOT(rm()));
    connect(ui->actionPrejmenovat, SIGNAL(triggered()), this, SLOT(ren()));
    connect(ui->plainTextEdit, SIGNAL(textChanged()), this, SLOT(mod()));
    connect(ui->actionO, SIGNAL(triggered()), this, SLOT(about()));
    connect(ui->listWidget, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(change(QListWidgetItem*)));
    connect(ui->actionO_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}
Example #11
0
QString findD3dCompiler(Platform platform, const QString &qtBinDir, unsigned wordSize)
{
    const QString prefix = QStringLiteral("D3Dcompiler_");
    const QString suffix = QLatin1String(windowsSharedLibrarySuffix);
    // Get the DLL from Kit 8.0 onwards
    const QString kitDir = QString::fromLocal8Bit(qgetenv("WindowsSdkDir"));
    if (!kitDir.isEmpty()) {
        QString redistDirPath = QDir::cleanPath(kitDir) + QStringLiteral("/Redist/D3D/");
        if (platform & ArmBased) {
            redistDirPath += QStringLiteral("arm");
        } else {
            redistDirPath += wordSize == 32 ? QStringLiteral("x86") : QStringLiteral("x64");
        }
        QDir redistDir(redistDirPath);
        if (redistDir.exists()) {
            const QFileInfoList files = redistDir.entryInfoList(QStringList(prefix + QLatin1Char('*') + suffix), QDir::Files);
            if (!files.isEmpty())
                return files.front().absoluteFilePath();
        }
    }
    QStringList candidateVersions;
    for (int i = 47 ; i >= 40 ; --i)
        candidateVersions.append(prefix + QString::number(i) + suffix);
    // Check the bin directory of the Qt SDK (in case it is shadowed by the
    // Windows system directory in PATH).
    foreach (const QString &candidate, candidateVersions) {
        const QFileInfo fi(qtBinDir + QLatin1Char('/') + candidate);
        if (fi.isFile())
            return fi.absoluteFilePath();
    }
    // Find the latest D3D compiler DLL in path (Windows 8.1 has d3dcompiler_47).
    if (platform & IntelBased) {
        QString errorMessage;
        unsigned detectedWordSize;
        foreach (const QString &candidate, candidateVersions) {
            const QString dll = findInPath(candidate);
            if (!dll.isEmpty()
                && readPeExecutable(dll, &errorMessage, 0, &detectedWordSize, 0)
                && detectedWordSize == wordSize) {
                return dll;
            }
        }
    }
Example #12
0
void CycleRead::read_dcmrawdatapath(QString dcmrawpath)
{
  QFileInfo file;
  QDir dcmrawdir;

  dcmrawdir.setPath(dcmrawpath);


  QFileInfoList fList = dcmrawdir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files , QDir::Name);

  if (!fList.isEmpty())
//    QMessageBox::warning(this, tr("Warning"), "No Files in Directory!\n"+file.absoluteFilePath(),
//                               QMessageBox::Ok);

  {
    for(int i=0;i < fList.size(); ++i)
    {
      file = fList.at(i);

      if(("dcm" == file.completeSuffix()) && (!_all_filenames.contains(file.filePath())))
      {
        _all_filenames.push_back(file.filePath());

        if(_fileblocks.isEmpty())
        { //if its the fist file - and no fileblocks exist - create first
          FileBlock fileblock;
          fileblock.set_file(file);
          _fileblocks.push_back(fileblock);
        }
        else
        {
          if(!_fileblocks.last().set_file(file))
          { //if actual file is not for actual block
            FileBlock fileblock;
            fileblock.set_file(file);
            _fileblocks.push_back(fileblock);  //create new block at the back
          }
        }
      }
    }
  }
}
Example #13
0
void Q3LocalFs::operationListChildren( Q3NetworkOperation *op )
{
#ifdef QLOCALFS_DEBUG
    qDebug( "Q3LocalFs: operationListChildren" );
#endif
    op->setState( StInProgress );

    dir = QDir( url()->path() );
    dir.setNameFilter( url()->nameFilter() );
    dir.setMatchAllDirs( true );
    if ( !dir.isReadable() ) {
	QString msg = tr( "Could not read directory\n%1" ).arg( url()->path() );
	op->setState( StFailed );
	op->setProtocolDetail( msg );
	op->setErrorCode( (int)ErrListChildren );
	emit finished( op );
	return;
    }

    QFileInfoList filist = dir.entryInfoList(QDir::All | QDir::Hidden | QDir::System);
    if ( filist.isEmpty() ) {
	QString msg = tr( "Could not read directory\n%1" ).arg( url()->path() );
	op->setState( StFailed );
	op->setProtocolDetail( msg );
	op->setErrorCode( (int)ErrListChildren );
	emit finished( op );
	return;
    }

    emit start( op );

    Q3ValueList<QUrlInfo> infos;
    for (int i = 0; i < filist.size(); ++i) {
        QFileInfo fi = filist.at(i);
	infos << QUrlInfo( fi.fileName(), convertPermissions(&fi), fi.owner(), fi.group(),
			   fi.size(), fi.lastModified(), fi.lastRead(), fi.isDir(), fi.isFile(),
			   fi.isSymLink(), fi.isWritable(), fi.isReadable(), fi.isExecutable() );
    }
    emit newChildren( infos, op );
    op->setState( StDone );
    emit finished( op );
}
Example #14
0
void NewWizardPage4::buildTemplatesList()
      {

      QDir dir(mscoreGlobalShare + "/templates");
      QFileInfoList fil = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Readable | QDir::Dirs | QDir::Files, QDir::Name);
      if(fil.isEmpty()){
          fil.append(QFileInfo(QFile(":data/Empty_Score.mscz")));
          }

      QDir myTemplatesDir(preferences.getString(PREF_APP_PATHS_MYTEMPLATES));
      fil.append(myTemplatesDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Readable | QDir::Dirs | QDir::Files, QDir::Name));

      // append templates directories from extensions
      QStringList extensionsDir = Extension::getDirectoriesByType(Extension::templatesDir);
      for (QString extDir : extensionsDir) {
            QDir extTemplateDir(extDir);
            fil.append(extTemplateDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Readable | QDir::Dirs | QDir::Files, QDir::Name));
            }
      templateFileBrowser->setScores(fil);
      }
Example #15
0
void ThumbGenerator::loadDir(QImage& image, const QFileInfo& fi)
{
    QDir dir(fi.absoluteFilePath());
    dir.setFilter(QDir::Files);

    QFileInfoList list = dir.entryInfoList();

    for (QFileInfoList::const_iterator it = list.begin();
         it != list.end() && !m_cancel; ++it)
    {
        const QFileInfo *f = &(*it);
        QImageReader testread(f->absoluteFilePath());
        if (testread.canRead())
        {
            loadFile(image, *f);
            return;
        }
    }

    // If we are supposed to cancel, don't recurse into subdirs, just quit
    if (m_cancel)
        return;

    // if we didn't find the image yet
    // go into subdirs and keep looking
    dir.setFilter(QDir::Dirs);
    QFileInfoList dirlist = dir.entryInfoList();
    if (dirlist.isEmpty())
        return;

    for (QFileInfoList::const_iterator it = dirlist.begin();
         it != dirlist.end() && image.isNull() && !m_cancel; ++it)
    {
        const QFileInfo *f = &(*it);

        if (f->fileName() == "." || f->fileName() == "..")
            continue;

        loadDir(image, *f);
    }
}
Example #16
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");
      }
    }
  }
}
Example #17
0
void FileSettings::constrainCacheToMaxSize(int size)
{
	const QString dataPath = dataFilePath();
	QDir dataDir(dataPath);

	// get size of cache
	QFileInfoList dataFileInfoList = dataDir.entryInfoList(QDir::Files | QDir::NoDotDot, QDir::Time);
	int cacheSize = QFileInfo(dataPath).size();
	for (int i = 0; i < dataFileInfoList.size(); ++i)
		cacheSize += dataFileInfoList.at(i).size();

	while (cacheSize > size) // remove oldest file settings from cache
	{
		if (dataFileInfoList.isEmpty())
			break;
		const QString fileName = dataFileInfoList.last().fileName();
		int fileSize = dataFileInfoList.takeLast().size();
		if (dataDir.remove(fileName))
			cacheSize -= fileSize;
	}
}
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();
}
Example #19
0
QList<File> *Computer::getFileList()
{
    QDir directory(this->getPath());
    QFileInfoList fileInfoList;
    if (this->hiddenFiles)
    {
        fileInfoList = directory.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
    }
    else
    {
        fileInfoList = directory.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
    }
    QFileInfo fileInfo;
    File file;
    QList<File> *fileList = new QList<File>;
    QFileIconProvider *provider = new QFileIconProvider;
    while (!fileInfoList.isEmpty())
    {
        if (this->procesEvents)
            qApp->processEvents();
        fileInfo = fileInfoList.takeFirst();

        file.fileIcon = provider->icon(fileInfo);
        file.fileName = fileInfo.fileName();
        file.fileSize = QString::number(fileInfo.size());
        file.fileDate = fileInfo.lastModified().toString("MMM dd yyyy");
        file.filePath = fileInfo.absoluteFilePath();
        file.filePermissions = "";
        file.fileOwner = fileInfo.owner();
        if (fileInfo.isDir())
            file.fileType = "dir";
        else
            file.fileType = "file";

        fileList->append(file);
    }
    delete provider;
    return fileList;
}
Example #20
0
void Parser::recursive(const QString &dirPath)
{
    itsDir->cd(dirPath);

    dirFilters();

    QFileInfoList list = itsDir->entryInfoList();
    QTextStream itsOut(stdout);

    for(int iList = 0; iList < list.size(); ++iList)
    {
        QFileInfo fileInfo = list.at(iList);
        QString filePath = fileInfo.absoluteFilePath();

        if(fileInfo.isDir())
        {
            if(itsOptions.testFlag(SHOWDIRS) && !list.isEmpty())
            {
                if(itsOptions.testFlag(ABSOLUTEPATH))
                {
                    itsOut << "\nSUBDIR:\n" << QDir::toNativeSeparators(filePath) << ":\n";
                }
                else
                {
                    QString temp = filePath;
                    itsOut << "\nSUBDIR:\n.." << QDir::toNativeSeparators(temp.remove(0, QString(itsArgv[1]).size())) << ":\n";
                }
            }
            itsOut.flush(); // чтобы после ROOT DIR:\nпуть к корневой папке\n было "..ке\n", т.е. сробатывл перевод строки
            // + к тому же, чтобы, если там будут нужные для вывода файлы, они выводились в правильном порядке
            recursive(filePath);
        }
        else
        {
            itsOut << fileInfo.fileName() << "\n";
        }
    }
}
Example #21
0
int ChildCountThread::getChildCount(const QString &filepath)
{
    QDir d(filepath);

    bool isGallery;
    QFileInfoList gList = d.entryInfoList(QStringList("serial*.dat"),
                                          QDir::Files);
    isGallery = (gList.count() != 0);

    QFileInfoList list = d.entryInfoList(GalleryUtil::GetMediaFilter(),
                                         QDir::Files | QDir::AllDirs);

    if (list.isEmpty())
        return 0;

    QFileInfoList::const_iterator it = list.begin();
    const QFileInfo *fi;

    int count = 0;
    while (it != list.end())
    {
        fi = &(*it);
        ++it;
        if (fi->fileName() == "." || fi->fileName() == "..")
            continue;

        // remove these already-resized pictures.
        if (isGallery && (
                (fi->fileName().indexOf(".thumb.") > 0) ||
                (fi->fileName().indexOf(".sized.") > 0) ||
                (fi->fileName().indexOf(".highlight.") > 0)))
            continue;

        count++;
    }

    return count;
}
/**
\param idasiento
**/
void BcAsientoInteligenteView::inicializa ( int idasiento )
{
    BL_FUNC_DEBUG
    numasiento = idasiento;
    inicializaVariables();

    QDir dir ( g_confpr->value( CONF_DIR_AINTELIGENTES ) );
    dir.setFilter ( QDir::Files );
    dir.setNameFilters ( QStringList ( "*.xml" ) );
    dir.setSorting ( QDir::Size | QDir::Reversed );

    QFileInfoList list = dir.entryInfoList();

    if ( list.size() > 0 ) {
        /// Cargamos el combo con los ficheros de asientos inteligentes disponibles
        QStringList listaOrdenada;
        while ( !list.isEmpty() ) {
            QFileInfo fileInfo = list.takeFirst();
            listaOrdenada.append ( fileInfo.fileName().replace ( ".xml", "" ) ); /// cogemos los nombres de los ficheros sin la extension
            listasientos.append ( fileInfo.filePath() ); /// y la ruta completa
        }
        listaOrdenada.sort(); /// se ordena la lista alfabeticamente
        listasientos.sort(); /// y la de la ruta, que se ordenara igual
        while ( !listaOrdenada.isEmpty() )
            mui_comboainteligentes->addItem ( listaOrdenada.takeFirst() ); /// y se carga en el combo

        /// Calculamos el n&uacute;mero de d&iacute;gitos que tiene una cuenta.
        mainCompany() ->begin();
        QString query1 = "SELECT * FROM configuracion WHERE nombre = 'CodCuenta'";
        BlDbRecordSet *cursoraux1 = mainCompany() ->loadQuery ( query1, "codcuenta" );
        numDigitos = cursoraux1->value( 2 ).length();
        mainCompany() ->commit();
        delete cursoraux1;

        on_mui_comboainteligentes_activated ( 0 );
    }
    
}
Example #23
0
bool Utils::deleteDir(const QString& dirPath)
{
    QDir dir(dirPath);
    if (!dir.exists())
        return false;

    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks);

    QFileInfoList infoList = dir.entryInfoList();
    if (infoList.isEmpty())
        return false;

    QFileInfoList::iterator it = infoList.begin();
    QFileInfo fi;

    while( it != infoList.end() )
    {
        fi = *it;
        if(fi.fileName() == "." || fi.fileName() == ".." )
        {
            ++it;
            continue;
        }

        if( fi.isDir() )
        {
            deleteDir(fi.absoluteFilePath());
        }
        else if( fi.isFile() )
            dir.remove(fi.absoluteFilePath());

        ++it;
    }

    dir.rmdir(dir.absolutePath());
    return true;
}
Example #24
0
bool myRemovePath(QString dirPath, bool deleteHidden, bool deleteSelf)
{
    qDebug()<<"removePath的进程"<<QThread::currentThread ();
    QDir entry (dirPath);
    if(!entry.exists()||!entry.isReadable())
        return false;
    entry.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden);
    QFileInfoList dirList = entry.entryInfoList();
    bool bHaveHiddenFile = false;

    if(!dirList.isEmpty()) {
        for( int i = 0; i < dirList.size() ; ++i) {
            QFileInfo info = dirList.at(i);
            if(info.isHidden() && !deleteHidden) {
                bHaveHiddenFile = true;
                continue;
            }
            QString path = info.absoluteFilePath();
            if(info.isDir()) {
                if(!myRemovePath(path, deleteHidden, true))
                    return false;
            }else if(info.isFile()) {
                if(!QFile::remove(path))
                    return false;
            }else
                return false;
        }
    }

    if(deleteSelf && !bHaveHiddenFile) {
        if(!entry.rmdir(dirPath)) {
            return false;
        }
    }
    return true;
}
Example #25
0
/*!
 * \brief Builds a list of all the files found descending recursively
 *        into the given directory
 *
 * \param directory Directory to begin search
 * \param music_files A pointer to the MusicLoadedMap to store the results
 * \param parentid The id of the parent directory in the music_directories
 *                 table. The root directory should have an id of 0
 *
 * \returns Nothing.
 */
void FileScanner::BuildFileList(QString &directory, MusicLoadedMap &music_files, int parentid)
{
    QDir d(directory);

    if (!d.exists())
        return;

    QFileInfoList list = d.entryInfoList();
    if (list.isEmpty())
        return;

    QFileInfoList::const_iterator it = list.begin();
    const QFileInfo *fi;

    /* Recursively traverse directory, calling QApplication::processEvents()
       every now and then to ensure the UI updates */
    int update_interval = 0;
    int newparentid = 0;
    while (it != list.end())
    {
        fi = &(*it);
        ++it;
        if (fi->fileName() == "." || fi->fileName() == "..")
            continue;
        QString filename = fi->absoluteFilePath();
        if (fi->isDir())
        {

            QString dir(filename);
            dir.remove(0, m_startdir.length());

            newparentid = m_directoryid[dir];

            if (newparentid == 0)
            {
                int id = GetDirectoryId(dir, parentid);
                m_directoryid[dir] = id;

                if (id > 0)
                {
                    newparentid = id;
                }
                else
                {
                    LOG(VB_GENERAL, LOG_ERR,
                        QString("Failed to get directory id for path %1")
                            .arg(dir));
                }
            }

            BuildFileList(filename, music_files, newparentid);

            qApp->processEvents ();
        }
        else
        {
            if (++update_interval > 100)
            {
                qApp->processEvents();
                update_interval = 0;
            }

            music_files[filename] = kFileSystem;
        }
    }
}
Example #26
0
void ScoreBrowser::setScores(QFileInfoList& s)
      {
      qDeleteAll(scoreLists);
      scoreLists.clear();

      QVBoxLayout* l = static_cast<QVBoxLayout*>(scoreList->layout());
      while (l->count())
            l->removeItem(l->itemAt(0));

      ScoreListWidget* sl = 0;

      QStringList filter = { "*.mscz" };

      if (_showCustomCategory)
            std::sort(s.begin(), s.end(), [](QFileInfo a, QFileInfo b)->bool { return a.fileName() < b.fileName(); });

      QSet<QString> entries; //to avoid duplicates
      for (const QFileInfo& fi : s) {
            if (fi.isDir()) {
                  QString s(fi.fileName());
                  if (!s.isEmpty() && s[0].isNumber() && _stripNumbers)
                        s = s.mid(3);
                  s = s.replace('_', ' ');
                  QLabel* label = new QLabel(s);
                  QFont f = label->font();
                  f.setBold(true);
                  label->setFont(f);
                  static_cast<QVBoxLayout*>(l)->addWidget(label);
                  QDir dir(fi.filePath());
                  sl = createScoreList();
                  l->addWidget(sl);
                  unsigned count = 0; //nbr of entries added
                  for (const QFileInfo& fi : dir.entryInfoList(filter, QDir::Files, QDir::Name)){
                        if (entries.contains(fi.filePath()))
                            continue;
                        sl->addItem(genScoreItem(fi, sl));
                        count++;
                        entries.insert(fi.filePath());
                        }
                  if (count == 0) {
                        delete label;
                        delete sl;
                        }
                  sl = 0;
                  }
            }
      for (const QFileInfo& fi : s) {
            if (fi.isFile()) {
                  QString s = fi.filePath();
                  if (entries.contains(s))
                      continue;
                  if (s.endsWith(".mscz") || s.endsWith(".mscx")) {
                        if (!sl) {
                              if (_showCustomCategory) {
                                    QLabel* label = new QLabel(tr("Custom Templates"));
                                    QFont f = label->font();
                                    f.setBold(true);
                                    label->setFont(f);
                                    l->insertWidget(2,label);
                                    }
                              sl = createScoreList();
                              l->insertWidget(3,sl);
                              }
                        sl->addItem(genScoreItem(fi, sl));
                        entries.insert(s);
                        }
                  }
            }
      }
Example #27
0
int main(int argc, char *argv[])
{
	QString workDir;
#ifdef Q_OS_MAC
    if (QDir(QString()).absolutePath() == "/") {
		QString first = argc ? QString::fromLocal8Bit(argv[0]) : QString();
		if (!first.isEmpty()) {
			QFileInfo info(first);
			if (info.exists()) {
				QDir result(info.absolutePath() + "/../../..");
				workDir = result.absolutePath() + '/';
			}
		}
	}
#endif

	QString remove;
	int version = 0;
	QFileInfoList files;
	for (int i = 0; i < argc; ++i) {
		if (string("-path") == argv[i] && i + 1 < argc) {
			QString path = workDir + QString(argv[i + 1]);
			QFileInfo info(path);
			files.push_back(info);
			if (remove.isEmpty()) remove = info.canonicalPath() + "/";
		} else if (string("-version") == argv[i] && i + 1 < argc) {
			version = QString(argv[i + 1]).toInt();
		} else if (string("-dev") == argv[i]) {
			DevChannel = true;
		} else if (string("-beta") == argv[i] && i + 1 < argc) {
			BetaVersion = QString(argv[i + 1]).toULongLong();
			if (BetaVersion > version * 1000ULL && BetaVersion < (version + 1) * 1000ULL) {
				DevChannel = false;
				BetaSignature = countBetaVersionSignature(BetaVersion);
				if (BetaSignature.isEmpty()) {
					return -1;
				}
			} else {
				cout << "Bad -beta param value passed, should be for the same version: " << version << ", beta: " << BetaVersion << "\n";
				return -1;
			}
		}
	}

	if (files.isEmpty() || remove.isEmpty() || version <= 1016 || version > 999999999) {
#ifdef Q_OS_WIN
		cout << "Usage: Packer.exe -path {file} -version {version} OR Packer.exe -path {dir} -version {version}\n";
#elif defined Q_OS_MAC
		cout << "Usage: Packer.app -path {file} -version {version} OR Packer.app -path {dir} -version {version}\n";
#else
		cout << "Usage: Packer -path {file} -version {version} OR Packer -path {dir} -version {version}\n";
#endif
		return -1;
	}

	bool hasDirs = true;
	while (hasDirs) {
		hasDirs = false;
		for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) {
			QFileInfo info(*i);
			QString fullPath = info.canonicalFilePath();
			if (info.isDir()) {
				hasDirs = true;
				files.erase(i);
				QDir d = QDir(info.absoluteFilePath());
				QString fullDir = d.canonicalPath();
				QStringList entries = d.entryList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
				files.append(d.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot));
				break;
			} else if (!info.isReadable()) {
				cout << "Can't read: " << info.absoluteFilePath().toUtf8().constData() << "\n";
				return -1;
			} else if (info.isHidden()) {
				hasDirs = true;
				files.erase(i);
				break;
			}
		}
	}
	for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) {
		QFileInfo info(*i);
		if (!info.canonicalFilePath().startsWith(remove)) {
			cout << "Can't find '" << remove.toUtf8().constData() << "' in file '" << info.canonicalFilePath().toUtf8().constData() << "' :(\n";
			return -1;
		}
	}

	QByteArray result;
	{
		QBuffer buffer(&result);
		buffer.open(QIODevice::WriteOnly);
		QDataStream stream(&buffer);
		stream.setVersion(QDataStream::Qt_5_1);

		if (BetaVersion) {
			stream << quint32(0x7FFFFFFF);
			stream << quint64(BetaVersion);
		} else {
			stream << quint32(version);
		}

		stream << quint32(files.size());
		cout << "Found " << files.size() << " file" << (files.size() == 1 ? "" : "s") << "..\n";
		for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) {
			QFileInfo info(*i);
			QString fullName = info.canonicalFilePath();
			QString name = fullName.mid(remove.length());
			cout << name.toUtf8().constData() << " (" << info.size() << ")\n";

			QFile f(fullName);
			if (!f.open(QIODevice::ReadOnly)) {
				cout << "Can't open '" << fullName.toUtf8().constData() << "' for read..\n";
				return -1;
			}
			QByteArray inner = f.readAll();
			stream << name << quint32(inner.size()) << inner;
#if defined Q_OS_MAC || defined Q_OS_LINUX
			stream << (QFileInfo(fullName).isExecutable() ? true : false);
#endif
		}
		if (stream.status() != QDataStream::Ok) {
			cout << "Stream status is bad: " << stream.status() << "\n";
			return -1;
		}
	}

	int32 resultSize = result.size();
	cout << "Compression start, size: " << resultSize << "\n";

	QByteArray compressed, resultCheck;
#ifdef Q_OS_WIN // use Lzma SDK for win
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header

	compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size

	size_t compressedLen = compressed.size() - hSize;
	size_t outPropsSize = LZMA_PROPS_SIZE;
	uchar *_dest = (uchar*)(compressed.data() + hSize);
	size_t *_destLen = &compressedLen;
	const uchar *_src = (const uchar*)(result.constData());
	size_t _srcLen = result.size();
	uchar *_outProps = (uchar*)(compressed.data() + hSigLen + hShaLen);
	int res = LzmaCompress(_dest, _destLen, _src, _srcLen, _outProps, &outPropsSize, 9, 64 * 1024 * 1024, 4, 0, 2, 273, 2);
	if (res != SZ_OK) {
		cout << "Error in compression: " << res << "\n";
		return -1;
	}
	compressed.resize(int(hSize + compressedLen));
	memcpy(compressed.data() + hSigLen + hShaLen + hPropsLen, &resultSize, hOriginalSizeLen);

	cout << "Compressed to size: " << compressedLen << "\n";

	cout << "Checking uncompressed..\n";

	int32 resultCheckLen;
	memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen);
	if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) {
		cout << "Bad result len: " << resultCheckLen << "\n";
		return -1;
	}
	resultCheck.resize(resultCheckLen);

	size_t resultLen = resultCheck.size();
	SizeT srcLen = compressedLen;
	int uncompressRes = LzmaUncompress((uchar*)resultCheck.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE);
	if (uncompressRes != SZ_OK) {
		cout << "Uncompress failed: " << uncompressRes << "\n";
		return -1;
	}
	if (resultLen != size_t(result.size())) {
		cout << "Uncompress bad size: " << resultLen << ", was: " << result.size() << "\n";
		return -1;
	}
#else // use liblzma for others
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header

	compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size

	size_t compressedLen = compressed.size() - hSize;

	lzma_stream stream = LZMA_STREAM_INIT;

	int preset = 9 | LZMA_PRESET_EXTREME;
	lzma_ret ret = lzma_easy_encoder(&stream, preset, LZMA_CHECK_CRC64);
	if (ret != LZMA_OK) {
		const char *msg;
		switch (ret) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
			case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		cout << "Error initializing the encoder: " << msg << " (error code " << ret << ")\n";
		return -1;
	}

	stream.avail_in = resultSize;
	stream.next_in = (uint8_t*)result.constData();
	stream.avail_out = compressedLen;
	stream.next_out = (uint8_t*)(compressed.data() + hSize);

	lzma_ret res = lzma_code(&stream, LZMA_FINISH);
	compressedLen -= stream.avail_out;
	lzma_end(&stream);
	if (res != LZMA_OK && res != LZMA_STREAM_END) {
		const char *msg;
		switch (res) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_DATA_ERROR: msg = "File size limits exceeded"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		cout << "Error in compression: " << msg << " (error code " << res << ")\n";
		return -1;
	}

	compressed.resize(int(hSize + compressedLen));
	memcpy(compressed.data() + hSigLen + hShaLen, &resultSize, hOriginalSizeLen);

	cout << "Compressed to size: " << compressedLen << "\n";

	cout << "Checking uncompressed..\n";

	int32 resultCheckLen;
	memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen, hOriginalSizeLen);
	if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) {
		cout << "Bad result len: " << resultCheckLen << "\n";
		return -1;
	}
	resultCheck.resize(resultCheckLen);

	size_t resultLen = resultCheck.size();

	stream = LZMA_STREAM_INIT;

	ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED);
	if (ret != LZMA_OK) {
		const char *msg;
		switch (ret) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
			case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		cout << "Error initializing the decoder: " << msg << " (error code " << ret << ")\n";
		return -1;
	}

	stream.avail_in = compressedLen;
	stream.next_in = (uint8_t*)(compressed.constData() + hSize);
	stream.avail_out = resultLen;
	stream.next_out = (uint8_t*)resultCheck.data();

	res = lzma_code(&stream, LZMA_FINISH);
	if (stream.avail_in) {
		cout << "Error in decompression, " << stream.avail_in << " bytes left in _in of " << compressedLen << " whole.\n";
		return -1;
	} else if (stream.avail_out) {
		cout << "Error in decompression, " << stream.avail_out << " bytes free left in _out of " << resultLen << " whole.\n";
		return -1;
	}
	lzma_end(&stream);
	if (res != LZMA_OK && res != LZMA_STREAM_END) {
		const char *msg;
		switch (res) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break;
			case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break;
			case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break;
			case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		cout << "Error in decompression: " << msg << " (error code " << res << ")\n";
		return -1;
	}
#endif
	if (memcmp(result.constData(), resultCheck.constData(), resultLen)) {
		cout << "Data differ :(\n";
		return -1;
	}
	/**/
	result = resultCheck = QByteArray();

	cout << "Counting SHA1 hash..\n";

	uchar sha1Buffer[20];
	memcpy(compressed.data() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, uint32(compressedLen + hPropsLen + hOriginalSizeLen), sha1Buffer), hShaLen); // count sha1

	uint32 siglen = 0;

	cout << "Signing..\n";
	RSA *prKey = PEM_read_bio_RSAPrivateKey(BIO_new_mem_buf(const_cast<char*>((DevChannel || BetaVersion) ? PrivateDevKey : PrivateKey), -1), 0, 0, 0);
	if (!prKey) {
		cout << "Could not read RSA private key!\n";
		return -1;
	}
	if (RSA_size(prKey) != hSigLen) {
		cout << "Bad private key, size: " << RSA_size(prKey) << "\n";
		RSA_free(prKey);
		return -1;
	}
	if (RSA_sign(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (uchar*)(compressed.data()), &siglen, prKey) != 1) { // count signature
		cout << "Signing failed!\n";
		RSA_free(prKey);
		return -1;
	}
	RSA_free(prKey);

	if (siglen != hSigLen) {
		cout << "Bad signature length: " << siglen << "\n";
		return -1;
	}

	cout << "Checking signature..\n";
	RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>((DevChannel || BetaVersion) ? PublicDevKey : PublicKey), -1), 0, 0, 0);
	if (!pbKey) {
		cout << "Could not read RSA public key!\n";
		return -1;
	}
	if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), siglen, pbKey) != 1) { // verify signature
		RSA_free(pbKey);
		cout << "Signature verification failed!\n";
		return -1;
	}
	cout << "Signature verified!\n";
	RSA_free(pbKey);
#ifdef Q_OS_WIN
	QString outName(QString("tupdate%1").arg(BetaVersion ? BetaVersion : version));
#elif defined Q_OS_MAC
	QString outName(QString("tmacupd%1").arg(BetaVersion ? BetaVersion : version));
#elif defined Q_OS_LINUX32
    QString outName(QString("tlinux32upd%1").arg(BetaVersion ? BetaVersion : version));
#elif defined Q_OS_LINUX64
    QString outName(QString("tlinuxupd%1").arg(BetaVersion ? BetaVersion : version));
#else
#error Unknown platform!
#endif
	if (BetaVersion) {
		outName += "_" + BetaSignature;
	}
	QFile out(outName);
	if (!out.open(QIODevice::WriteOnly)) {
		cout << "Can't open '" << outName.toUtf8().constData() << "' for write..\n";
		return -1;
	}
	out.write(compressed);
	out.close();

	if (BetaVersion) {
		QString keyName(QString("tbeta_%1_key").arg(BetaVersion));
		QFile key(keyName);
		if (!key.open(QIODevice::WriteOnly)) {
			cout << "Can't open '" << keyName.toUtf8().constData() << "' for write..\n";
			return -1;
		}
		key.write(BetaSignature.toUtf8());
		key.close();
	}

	cout << "Update file '" << outName.toUtf8().constData() << "' written successfully!\n";

	return 0;
}
void RecursiveDirJobHelper::recursiveRmDir(const QString & dir)
{
    QDir currentDir(dir);
    if ( !currentDir.exists() ) {
        qWarning() << "recursiveRmDir: trying to remove non-existent directory" << dir;
        if (m_reportProgress) {
            //no files to be removed, so set the progressbar to 100%
            emit setMaximum(1);
            emit setValue(1);
        }
        return; // directory gone, no work to do
    }

    QFileInfoList currentList = currentDir.entryInfoList(dirFilters);
    QFileInfo currentItem;
    QStack<QFileInfoList> stack;
    quint64 bytesRemoved = 0;

    if (m_reportProgress) {
        quint64 dirSize = calculateDirSize(dir);
        emit setLabelText(tr("Removing directory \"%1\"...").arg(dir));
        if (dirSize > 0) {
            emit setMaximum(dirSize);
            //start with the size of the directory to be removed.
            //we do this before starting removing files, because on some filesystems
            //(like reiserfs) the directory size is variable and will be smaller
            //when all files have been removed
            bytesRemoved += stat_size(dir);
            emit setValue(bytesRemoved);
        } else {
            //no files to be removed, so set the progressbar to 100%
            emit setMaximum(1);
            emit setValue(1);
        }
    }

    while(1)
    {
        if ( !currentList.isEmpty() ){
            currentItem = currentList.takeFirst();

            if ( m_reportProgress ) {
                bytesRemoved += stat_size(currentItem.absoluteFilePath());
                emit setValue(bytesRemoved);
            }

            if ( currentItem.isDir() && !currentItem.isSymLink() )
            {
                if ( !currentDir.cd(currentItem.fileName()) ) {
                    emit errorOccured(Error(Error::AccessDenied, currentItem.absoluteFilePath()));
                } else {
                    stack.push(currentList);
                    currentList = currentDir.entryInfoList(dirFilters);
                }
            }
            else
            {
                if ( !currentDir.remove(currentItem.fileName()) )
                    emit errorOccured(Error(Error::RmFail, currentItem.absoluteFilePath()));
            }
        }
        else // list is empty
        {
            bool quit = false;
            if ( !stack.isEmpty() )
                currentList = stack.pop();
            else
                quit = true;

            //if quit == true, we remove the original dir itself, now that it is empty for sure...
            QString tmpname = currentDir.dirName();
            currentDir.cdUp();

            if ( !currentDir.rmdir(tmpname) )
                emit errorOccured(Error(Error::RmFail, currentDir.absoluteFilePath(tmpname)));

            if ( quit )
                break;
        }
    }
}
void RecursiveDirJobHelper::recursiveCpDir(const QString & sourcePath, const QString & destPath,
                                            RecursiveDirJob::CopyOptions options)
{
    QDir source(sourcePath);
    if ( !source.exists() ) {
        emit errorOccured(Error(Error::NoSuchFileOrDirectory, sourcePath));
        return;
    }

    QDir dest(destPath);
    if ( dest.exists() ) {
        if ( options & RecursiveDirJob::RemoveDestination ) {
            //in case the destination is a symlink to another directory, we remove first
            //the symlink target (returned by dest.canonicalPath()) and then the symlink itself.
            recursiveRmDir(dest.canonicalPath());
            if ( QFileInfo(destPath).isSymLink() ) {
                QFile::remove(destPath);
            }
        } else if ( !(options & RecursiveDirJob::OverWrite) ) {
            emit errorOccured(Error(Error::FileOrDirectoryExists, destPath));
            return;
        }
    }

    if ( dest.mkdir(dest.absolutePath()) ) {
        QFile::setPermissions(destPath, QFile::permissions(sourcePath));
    }

    QFileInfoList currentList = source.entryInfoList(dirFilters);
    QFileInfo currentItem;
    QStack<QFileInfoList> stack;
    QString currentName;
    quint64 bytesCopied = 0;

    if ( m_reportProgress ) {
        quint64 dirSize = calculateDirSize(sourcePath);
        emit setLabelText(tr("Copying files from \"%1\" to \"%2\"...").arg(sourcePath).arg(destPath));
        if (dirSize > 0) {
            emit setMaximum(dirSize);
            //the directory special file is already (almost) copied in dest.mkdir() above
            bytesCopied += stat_size(sourcePath);
            emit setValue(bytesCopied);
        } else {
            //no files to be copied, so set the progressbar to 100%
            emit setMaximum(1);
            emit setValue(1);
        }
    }

    while(1)
    {
        if ( !currentList.isEmpty() )
        {
            currentItem = currentList.takeFirst();
            currentName = currentItem.fileName();

            if ( currentItem.isSymLink() )
            {
                if ( options & RecursiveDirJob::OverWrite ) {
                    if ( !QFile::remove(dest.absoluteFilePath(currentName)) )
                        emit errorOccured(Error(Error::RmFail, dest.absoluteFilePath(currentName)));
                }
                if ( !QFile::link( DirOperations::relativeSymLinkTarget(source.absoluteFilePath(currentName)),
                                    dest.absoluteFilePath(currentName) ) )
                    emit errorOccured(Error(Error::CopyFail, source.absoluteFilePath(currentName)));
            }
            else if ( currentItem.isDir() )
            {
                bool ok = false;
                QFile::Permissions sourcePermissions = QFile::permissions(source.absoluteFilePath(currentName));

                if ( !(ok = source.cd(currentName)) ) {
                    emit errorOccured(Error(Error::AccessDenied, source.absoluteFilePath(currentName)));
                }
                if ( ok && !dest.cd(currentName) ) {
                    //if the target dir doesn't exist, create it and try again.
                    if ( !dest.mkdir(currentName) ) {
                        emit errorOccured(Error(Error::MkdirFail, dest.absoluteFilePath(currentName)));
                    }

                    //preserve permissions of the directory
                    QFile::setPermissions(dest.absoluteFilePath(currentName), sourcePermissions);

                    if ( !dest.cd(currentName) ) {
                         //quite impossible to happen
                        emit errorOccured(Error(Error::AccessDenied, dest.absoluteFilePath(currentName)));
                        ok = false;
                        source.cdUp(); //revert the state of source, as we are not going to copy this dir.
                    }
                }

                if (ok) {
                    stack.push(currentList);
                    currentList = source.entryInfoList(dirFilters);
                }
            }
            else if ( currentItem.isFile() )
            {
                if ( options & RecursiveDirJob::OverWrite ) {
                    if ( !QFile::remove(dest.absoluteFilePath(currentName)) )
                        emit errorOccured(Error(Error::RmFail, dest.absoluteFilePath(currentName)));
                }
                if ( !internal_copy( source.absoluteFilePath(currentName), dest.absoluteFilePath(currentName),
                                        options & RecursiveDirJob::ReplaceKde4InFiles ) )
                    emit errorOccured(Error(Error::CopyFail, source.absoluteFilePath(currentName)));
            }
            else
            {
                if ( currentItem.exists() ) {
                    qDebug() << "Ignoring special file" << source.absoluteFilePath(currentName);
                } else {
                    //this can happen with filename encoding bugs
                    emit errorOccured(Error(Error::NoSuchFileOrDirectory, source.absoluteFilePath(currentName)));
                }
            }

            if ( m_reportProgress ) {
                bytesCopied += stat_size(currentItem.absoluteFilePath());
                emit setValue(bytesCopied);
            }
        }
        else // list is empty
        {
            if ( !stack.isEmpty() )
            {
                currentList = stack.pop();
                source.cdUp();
                dest.cdUp();
            }
            else
                break;
        }
    }
}
Example #30
0
bool GalleryUtil::LoadDirectory(ThumbList& itemList, const QString& dir,
                                const GalleryFilter& flt, bool recurse,
                                ThumbHash *itemHash, ThumbGenerator* thumbGen)
{
    QString blah = dir;
    QDir d(blah);
    QString currDir = d.absolutePath();
    QStringList splitFD;

    bool isGallery;
    QFileInfoList gList = d.entryInfoList(QStringList("serial*.dat"),
                                          QDir::Files);
    isGallery = (gList.count() != 0);

    // Create .thumbcache dir if neccesary
    if (thumbGen)
        thumbGen->getThumbcacheDir(currDir);

    QFileInfoList list = d.entryInfoList(GetMediaFilter(),
                                         QDir::Files | QDir::AllDirs |
                                         QDir::NoDotAndDotDot,
                                         (QDir::SortFlag)flt.getSort());

    if (list.isEmpty())
        return false;

    QFileInfoList::const_iterator it = list.begin();
    const QFileInfo *fi;

    if (thumbGen)
    {
        thumbGen->cancel();
        thumbGen->setDirectory(currDir, isGallery);
    }

    if (!flt.getDirFilter().isEmpty())
    {
        splitFD = flt.getDirFilter().split(":");
    }

    while (it != list.end())
    {
        fi = &(*it);
        ++it;

        // remove these already-resized pictures.
        if (isGallery && (
                (fi->fileName().indexOf(".thumb.") > 0) ||
                (fi->fileName().indexOf(".sized.") > 0) ||
                (fi->fileName().indexOf(".highlight.") > 0)))
            continue;

        // skip filtered directory
        if (fi->isDir() &&
             !splitFD.filter(fi->fileName(), Qt::CaseInsensitive).isEmpty())
            continue;

        if (fi->isDir() && recurse)
        {
            LoadDirectory(itemList, QDir::cleanPath(fi->absoluteFilePath()),
                          flt, true, itemHash, thumbGen);
        }
        else
        {
            if ((GalleryUtil::IsImage(fi->absoluteFilePath()) &&
                 flt.getTypeFilter() == kTypeFilterMoviesOnly) ||
                (GalleryUtil::IsMovie(fi->absoluteFilePath()) &&
                 flt.getTypeFilter() == kTypeFilterImagesOnly))
                continue;

            ThumbItem *item = new ThumbItem(fi->fileName(),
                QDir::cleanPath(fi->absoluteFilePath()), fi->isDir());

            itemList.append(item);

            if (itemHash)
                itemHash->insert(item->GetName(), item);

            if (thumbGen)
                thumbGen->addFile(item->GetName());
        }
    }

    return isGallery;
}