Пример #1
0
static bool AutoExportDir(const char* inputDir, const char* outputDir, const char* groupFiles, std::vector<std::string>& excludeFiles)
{
    bool exportedFile = false;

    char outputFileName[MAX_PATH];
    sprintf(outputFileName, "%s\\Export.prd", outputDir);

    char outputLog[MAX_PATH];
    sprintf(outputLog, "%s\\AutoExport.log", outputDir);

    char doneDir[MAX_PATH];
    sprintf(doneDir, "%s\\Done\\", inputDir);
    CreateDirectory(doneDir, NULL);

    // Don't give missing bitmap warnings
    TheManager->SetSilentMode(TRUE);

    hsFolderIterator sourceDir(inputDir);
    while (sourceDir.NextFileSuffix(".max"))
    {
        char exportFile[MAX_PATH];
        sourceDir.GetPathAndName(exportFile);

        if (IsExcluded(sourceDir.GetFileName(), excludeFiles))
            continue;

        // If we're doing grouped files, and this isn't one, keep looking
        if (groupFiles && strncmp(sourceDir.GetFileName(), groupFiles, strlen(groupFiles)) != 0)
            continue;

        hsUNIXStream log;
        if (log.Open(outputLog, "ab"))
        {
            log.WriteFmt("%s\r\n", sourceDir.GetFileName());
            log.Close();
        }

        if (GetCOREInterface()->LoadFromFile(exportFile))
        {
            sprintf(doneDir, "%s\\Done\\%s", inputDir, sourceDir.GetFileName());
            MoveFileEx(exportFile, doneDir, MOVEFILE_REPLACE_EXISTING);

            GetCOREInterface()->ExportToFile(outputFileName, TRUE);
            exportedFile = true;

            // If we're not doing grouped files, this is it, we exported our one file
            if (!groupFiles)
                break;
        }
    }

    return exportedFile;
}
Пример #2
0
void savesWidget::copySaves(QList<QString> paths,QString emu)
{
	    for (int i = 0; i < paths.size(); i++)
        {
			QDir sourceDir(paths.at(i));

			QString destdirectory;
			if(emu=="PCSP")
			{
				destdirectory = theSettings->s_pcspPath + "/ms0/PSP/SAVEDATA" + "/" + sourceDir.dirName();
			}
			if(emu=="PSPE4ALL")
			{
				destdirectory = QDir::homePath() + "/pspe4all/vfs/ms0/PSP/SAVEDATA" + "/" + sourceDir.dirName();
			}
			if(emu=="JPCSP")
			{
				destdirectory = theSettings->s_jpcspPath + "/ms0/PSP/SAVEDATA" + "/" + sourceDir.dirName();
			}
			if(emu=="Local Folder")
			{
				destdirectory = theSettings->s_localdirpath + "/Saves" + "/" + sourceDir.dirName();
			}
			if(emu=="PSP Device")
			{
				destdirectory = theSettings->s_pspdevicePath + "/PSP/SAVEDATA" + "/" + sourceDir.dirName();
			}
            QDir destDir(destdirectory);
  /*          if (destDir.exists())  //TODO
            {
                if (askAppOverwrite(destdirectory))
                {
                    FileManager::deleteDir(destDir.absolutePath());
                    if (!FileManager::copyFolder(sourceDir, destDir, true))
                    {
						QErrorMessage *message= new QErrorMessage(this);
						message->showMessage(tr("Error moving %1").arg(paths.at(i)));
                    }
                }
            }
            else
            {
                if (!FileManager::copyFolder(sourceDir, destDir, true))
                {
                    	QErrorMessage *message= new QErrorMessage(this);
						message->showMessage(tr("Error moving %1").arg(paths.at(i)));
                }
            }*/
        }
}
Пример #3
0
static QScriptValue js_baseDir(QScriptContext *ctx, QScriptEngine *engine,
                               const Artifact *artifact)
{
    Q_UNUSED(ctx);
    Q_UNUSED(engine);
    QString basedir;
    if (artifact->artifactType == Artifact::SourceFile) {
        QDir sourceDir(artifact->product->sourceDirectory);
        basedir = FileInfo::path(sourceDir.relativeFilePath(artifact->filePath()));
    } else {
        QDir buildDir(artifact->product->buildDirectory());
        basedir = FileInfo::path(buildDir.relativeFilePath(artifact->filePath()));
    }
    return basedir;
}
Пример #4
0
// Taken from Qt Creator (src/app/main.cpp)
bool MainWindow::copyRecursively(const QString &srcFilePath, const QString &tgtFilePath)
{
    QFileInfo srcFileInfo(srcFilePath);
    if (srcFileInfo.isDir()) {
        QDir targetDir(tgtFilePath);
        targetDir.cdUp();
        if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName()))
            return false;
        QDir sourceDir(srcFilePath);
        QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
        foreach (const QString &fileName, fileNames) {
            const QString newSrcFilePath = srcFilePath + QStringLiteral("/") + fileName;
            const QString newTgtFilePath = tgtFilePath + QStringLiteral("/") + fileName;
            if (!copyRecursively(newSrcFilePath, newTgtFilePath))
                return false;
        }
    } else {
Пример #5
0
bool CopyDirectoryCommand::copyDir(const QString &from, const QString &to, bool recursive)
{
    QDir().mkpath(to);
    QDir sourceDir(from);
    QDir destDir(to);
    QStringList entries = sourceDir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
    foreach (QString item , entries) {
        QString itemFrom = sourceDir.absoluteFilePath(item);
        QString itemTo = destDir.absoluteFilePath(item);
        if (QFileInfo(item).isDir()) {
            if (recursive && !copyDir(itemFrom, itemTo, recursive))
                return false;
        } else {
            if (!QFile::copy(itemFrom, itemTo))
                return false;
        }
    }
Пример #6
0
void FaceCropperBatch::go()
{
    QStringList arguments = qApp->arguments();
    if (arguments.count()<3) {
        showUsage();
        QMetaObject::invokeMethod(qApp, "quit", Qt::DirectConnection);
        return;
    }
    QString sourceString = arguments.at(1);
    QString destString = arguments.at(2);

    QDir sourceDir(sourceString);
    QDir destDir(destString);
    QStringList nameFilters;
    foreach (QByteArray format, QImageReader::supportedImageFormats()) {

        nameFilters << "*."+format;
    }
Пример #7
0
bool SelectFile::copyDirectoryFiles(QString fromDir ,QString toDir, bool coverFileIfExist)
{
    QDir sourceDir(fromDir);
    QDir targetDir(toDir);
    QString toFile;
    if(!targetDir.exists()){    /**< 如果目标目录不存在,则进行创建 */
        if(!targetDir.mkdir(targetDir.absolutePath()))
            return false;
    }

    QFileInfoList fileInfoList = sourceDir.entryInfoList();
    foreach(QFileInfo fileInfo, fileInfoList){
        if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
            continue;

        if(fileInfo.isDir()){    /**< 当为目录时,递归的进行copy */
            if(!copyDirectoryFiles(fileInfo.filePath(),
                                   targetDir.filePath(fileInfo.fileName()),
                                   coverFileIfExist))
                return false;
        }
        else{            /**< 当允许覆盖操作时,将旧文件进行删除操作 */
            toFile = targetDir.filePath(fileInfo.fileName());
//            QMessageBox::warning(0,"PATH1",toFile,QMessageBox::Yes);
            if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){
                targetDir.remove(fileInfo.fileName());
            }
            toFile = toDir+"\\"+fileInfo.fileName();
            qDebug() << toFile << "  remove from m_pictures";
             if(mw->m_pictures.contains(toFile)){
//                 QMessageBox::warning(0,"PATH2",toFile,QMessageBox::Yes);
                 mw->m_pictures.removeAll(toFile);
             }

            /// 进行文件copy
            if(!QFile::copy(fileInfo.filePath(),
                            targetDir.filePath(fileInfo.fileName()))){
                return false;
            }
        }
    }
    return true;
}
Пример #8
0
 bool ProjectManager::copyFiles(const QString& src, const QString& dst)
 {
   QFileInfo srcFileInfo(src);
   if (srcFileInfo.isDir()) {
     QDir targetDir(dst);
     targetDir.cdUp();
     if (!targetDir.mkdir(QFileInfo(dst).fileName()))
       return false;
     QDir sourceDir(src);
     QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
     foreach (const QString &fileName, fileNames) {
       LOG(INFO) << "Copying file " << fileName.toUtf8().constData();
       const QString newSrcFilePath
         = src + QLatin1Char('/') + fileName;
       const QString newTgtFilePath
         = dst + QLatin1Char('/') + fileName;
       if (!copyFiles(newSrcFilePath, newTgtFilePath))
         return false;
     }
Пример #9
0
bool MainWindow::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)
{
    if(isPathExcept(fromDir))
        return true;
    // 流逝时间计算
    static QElapsedTimer et;
    et.start();

    QDir sourceDir(fromDir);
    QDir targetDir(toDir);
    if(!targetDir.exists()){    /** 如果目标目录不存在,则进行创建 */
        if(!targetDir.mkdir(targetDir.path()))
        {
            qDebug() << "mkdir " + targetDir.filePath(sourceDir.dirName()) + " failed";
        }
    }

    QFileInfoList fileInfoList = sourceDir.entryInfoList();

    foreach(QFileInfo fileInfo, fileInfoList)
    {
        if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
            continue;

        if(fileInfo.isDir())
        {   /**< 当为目录时,递归的进行 copy */
            qDebug() << fileInfo.filePath() << "-> " << targetDir.filePath(fileInfo.fileName());
            copyDirectoryFiles(fileInfo.filePath(),targetDir.filePath(fileInfo.fileName()),coverFileIfExist);
        }
        else
        {
            // 同步文件
            synTwoFiles(fileInfo.filePath(),targetDir.filePath(fileInfo.fileName()));
        }
        if(et.elapsed() > 300)
        {
            QApplication::processEvents();
            et.restart();
            qDebug() << "回到UI";
        }
    }
    return true;
}
Пример #10
0
/*
Функция подготавливает список файлов для копирования и подсчитивает их колличество. Содержимое
каталога строится в алфавитном порядке. (можно изменить с помощью переменной filesSort)
При работе функции возможно возбуждение исключения CopyExcepion. При обработки символической ссылки
в список копирования будет добавлен путь к файлу на который указывает эта ссылка
*/
int CopyJob::prepareCopy(int index, int level, const QString& sName, QString destDir, CopyInfoList& files)
{
  QFileInfo sourceInfo(sName);
  qint64 countFiles(0);
  
  CopyExcepion::throwIf(breakCurrentWork, UserTerminate, "User terminate");
  
  if ( !destDir.isEmpty() && !destDir.endsWith(QLatin1Char('/')) ) destDir += QLatin1Char('/');
  
  CopyExcepion::throwIf(!sourceInfo.exists(), SourceNotExists, sourceInfo.absoluteFilePath());
  
  if ( sourceInfo.isSymLink() )
    sourceInfo.setFile(sourceInfo.symLinkTarget());
  
  CopyInfo copyInfo;
  
  if ( sourceInfo.isFile() ){
    copyInfo.fill(sourceInfo.fileName(), sourceInfo.absoluteDir().absolutePath() + QLatin1Char('/'),
                  destDir, CopyInfo::FILE, sourceInfo.size(), index, level);
    files.append(copyInfo);
    countFiles++;
  }
  else 
    if ( sourceInfo.isDir() ){
      QDir sourceDir(sourceInfo.filePath());
          
      copyInfo.fill(sourceDir.dirName(), "", destDir, CopyInfo::DIR, 0, index, level);
      files.append(copyInfo);
      countFiles++;

      QFileInfoList filesInDir = sourceDir.entryInfoList(filesFilter, filesSort);
    
      for ( int i = 0; i < filesInDir.size(); i++ ){
        countFiles += prepareCopy(index, level + 1, filesInDir.at(i).absoluteFilePath(), 
                                  destDir + sourceDir.dirName(), files);
      }
    }
    else
      throw CopyExcepion(UnknownFileType, "Unknown file type");
    
  return countFiles;
}
Пример #11
0
bool Thread::copyDirectoryFiles(const QString &fromDir,const QString &toDir)
{
        QDir sourceDir(fromDir);
        QDir targetDir(toDir);
        if(!targetDir.exists())
        {
               /**< 如果目标目录不存在,则进行创建 */
                if(!targetDir.mkdir(targetDir.absolutePath()))
                    return false;
        }
        QFileInfoList fileInfoList = sourceDir.entryInfoList();
        foreach(QFileInfo fileInfo, fileInfoList)
        {
            if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
                continue;
            if(fileInfo.isDir())
            {
                /**< 当为目录时,递归的进行copy */
                if(!copyDirectoryFiles(fileInfo.filePath(),
                    targetDir.filePath(fileInfo.fileName())))
                    return false;
            }
            else
            {
                /**< 当允许覆盖操作时,将旧文件进行删除操作 */
                if(targetDir.exists(fileInfo.fileName()))
                {
                    targetDir.remove(fileInfo.fileName());
                }

                /// 进行文件copy
                if(!copy(fileInfo.filePath(),targetDir.filePath(fileInfo.fileName())))
                {
                        return false;
                }
            }
        }
        return true;
}
Пример #12
0
void AnimatorApplication::animate(){

    printed = 0;
    QDir sourceDir(rootQML->property("sourceDirectory").toUrl().toLocalFile());
    destinationDir = rootQML->property("destinationDirectory").toUrl().toLocalFile();
    QString pathToSave(destinationDir);
    QDir saveDir(sourceDir);
    QStringList nameFilters;
    nameFilters << QString("*.json");
    QStringList filelist = saveDir.entryList(nameFilters);
    //QMap сам сортирует по ключу вроде как
    QMap<int,GenAlgObject> map;
    QMap<int,double> fitnessMap;
    foreach(QString file, filelist){
        int popNum = file.split("-")[0].toInt();
        QFile jsonFile(sourceDir.absolutePath()+"\\" + file);
        jsonFile.open(QIODevice::ReadOnly);
        QByteArray data = jsonFile.readAll();
        QJsonDocument doc = QJsonDocument::fromJson(data);
        map[popNum] = GenAlgObject(doc.object());
        fitnessMap[popNum] = file.split("-")[1].toDouble();
    }
bool PathManager::copyWholeDirectory_recursive(QString sourceDirPath, QString destDirPath)
{
#ifdef ENABLE_PATH_MANAGER_LOGGING
    DLog(QString("copyWholeDirectory_recursive - sourceDir:%1 | destDir:%2").arg(sourceDirPath).arg(destDirPath));
#endif

    QDir sourceDir(sourceDirPath);
    if(!sourceDir.exists()) {
        WLogS << " ! The specified source path does not exists: " << sourceDirPath;
        return false;
    }

    QDir destDir(destDirPath);
    if(!destDir.exists())
    {
        if(!PathManager::ensureDirectoryCreated(destDirPath)) {
            WLogS << " ! The specified destination path cannot be created: " << destDirPath;
            return false;
        }
    }

    if(!PathManager::copyOnlyFilesOfDirectory(sourceDirPath, destDirPath)) {
        return false;
    }

    // and get sub-directories as well
    QStringList dirs = sourceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); // !!! No symlink folders allowed
    for(int i = 0; i < dirs.count(); i++)
    {
        QString srcName = PathManager::combineAndCleanPathes(sourceDirPath, dirs[i]);
        QString destName = PathManager::combineAndCleanPathes(destDirPath, dirs[i]);
        if(!PathManager::copyWholeDirectory_recursive(srcName, destName)) {
            return false;
        }
    }

    return true;
}
bool PathManager::copyWholeDirectory(QString sourceDirPath, QString destDirPath, bool isCopyOnlyContentOfSource)
{
    if(!isCopyOnlyContentOfSource) {
        // copy the folder as well
        return PathManager::copyWholeDirectory_recursive(sourceDirPath, destDirPath);
    }

    // copy only the sub dirs
    QDir sourceDir(sourceDirPath);
    if(!sourceDir.exists()) {
        WLogS << " ! The specified source path does not exists: " << sourceDirPath;
        return false;
    }

    QStringList subDirs = sourceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    if(subDirs.isEmpty()) {
#ifdef ENABLE_PATH_MANAGER_LOGGING
        DLogS << "The specified source directory is empty.";
#endif
        return true;
    }

    for(int i = 0; i < subDirs.count(); i++)
    {
        QString srcName = PathManager::combineAndCleanPathes(sourceDirPath, subDirs[i]);
        QString destName = PathManager::combineAndCleanPathes(destDirPath, subDirs[i]);
        if(!PathManager::copyWholeDirectory_recursive(srcName, destName)) {
            return false;
        }
    }

    // also copy the files from sourceDirPath
    if(!PathManager::copyOnlyFilesOfDirectory(sourceDirPath, destDirPath)) {
        return false;
    }

    return true;
}
Пример #15
0
void ApplicationsManager::moveApplicationsToPSP(QList<int> list)
{
    if (m_options.isPSPDirSet())
    {
        for (int i = 0; i < list.size(); i++)
        {
            QDir sourceDir(m_appComputerList.at(list.at(i)).getPath());
            sourceDir.cdUp();
            QDir destDir(getAppDirectory(m_options.getPSPDir(), m_options.getFirmware()) + "/" + sourceDir.dirName());
            if (destDir.exists())
            {
                if (m_view.askAppOverwrite(m_appComputerList.at(list.at(i)).getName()))
                {
                    FileManager::deleteDir(destDir.absolutePath());
                    if (!FileManager::copyFolder(sourceDir, destDir, true))
                    {
                        m_view.showErrorMessage(tr("Error moving %1").arg(m_appComputerList.at(list.at(i)).getName()));
                    }
                }
            }
            else
            {
                if (!FileManager::copyFolder(sourceDir, destDir, true))
                {
                    m_view.showErrorMessage(tr("Error moving %1").arg(m_appComputerList.at(list.at(i)).getName()));
                }
            }
        }
        
        scanPSP();
        updatePSPGUI();
    }
    else
    {
        m_view.showErrorMessage(tr("Please, set the PSP Directory in the options menu"));
    }

}
Пример #16
0
void Package::directoryInstall()
{
    QString srcFilePath = QString::fromStdString(getConfigVar(Directory));
    QString tgtFilePath = QDir::currentPath() + "/Games/" + QString::fromStdString(getConfigVar(Name)); 
    
    LOG(INFO) << "Installing \"" << getConfigVar(Name) << "\" with version " << getVersion().asString() << " from \"" 
        << srcFilePath.toStdString() << "\" to \"" << tgtFilePath.toStdString() << "\".";
    
    QFileInfo srcFileInfo(srcFilePath);
    
    if (srcFileInfo.isDir()) {
        QDir targetDir(tgtFilePath);
        targetDir.cdUp();
        if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName()))
            LOG(FATAL) << "Install failure: Could not create target directory.";
        QDir sourceDir(srcFilePath);
        QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
        Q_FOREACH(const QString &fileName, fileNames) {
            const QString newSrcFilePath
                    = srcFilePath + QLatin1Char('/') + fileName;
            const QString newTgtFilePath
                    = tgtFilePath + QLatin1Char('/') + fileName;
        }
    } else {
Пример #17
0
void plExportDlgImp::IDoExport()
{
    fExporting = true;

    // Hide the window, since we don't get control back until the export is done
    ShowWindow(fDlg, SW_HIDE);

    // Do the export
    char exportPath[MAX_PATH];
    GetDlgItemText(fDlg, IDC_CLIENT_PATH, exportPath, sizeof(exportPath));
    strcat(exportPath, "Export.prd");

    // For export time stats
    DWORD exportTime = timeGetTime();

    if (fExportFile)
        IExportCurrentFile(exportPath);
    else
    {
        hsFolderIterator sourceDir(fExportSourceDir);
        while (sourceDir.NextFileSuffix(".max"))
        {
            char exportFile[MAX_PATH];
            sourceDir.GetPathAndName(exportFile);

            if (GetCOREInterface()->LoadFromFile(exportFile))
                IExportCurrentFile(exportPath);
        }
    }

    fLastExportTime = (timeGetTime() - exportTime) / 1000;

    IDestroy();

    fExporting = false;
}
Пример #18
0
void tst_QTemporaryFile::initTestCase()
{
    // For QTBUG_4796
    QVERIFY(QDir("test-XXXXXX").exists() || QDir().mkdir("test-XXXXXX"));
    QCoreApplication::setApplicationName("tst_qtemporaryfile");

#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_NO_SDK)
    QString sourceDir(":/android_testdata/");
    QDirIterator it(sourceDir, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        it.next();

        QFileInfo sourceFileInfo = it.fileInfo();
        if (!sourceFileInfo.isDir()) {
            QFileInfo destinationFileInfo(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1Char('/') + sourceFileInfo.filePath().mid(sourceDir.length()));

            if (!destinationFileInfo.exists()) {
                QVERIFY(QDir().mkpath(destinationFileInfo.path()));
                QVERIFY(QFile::copy(sourceFileInfo.filePath(), destinationFileInfo.filePath()));
            }
        }
    }
#endif
}
Пример #19
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    a.setApplicationName("Imageset package manager");
    a.setApplicationVersion("1.0");

    const qint32 delay=3000;

    QCommandLineParser parser;
    parser.setApplicationDescription("This application look throw target folder and creates or refreshes .json file for package builder");
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption addSizeset("a","Add sizeset","size");
    QCommandLineOption removeSizeset("r","Remove sizeset","size");
    QCommandLineOption dir("dir","Run for nested folders (assume provided location of multiple packages)");
    QCommandLineOption runningDelay("d",QString("Wait %1 ms before execution").arg(QString::number(delay)));
    parser.addOption(addSizeset);
    parser.addOption(removeSizeset);
    parser.addOption(dir);
    parser.addOption(runningDelay);

    parser.addPositionalArgument("target","Target folder containing source images");

    parser.process(a);

    if(parser.isSet(runningDelay)){
        QThread::msleep(delay);
    }

    QStringList arguments(parser.positionalArguments());
    if(arguments.size()!=1){
        return 1;
    }

    QStringList subfolders;
    if(parser.isSet(dir)){
        QDir sourceDir(arguments.at(0));
        subfolders=sourceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    }else{
        subfolders<<".";
    }

    foreach(QString subfolder,subfolders){
        PackageManager package(arguments.at(0)+"/"+subfolder);
        if(!package.readData()){
            return 2;
        }

        QStringList sizesToRemove = parser.values(removeSizeset);
        if(!sizesToRemove.isEmpty()){
            foreach(QString size,sizesToRemove)package.removeSizeset(size);
        }
        QStringList sizesToAdd    = parser.values(addSizeset);
        if(!sizesToAdd.isEmpty()){
            foreach(QString size,sizesToAdd)package.addSizeset(size);
        }

        package.refreshPackage();

        if(!package.writeData()){
            return 3;
        }
    }
Пример #20
0
QString GeoSceneTileDataset::themeStr() const
{
    QFileInfo const dirInfo( sourceDir() );
    return dirInfo.isAbsolute() ? sourceDir() : "maps/" + sourceDir();
}
Пример #21
0
bool KDUpdater::UFCompressor::compress()
{
    d->errorString.clear();
   
    // Perform some basic checks.
    QFileInfo sourceInfo(d->source);
    if( !sourceInfo.isReadable() ) {
        d->setError( tr( "\"%1\" is not readable").arg( d->source ) );
        return false;
    }

    QDir sourceDir( sourceInfo.absoluteFilePath() ); // = sourceInfo.dir();
    sourceDir.cdUp();
    QString sourcePath = sourceDir.absolutePath();

    // First create the ZIP header.
    KDUpdater::UFHeader header;
    header.magic = QLatin1String( KD_UPDATER_UF_HEADER_MAGIC );
    header.fileList << d->fileNameRelativeTo(sourceInfo.absoluteFilePath(), sourcePath);
    header.permList << static_cast<quint64>(sourceInfo.permissions());
    header.isDirList << sourceInfo.isDir();
    // qDebug("ToCompress: %s", qPrintable(header.FileList.first()));

    if(sourceInfo.isDir())
        d->updateUFHeader(sourcePath, QDir(d->source), header);

    // open the uf file for writing
    QFile ufFile( d->ufFileName );
    //this should actually use temp files for security, for now remove partial files if saving failed  
    FileRemover remover( &ufFile );
    
    if( !ufFile.open(QFile::WriteOnly) )
    {
        d->setError( tr( "Could not open \"%1\" for writing: %2").arg( d->ufFileName, ufFile.errorString() ) );
        return false;
    }
    
    QDataStream ufDS( &ufFile );
    ufDS.setVersion( QDataStream::Qt_4_2 );
    QCryptographicHash hash( QCryptographicHash::Md5 );

    // Insert the header into the UF file
    ufDS << header;
    header.addToHash(hash);

    // Now create ZIP entries and add them.
    for(int i=0; i<header.fileList.count(); i++)
    {
        if(header.isDirList[i])
            continue;

        KDUpdater::UFEntry ufEntry;
        ufEntry.fileName = header.fileList[i];

        QString completeFileName = QString::fromLatin1( "%1/%2" ).arg(sourcePath, ufEntry.fileName);
        QFile zeFile( completeFileName );
        if ( !zeFile.open( QFile::ReadOnly ) ) {
            d->setError( tr( "Could not open input file \"%1\" to compress: %2").arg( completeFileName, zeFile.errorString() ) );
            return false;
        }
        ufEntry.fileData = qCompress(zeFile.readAll());
        ufEntry.permissions = static_cast<quint64>(zeFile.permissions());

        //qDebug("Compressed %s as %s", qPrintable(completeFileName), qPrintable(ufEntry.fileName));

        ufDS << ufEntry;
        ufEntry.addToHash(hash);
    }

    // All done, append hash and close file
    ufDS << hash.result();
    ufFile.close();
    
    if ( ufFile.error() != QFile::NoError )
    {
        d->setError( tr( "Could not save compressed data to \"%1\": %2").arg( ufFile.fileName(), ufFile.errorString() ) );
        return false;
    }

    remover.finalizeAndRelease(); // do not remove the file

    return true;
}
bool PathHelper::copyWholeDirectory_recursive(QString sourceDirPath, QString destDirPath, SymlinkHandlingModeEnum symlinkHandlingMode, bool isFailWhenContentCopyFails)
{
#ifdef ENABLE_PATH_MANAGER_LOGGING
    DLog(QString("copyWholeDirectory_recursive - sourceDir:%1 | destDir:%2").arg(sourceDirPath).arg(destDirPath));
#endif

    QDir sourceDir(sourceDirPath);
    if(!sourceDir.exists()) {
        WLogS << " ! The specified source path does not exists: " << sourceDirPath;
        return false;
    }

    QDir destDir(destDirPath);
    if(!destDir.exists())
    {
        if(!PathHelper::ensureDirectoryCreated(destDirPath)) {
            WLogS << " ! The specified destination path cannot be created: " << destDirPath;
            return false;
        }
    }

    if(!PathHelper::copyOnlyFilesOfDirectory(sourceDirPath, destDirPath, symlinkHandlingMode, true)) {
        if(isFailWhenContentCopyFails) {
            return false;
        }
    }

    // and get sub-directories as well
    QStringList dirs = sourceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden/* | QDir::NoSymLinks*/); // !!! No symlink folders allowed
    for(int i = 0; i < dirs.count(); i++)
    {
        QString srcDirFullPath = PathHelper::combineAndCleanPathes(sourceDirPath, dirs[i]);
        QString destDirFullPath = PathHelper::combineAndCleanPathes(destDirPath, dirs[i]);
        QFileInfo srcFInfo(srcDirFullPath);

        if(PathHelper::isSymlink(srcDirFullPath)) {
            DLog(QString(" - Symlink %1 found for target %2").arg(srcDirFullPath).arg(srcFInfo.symLinkTarget()));

            if(symlinkHandlingMode == SHM_UseAsFile) {
                // use as file

#ifdef Q_OS_WIN
                // copy it as a normal file
                if(!QFile::copy(srcDirFullPath, destDirFullPath)) {
                    WLog(QString(" ! Cannot copy the symlink-file from [%1] to [%2]").arg(srcDirFullPath).arg(destDirFullPath));
                    if(QFile::exists(destDirFullPath)) {
                        WLog("Dest file is already exists: ") << destDirFullPath;
                    }
                    return false;
                }
#endif


#ifdef Q_OS_MAC
//                if(QFileInfo(srcDirFullPath).symLinkTarget().isEmpty()) {
//                    WLog("Symlink found, but target is empty: ") << srcDirFullPath;
//                    continue;
//                }
                /////
                //QDir sourceDir(sourceDirPath);
                QString symlinkPath = getSymlinkTarget(QFileInfo(srcDirFullPath).absoluteFilePath());
                //sourceDir.relativeFilePath(srcFInfo.symLinkTarget());





                DLog(QString("Symlink created at path %1 with target %2").arg(destDirFullPath).arg(symlinkPath));

                /////

                if( !QFile::link(symlinkPath, destDirFullPath) ) {
                    WLog("Symlink cannot be created!");
                    if(isFailWhenContentCopyFails) {
                        WLog(" - Fail");
                        return false;
                    }
                }
#endif
            }
            else if(symlinkHandlingMode == SHM_UseAsTarget) {
                WLog("!!!!!!!! Not yet implemented! (will be ignored)");
            }
            else {
                DLog("Symlink handling mode: ignore.");
            }
        }
        else {
            if(!PathHelper::copyWholeDirectory_recursive(srcDirFullPath, destDirFullPath, symlinkHandlingMode, isFailWhenContentCopyFails)) {
                return false;
            }
        }
    }

    return true;
}
bool PathHelper::copyOnlyFilesOfDirectory(QString sourceDirPath, QString destDirPath, SymlinkHandlingModeEnum symlinkHandlingMode, bool isIgnoreDirectorySymlinks)
{
//    FLAG_FOR_REVIEW_WITH_HINT("Should copy symlink / shortcut files as well?? Temporarily removed / turned off.");

    QDir sourceDir(sourceDirPath);

    //
    // get everything, but handle only files and symlinks (pointing for other targets, like Drives)
    //

    QDir::Filters entryListFilters = QDir::NoDotAndDotDot | QDir::Files | QDir::Drives | QDir::Hidden | QDir::System;
    if(!isIgnoreDirectorySymlinks) {
        entryListFilters |= QDir::Dirs;
    }

    QStringList files = sourceDir.entryList(entryListFilters);
    for(int i = 0; i < files.count(); i++)
    {
        QString srcFullPath = PathHelper::combineAndCleanPathes(sourceDirPath, files[i]);
        QString destFullPath = PathHelper::combineAndCleanPathes(destDirPath, files[i]);

        // SYMLINKS

        // QFile cannot copy the file, when destName exists
        if(PathHelper::isSymlink(srcFullPath)) {
            // Symlink!
            DLogS << QString("Symlink found (%1) - target: (%2). Symlink-handling-mode: (%3) ").arg(srcFullPath).arg(QFileInfo(srcFullPath).symLinkTarget()).arg(symlinkHandlingMode);
//            WLog(QString("The file [%1] is a symlink to file [%2]").arg(srcName).arg( QFileInfo(srcName).symLinkTarget() ));

            if(symlinkHandlingMode == SHM_UseAsFile) {
                DLog(" - Symlink will be used as file, will be saved to path: ") << destFullPath;

#ifdef Q_OS_WIN
                // copy it as a normal file
                if(!QFile::copy(srcFullPath, destFullPath)) {
                    WLog(QString(" ! Cannot copy the symlink-file from [%1] to [%2]").arg(srcFullPath).arg(destFullPath));
                    return false;
                }
#endif

#ifdef Q_OS_MAC
//                if(QFileInfo(srcFullPath).symLinkTarget().isEmpty()) {
//                    WLog("Symlink found, but target is empty: ") << srcFullPath;
//                    continue;
//                }

//                QDir sourceDir(sourceDirPath);
                QString symlinkPath = getSymlinkTarget(QFileInfo(srcFullPath).absoluteFilePath());
                //sourceDir.relativeFilePath(QFileInfo(srcFullPath).symLinkTarget());

                DLog(QString("Symlink created at path %1 with target %2").arg(destFullPath).arg(symlinkPath));

                if( !QFile::link(symlinkPath, destFullPath) ) {
                    WLog("Symlink cannot be created!");
                    return false;
                }
#endif
            }
            else if(symlinkHandlingMode == SHM_UseAsTarget)
            {
                WLog(" - Symlink handling is set to 'UseAsTarget' - not yet implemented.");
//                QString linkTargetPath = QFileInfo(srcFullPath).symLinkTarget();
//                QFileInfo linkTargetFInfo(linkTargetPath);

//                if(linkTargetFInfo.isDir())
//                {
//                    // symlink target is a dir!
//                    DLog(" - Symlink target is a directory!");
//                    QDir linkTargetDir(linkTargetPath);
//                    if(!linkTargetDir.exists()) {
//                        WLog(" - Symlink target directory does NOT exists: ") << linkTargetPath;
//                    }
//                    QString destTargetDirPath = PathHelper::combineAndCleanPathes(destDirPath, linkTargetDir.dirName());
//                    DLog(" - Symlink dest target dir path: ") << destTargetDirPath;

//                    if(!PathHelper::copyWholeDirectory_recursive(srcFullPath, destTargetDirPath, symlinkHandlingMode, isFailWhenContentCopyFails)) {
//                        return false;
//                    }
//                }
//                else {
//                    DLog("Symlink target is a file: ") << linkTargetPath;
//                    QString destTargetFilePath = PathHelper::combineAndCleanPathes(destDirPath, linkTargetFInfo.fileName());
//                    DLog(" - Dest target File path: ") << destTargetFilePath;
//                    QFile::copy(linkTargetPath, destTargetFilePath);
//                }
            }
            else {
                DLog(" - Symlink ignored");
            }

        }

        else
        {
            // NOT symlink - handle only files
            if(QFileInfo(srcFullPath).isFile())
            {

                if(!QFile::copy(srcFullPath, destFullPath)) {
                    WLog(QString(" ! Cannot copy file from [%1] to [%2]").arg(srcFullPath).arg(destFullPath));
                    return false;
                }
                else {
#ifdef ENABLE_PATH_MANAGER_LOGGING
                    DLog(QString("Copy succeeded - file from [%1] to [%2]").arg(srcFullPath).arg(destFullPath));
#endif
                }
            }
            else {
                WLog("Not a symlink and not a file (will be ignored): ") << srcFullPath;
            }
        }
    }
    files.clear();

    return true;
}
Пример #24
0
void TestRegressionWindow::initTestsDirectory()
{
	bool okay = !m_testsUrl.isEmpty();
	if(okay)
	{
		const char *subdirs[] = { "tests", "baseline", "output", "resources" };
		for(int i = 0; i <= 3; i++)
		{
			QFileInfo sourceDir(m_testsUrl.path() + "/" + subdirs[i]);	//krazy:exclude=duoblequote_chars DOM demands chars
			if(!sourceDir.exists() || !sourceDir.isDir())
			{
				KMessageBox::error(0, i18n("Please choose a valid 'khtmltests/regression/' directory."));

				okay = false;
				m_testsUrl = KUrl();
				break;
			}
		}
	}

	if(okay)
	{
		// Clean up...
		m_itemMap.clear();
		m_ignoreMap.clear();
		m_failureMap.clear();
		m_directoryMap.clear();

		m_ui.treeWidget->clear();

		if(!m_khtmlUrl.isEmpty())
			m_ui.actionRun_tests->setEnabled(true);

		// Initialize map (to prevent assert below)...
		m_directoryMap.insert(QString(), QStringList());

		// Setup root tree widget item...
		(void) new QTreeWidgetItem(m_ui.treeWidget, QStringList(m_testsUrl.path() + "/tests"));

		// Check for ignore & failure file in root directory...
		QString ignoreFile = m_testsUrl.path() + "/tests/ignore";
		QString failureFile = m_testsUrl.path() + "/tests/KNOWN_FAILURES";

		QStringList ignoreFileList = readListFile(ignoreFile);
		QStringList failureFileList = readListFile(failureFile);

		if(!ignoreFileList.isEmpty())
			m_ignoreMap.insert(QString(), ignoreFileList);

		if(!failureFileList.isEmpty())
			m_failureMap.insert(QString(), failureFileList);

		// Remember directory...
		KConfig config("testregressiongui", KConfig::SimpleConfig);
		KConfigGroup grp = config.group("<default>");
		grp.writePathEntry("TestsDirectory", m_testsUrl.path());

		// Start listing directory...
		KUrl listUrl = m_testsUrl; listUrl.addPath("tests");
		KIO::ListJob *job = KIO::listRecursive(listUrl, KIO::HideProgressInfo, false /* no hidden files */);

		connect(job, SIGNAL(result(KJob *)), SLOT(directoryListingFinished(KJob *)));

		connect(job, SIGNAL(entries(KIO::Job *, const KIO::UDSEntryList &)),
				this, SLOT(directoryListingResult(KIO::Job *, const KIO::UDSEntryList &)));
	}
}
Пример #25
0
	QScriptValue File::movePrivate(const QString &source, const QString &destination, bool noErrorDialog, bool noConfirmDialog, bool noProgressDialog, bool allowUndo, bool createDestinationDirectory, QScriptContext *context, QScriptEngine *engine)
	{
		Q_UNUSED(engine)

#ifdef Q_OS_LINUX
		Q_UNUSED(noErrorDialog)
		Q_UNUSED(noConfirmDialog)
		Q_UNUSED(noProgressDialog)
		Q_UNUSED(allowUndo)

		QDir destinationDir(destination);
		QString sourceCopy(source);
		QString destinationCopy(destination);

		sourceCopy.replace(" ", "\\ ");
		destinationCopy.replace(" ", "\\ ");

		if(!destinationDir.exists())
		{
			if(createDestinationDirectory)
			{
				if(QProcess::execute("sh -c \"mkdir -p " + QFile::encodeName(destinationCopy) + "\""))
				{
					throwError(context, engine, "DirectoryCreationError", tr("Unable to create destination directory"));
					return context->thisObject();
				}
			}
			else
			{
				throwError(context, engine, "DirectoryDoesntExistError", tr("Destination directory doesn't exist"));
				return context->thisObject();
			}
		}

		QString command = "sh -c \"mv -f";

		command += " ";
		command += QFile::encodeName(sourceCopy);
		command += " ";
		command += QFile::encodeName(destinationCopy);
		command += "\"";

		if(QProcess::execute(command))
		{
			throwError(context, engine, "MoveRenameError", tr("Move/rename failed"));
			return context->thisObject();
		}
#endif
#ifdef Q_OS_WIN
		Q_UNUSED(createDestinationDirectory)

		QDir sourceDir(source);
		QDir destinationDir(destination);

		std::wstring wideSource = QDir::toNativeSeparators(sourceDir.absolutePath()).toStdWString();
		wideSource += L'\0';

		std::wstring wideDestination = QDir::toNativeSeparators(destinationDir.absolutePath()).toStdWString();
		wideDestination += L'\0';

		SHFILEOPSTRUCT shFileOpStruct;
		shFileOpStruct.hwnd = 0;
		shFileOpStruct.wFunc = FO_MOVE;
		shFileOpStruct.pFrom = wideSource.c_str();
		shFileOpStruct.pTo = wideDestination.c_str();
		shFileOpStruct.fFlags = 0;
		shFileOpStruct.fAnyOperationsAborted = false;
		shFileOpStruct.lpszProgressTitle = 0;
		shFileOpStruct.hNameMappings = 0;

		if(noErrorDialog)
			shFileOpStruct.fFlags |= FOF_NOERRORUI;
		if(noConfirmDialog)
			shFileOpStruct.fFlags |= (FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR);
		if(noProgressDialog)
			shFileOpStruct.fFlags |= FOF_SILENT;
		if(allowUndo)
			shFileOpStruct.fFlags |= FOF_ALLOWUNDO;

		int result = SHFileOperation(&shFileOpStruct);
		if(result != 0)
		{
			throwError(context, engine, "MoveError", tr("Move failed: %1").arg(getErrorString(result)));
			return context->thisObject();
		}

		if(shFileOpStruct.fAnyOperationsAborted)
		{
			throwError(context, engine, "MoveAbortedError", tr("Move failed: aborted"));
			return context->thisObject();
		}
#endif

		return context->thisObject();
	}
Пример #26
0
int wmain(int argc, Chr16** argv)
{
	Lock::setupGlobalLock();

	Error error;
	LogStdout log;
		
	class Fatal {};

	try
	{
		loginfo("Tomazos Resource Compiler 1.0 (c) Andrew Tomazos 2009");

		if (argc != 3)
		{
			error.what(L"Usage: ResourceCompiler <ResourceDir> <Out.cpp>");
			throw Fatal();
		}

		UTF16 sSourceDirPath = argv[1];
		UTF16 sOutPath = argv[2];

		Path sourceDir(error, sSourceDirPath);
		
		if (error)
			throw Fatal();

		UTF16 sFullSourceDirPath = UTF16(sourceDir);
		if (!sFullSourceDirPath.endsWith(L"\\"))
			sFullSourceDirPath = sFullSourceDirPath + L"\\";

		UTF16List fps;
		sourceDir.walk(ResourceCompilerWalker(fps));

		loginfo("Found %d files", fps.size());

		TreeMap<UTF16, Blob> data;

		{
			UTF16List::Iterator it(fps);
			UTF16 sFullFilePath;

			while (it(sFullFilePath))
			{
				if (!sFullFilePath.startsWith(sFullSourceDirPath))
				{
					Check();
					throw Fatal();
				}

				UTF16 sRelFilePath = sFullFilePath.suffix(sFullFilePath.length() - sFullSourceDirPath.length());

				Path file(error, sFullFilePath);
				
				if (error)
					throw Fatal();

				HInputStream fis;
				
				file.readFile(error, fis);

				if (error)
					throw Fatal();

				
				Blob sFileContent = fis->slurp(error);

				if (error)
					throw Fatal();

				loginfo("Found %s (%d bytes)", sRelFilePath.ptr(), sFileContent.length());

				data.add(sRelFilePath, sFileContent);
			}
		}

		Path outPath(error, sOutPath);

		if (error)
			throw Fatal();

		HOutputStream hOut;
		outPath.overwriteFile(error, hOut);

		if (error)
			throw Fatal();

		#define ResLine(x) { hOut->twrite(error, UTF8(x)); if (error) throw Fatal(); hOut->twrite(error, UTF8("\r\n")); if (error) throw Fatal(); }
		#define ResLineF(...) { ResLine(UTF8::format(__VA_ARGS__)); }

		ResLine("#include \"Runtime.h\"");
		ResLine("");
		ResLine("void ResourceManager::setup()");
		ResLine("{");

		{
			TreeMap<UTF16, Blob>::Iterator it(data);
			UTF16 sPath;
			Blob bData;
			int iCount = 0;

			int iNumResources = data.size();

			while (it(sPath, bData))
			{
				iCount++;
				UTF8 sId = UTF8::format("s_res_data_%d", iCount);
				
				ResLineF("    static UInt8 %s[] = { ", sId.ptr());
				for (int i = 0; i < bData.length(); i++)
				{
					if (i % 16 == 0)
					{
						hOut->twrite(error, UTF8("        "));
						if (error)
							throw Fatal();
					}

					hOut->twrite(error, UTF8::format("0x%.2X", UInt32(bData.idx<UInt8>(i))));

					if (error) throw Fatal();

					if (i != bData.length() - 1)
					{
						hOut->twrite(error, UTF8(", "));

						if (error)
							throw Fatal();
					}

					if (i % 16 == 15 || i == bData.length() - 1)
						ResLine("");
				}
				ResLineF("    };");
				ResLine("");
				ResLineF("    ResourceManager::instance()->set(%s, %s, %d);", stringToCStringLiteral(sPath).ptr(), sId.ptr(), bData.length());
				if (iCount != iNumResources)
					ResLine("");
			}
		}

		ResLine("}");

		#undef ResLine

		return 0;
	}
	catch (Fatal&)
	{
		if (error)
			logerr("%s", UTF16(error).ptr());
		
		return 1;
	}
}
bool PathHelper::copyWholeDirectory(QString sourceDirPath, QString destDirPath, bool isCopyOnlyContentOfSource, SymlinkHandlingModeEnum symlinkHandlingMode, bool isFailWhenContentCopyFails)
{
    if(!isCopyOnlyContentOfSource) {
        // copy the folder as well
        QDir sourceDir(sourceDirPath);
        QString newDestDirPath = PathHelper::combineAndCleanPathes(destDirPath, sourceDir.dirName());
        return PathHelper::copyWholeDirectory_recursive(sourceDirPath, newDestDirPath, symlinkHandlingMode, isFailWhenContentCopyFails);
    }

    // copy only the sub dirs
    QDir sourceDir(sourceDirPath);
    if(!sourceDir.exists()) {
        WLogS << " ! The specified source path does not exists: " << sourceDirPath;
        return false;
    }

    QStringList subDirs = sourceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden/*| QDir::NoSymLinks*/);
    if(subDirs.isEmpty()) {
#ifdef ENABLE_PATH_MANAGER_LOGGING
        DLogS << "The specified source directory is empty.";
#endif
        return true;
    }

    for(int i = 0; i < subDirs.count(); i++)
    {
        QString srcDirFullPath = PathHelper::combineAndCleanPathes(sourceDirPath, subDirs[i]);
        QString destDirFullPath = PathHelper::combineAndCleanPathes(destDirPath, subDirs[i]);
        QFileInfo srcFInfo(srcDirFullPath);

        if(PathHelper::isSymlink(srcDirFullPath)) {
            DLog(QString(" - (Dir)Symlink %1 found for target %2").arg(srcDirFullPath).arg(srcFInfo.symLinkTarget()));

            if(symlinkHandlingMode == SHM_UseAsFile) {
                // use as file

#ifdef Q_OS_WIN
                // copy it as a normal file
                if(!QFile::copy(srcDirFullPath, destDirFullPath)) {
                    WLog(QString(" ! Cannot copy the symlink-file from [%1] to [%2]").arg(srcDirFullPath).arg(destDirFullPath));
                    return false;
                }
#endif

#ifdef Q_OS_MAC
//                if(QFileInfo(srcDirFullPath).symLinkTarget().isEmpty()) {
//                    WLog("Symlink found, but target is empty: ") << srcDirFullPath;
//                    continue;
//                }

                /////
                //QDir sourceDir(sourceDirPath);
                QString symlinkPath = getSymlinkTarget(QFileInfo(srcDirFullPath).absoluteFilePath());
                //sourceDir.relativeFilePath(srcFInfo.symLinkTarget());

                DLog(QString("Symlink created at path %1 with target %2").arg(destDirFullPath).arg(symlinkPath));

                /////

                if( !QFile::link(symlinkPath, destDirFullPath) ) {
                    WLog("Symlink cannot be created!");
                    if(isFailWhenContentCopyFails) {
                        WLog(" - Fail");
                        return false;
                    }
                }
#endif
            }
            else if(symlinkHandlingMode == SHM_UseAsTarget) {
                WLog("!!!!!!!! Not yet implemented! (will be ignored)");
            }
            else {
                DLog("Symlink handling mode: ignore.");
            }
        }
        else {
            QString destName = PathHelper::combineAndCleanPathes(destDirPath, subDirs[i]);
            if(!PathHelper::copyWholeDirectory_recursive(srcDirFullPath, destName, symlinkHandlingMode, isFailWhenContentCopyFails)) {
                return false;
            }
        }
    }

    // also copy the files from sourceDirPath
    if(!PathHelper::copyOnlyFilesOfDirectory(sourceDirPath, destDirPath, symlinkHandlingMode, true)) {
        if(isFailWhenContentCopyFails) {
            return false;
        }
    }

    return true;
}
Пример #28
0
/*
 *  Paste files to destination
 */
void Worker::pasteFiles(bool cut)
{
    buildFileList();

    QList<QString> directoryList;

    QDir sourceDir(m_clipboardDir);

    QTime startTime = QTime::currentTime();

    emit progressTextChanged(QString("Copying files..."));

    // Create a list of directories to be created
    for (int i=0; i < m_directoryList.count(); i++)
    {
        QString sourcePath = m_directoryList.at(i);
        QString newDirPath = QString("%1/%2").arg(m_destination, sourceDir.relativeFilePath(sourcePath));

        qDebug() << sourcePath.toLatin1() << " > " << newDirPath.toLatin1();

        directoryList.append(newDirPath);
    }

    emit progressTextChanged("Creating directories...");

    qDebug() << "FILES";

    // Create a list of files to be copied
    for (int i=0; i < m_fileList.count(); i++)
    {
        QString sourcePath = m_fileList.at(i);
        QString newFilePath = QString("%1/%2").arg(m_destination, sourceDir.relativeFilePath(sourcePath));

        qDebug() << sourcePath.toLatin1() << " > " << newFilePath.toLatin1();

        m_fileMap.insert(sourcePath, newFilePath);
    }

    // First, create the directories
    for (int i = 0; i < directoryList.count(); i++)
    {
        QString newDir = directoryList.at(i);

        QDir dir(newDir);

        // If the directory already exists, skip it
        if (dir.exists())
            continue;

        bool success = dir.mkdir(newDir);

        if (!success)
            directoryErrorMap.insert(newDir, DirCreateError);
    }

    // If any of the directories couldn't be created, abort the process
    if (directoryErrorMap.count() > 0)
    {
        emit progressTextChanged("Directories couldn't be created.");
        emit fileOperationFinished();

        // Abort the process
        quit();
    }

    // Now, copy the files
    int fileCount = 0;
    QMapIterator<QString, QString> i(m_fileMap);
    while (i.hasNext())
    {
        i.next();
        fileCount++;
        QString sourceFilePath = i.key();
        QString newFilePath = i.value();

        QFile sourceFile(sourceFilePath);

        // Report the progress, but only every 50 milliseconds to prevent the UI thread
        // from being flooded with signals
        if (QTime::currentTime().msecsTo(startTime) <= -50)
        {
            startTime = QTime::currentTime();

            emit progressTextChanged(QString("Copying files (%1 of %2)...").arg(QString("%1").arg(fileCount),
                                                                                 QString("%1").arg(m_fileMap.count())));
            emit currentEntryChanged(sourceFile.fileName());

            double progress = (double)(fileCount) / (double)m_fileMap.count();
            emit progressValueChanged(progress);
        }

        // Copy the file
        bool success = sourceFile.copy(sourceFilePath, newFilePath);

        if (!success)
            fileErrorMap.insert(newFilePath, sourceFile.error());
    }

    // If we don't have to cut files we are done
    if (!cut)
    {
        if (fileErrorMap.count() == 0 && directoryErrorMap.count() == 0)
            emit progressTextChanged("All files were copied successfully.");
        else
            emit progressTextChanged("All files couldn't be copied successfully.");

        emit fileOperationFinished();

        // Done, time to self-destruct
        quit();
    }
    else
    {
        fileCount = 0;

        if (fileErrorMap.count() == 0 && directoryErrorMap.count() == 0)
        {
            // We copied all files successfully, so delete the old ones now
            i.toFront();
            while (i.hasNext())
            {
                i.next();
                fileCount++;
                QString sourceFilePath = i.key();

                QFile sourceFile(sourceFilePath);

                // Report the progress, but only every 50 milliseconds to prevent the UI thread
                // from being flooded with signals
                if (QTime::currentTime().msecsTo(startTime) <= -50)
                {
                    startTime = QTime::currentTime();

                    emit progressTextChanged(QString("Deleting old files (%1 of %2)...").arg(QString("%1").arg(fileCount),
                                                                                         QString("%1").arg(m_fileMap.count())));
                    emit currentEntryChanged(sourceFile.fileName());

                    double progress = (double)(fileCount) / (double)m_fileMap.count();
                    emit progressValueChanged(progress);
                }

                // Delete the file
                bool success = sourceFile.remove();

                if (!success)
                    fileErrorMap.insert(sourceFilePath, sourceFile.error());
            }

            emit progressTextChanged(QString("Deleting old directories..."));
            emit progressValueChanged(-1);

            // Then delete the directories
            for (int i=m_directoryList.count()-1; i >= 0; i--)
            {
                QString sourcePath = m_directoryList.at(i);

                QDir dir(sourcePath);

                // If it doesn't exist, it was most likely removed earlier
                if (!dir.exists())
                    continue;

                bool success = dir.rmdir(sourcePath);

                if (!success)
                    directoryErrorMap.insert(sourcePath, DirDeleteError);
            }

            // Check if files were copied and deleted successfully
            if (fileErrorMap.count() == 0 && directoryErrorMap.count() == 0)
                emit progressTextChanged("All of the files were cut and pasted successfully.");
            else
                emit progressTextChanged("All of the files couldn't be cut and pasted successfully.");

            emit fileOperationFinished();

            // Done, time to self-destruct
            quit();
        }
        else
        {
            // All files couldn't be copied, so delete the new copied files to revert the process
            i.toFront();
            while (i.hasNext())
            {
                i.next();
                fileCount++;
                QString newFilePath = i.value();

                QFile newFile(newFilePath);

                // Report the progress, but only every 50 milliseconds to prevent the UI thread
                // from being flooded with signals
                if (QTime::currentTime().msecsTo(startTime) <= -50)
                {
                    startTime = QTime::currentTime();

                    emit progressTextChanged(QString("Failed to copy all files, deleting copied files (%1 of %2)...").arg(QString("%1").arg(fileCount),
                                                                                         QString("%1").arg(m_fileMap.count())));
                    emit currentEntryChanged(newFile.fileName());

                    double progress = (double)(fileCount) / (double)m_fileMap.count();
                    emit progressValueChanged(progress);
                }

                // Delete the file
                newFile.remove();
            }

            emit progressTextChanged(QString("Failed to copy all files, deleting created directories..."));
            emit progressValueChanged(-1);

            // Delete the directories
            for (int i=directoryList.count()-1; i >= 0; i--)
            {
                QString newDir = directoryList.at(i);

                QDir dir(newDir);

                // If the directory already exists, skip it
                if (dir.exists())
                    continue;

                bool success = dir.rmdir(newDir);

                if (!success)
                    directoryErrorMap.insert(newDir, DirDeleteError);
            }

            emit progressTextChanged("All files couldn't be copied successfully.");

            emit fileOperationFinished();
        }
    }
}