コード例 #1
0
ファイル: main.cpp プロジェクト: Tw1ddle/Blind-Crossword-3D
void extractEmbeddedCrosswordPuzzles()
{
    QDir destDir(assets::getExternalCrosswordsFolderPath());

    if (!destDir.exists()) {
        destDir.mkpath(".");
    }

    QDirIterator it(assets::getEmbeddedCrosswordsFolderPath(), QDirIterator::Subdirectories);

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

        const QString destinationPath = destDir.absolutePath() + "/" + it.fileName();

        if (QFile::exists(destinationPath)) {
            QFile(destinationPath).setPermissions(QFileDevice::ReadOther | QFileDevice::WriteOther);
            QFile::remove(destinationPath);
        }

        QFile::copy(it.filePath(), destinationPath);

        if (QFile::exists(destinationPath)) {
            QFile(destinationPath).setPermissions(QFileDevice::ReadOther | QFileDevice::WriteOther);
        }
    }
}
コード例 #2
0
ファイル: funcoes.cpp プロジェクト: escrifonife1/Almoco
void Funcoes::copyFolder(QString sourceFolder, QString destFolder)
{
    QDir sourceDir(sourceFolder);
    if(!sourceDir.exists())
        return;
    QDir destDir(destFolder);
    if(!destDir.exists())
    {
        destDir.mkdir(destFolder);
    }
    QStringList files = sourceDir.entryList(QDir::Files);
    for(int i = 0; i< files.count(); i++)
    {
        QString srcName = sourceFolder + "/" + files[i];
        QString destName = destFolder + "/" + files[i];
        QFile::copy(srcName, destName);
    }
    files.clear();
    files = sourceDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
    for(int i = 0; i< files.count(); i++)
    {
        QString srcName = sourceFolder + "/" + files[i];
        QString destName = destFolder + "/" + files[i];
        copyFolder(srcName, destName);
    }
}
コード例 #3
0
void BackupsManager::moveSavegamesToComputer(QList<int> list)
{
    if (m_options.isBackupDirSet())
    {
        for (int i = 0; i < list.size(); i++)
        {
            QDir sourceDir(m_savePSPList.at(list.at(i)).getPath());
            QDir destDir(getComputerDir() + "/" + QDir(m_savePSPList.at(list.at(i)).getPath()).dirName());
            if (destDir.exists())
            {
                if (m_view.askSaveOverwrite(m_savePSPList.at(list.at(i)).getName()))
                {
                    FileManager::deleteDir(destDir.absolutePath());
                    if (!FileManager::copyFolder(sourceDir, destDir, true))
                    {
                        m_view.showErrorMessage(tr("Error moving %1").arg(m_savePSPList.at(list.at(i)).getName()));
                    }
                }
            }
            else
            {
                if (!FileManager::copyFolder(sourceDir, destDir, true))
                {
                    m_view.showErrorMessage(tr("Error moving %1").arg(m_savePSPList.at(list.at(i)).getName()));
                }
            }
        }
        scanComputer();
        updateComputerGUI();
    }
    else
    {
        m_view.showErrorMessage(tr("Please, set the Backup Directory in the options menu"));
    }
}
コード例 #4
0
ファイル: MtpFolder.cpp プロジェクト: JasonFerrara/jmtpfs
void MtpFolder::Rename(MtpNode& newParent, const std::string& newName)
{
	if (newName.length() > MAX_MTP_NAME_LENGTH)
		throw MtpNameTooLong();

	MtpNodeMetadata md = m_cache.getItem(m_id, *this);

	uint32_t parentId = GetParentNodeId();
	if ((newParent.FolderId() == md.self.parentId) && (newParent.StorageId() == m_storageId))
	{
		// we can do a real rename
		m_device.RenameFile(m_id, newName);
	}
	else
	{
		// we have to do a copy and delete
		newParent.mkdir(newName);
		std::unique_ptr<MtpNode> destDir(newParent.getNode(FilesystemPath(newName.c_str())));
		std::vector<std::string> contents = readDirectory();
		for(std::vector<std::string>::iterator i = contents.begin(); i != contents.end(); i++)
		{
			std::unique_ptr<MtpNode> child(getNode(FilesystemPath(i->c_str())));
			child->Rename(*destDir, *i);
		}
		Remove();
	}
	m_cache.clearItem(newParent.Id());
	m_cache.clearItem(parentId);

}
コード例 #5
0
ファイル: symmake_sbsv2.cpp プロジェクト: 30114/phantomjs
// Copies Qt FLMs to correct location under epocroot.
// This is not done by configure as it is possible to change epocroot after configure.
void SymbianSbsv2MakefileGenerator::exportFlm()
{
    static bool flmExportDone = false;

    if (!flmExportDone) {
        QDir sourceDir = QDir(QLibraryInfo::location(QLibraryInfo::PrefixPath) + FLM_SOURCE_DIR);
        QFileInfoList sourceInfos = sourceDir.entryInfoList(QDir::Files);

        QDir destDir(qt_epocRoot() + FLM_DEST_DIR);
        if (!destDir.exists()) {
            if (destDir.mkpath(destDir.absolutePath()))
                generatedDirs << destDir.absolutePath();
        }

        foreach(QFileInfo item, sourceInfos) {
            QFileInfo destInfo = QFileInfo(destDir.absolutePath() + "/" + item.fileName());
            if (!destInfo.exists() || destInfo.lastModified() != item.lastModified()) {
                if (destInfo.exists())
                    QFile::remove(destInfo.absoluteFilePath());
                if (QFile::copy(item.absoluteFilePath(), destInfo.absoluteFilePath()))
                    generatedFiles << destInfo.absoluteFilePath();
                else
                    fprintf(stderr, "Error: Could not copy '%s' -> '%s'\n",
                            qPrintable(item.absoluteFilePath()),
                            qPrintable(destInfo.absoluteFilePath()));
            }
        }
コード例 #6
0
void copyFolders(const QString sourceDirec, const QStringList sourceFolders, const QString destBaseFolder)
{
    for(QString sourceFolder : sourceFolders)
    {
        sourceFolder = sourceDirec + sourceFolder + "/";
        QDir sourceDir(sourceFolder);
        if(!sourceDir.exists())
            return;
        QStringList source= sourceFolder.split('/');
        QString destFolder = destBaseFolder + "/" + source.at(source.size() - 2);
        QDir destDir(destFolder);
        if(destDir.exists())
        {
            destDir.removeRecursively();
        }
        destDir.mkdir(destFolder);
        QStringList files = sourceDir.entryList(QDir::Files);
        for(int i = 0; i< files.count(); i++)
        {
            QString srcName = sourceFolder + "/" + files[i];
            QString destName = destFolder + "/" + files[i];
            QFile::copy(srcName, destName);
        }
        files.clear();
        files = sourceDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
        for(int i = 0; i< files.count(); i++)
        {
            QString srcName = sourceFolder + "/" + files[i];
            QString destName = destFolder + "/" + files[i];
            copyFolders(sourceDirec, QStringList(srcName), destName);
        }
    }
}
コード例 #7
0
ファイル: vutils.cpp プロジェクト: liunianbanbo/vnote
bool VUtils::copyDirectory(const QString &p_srcDirPath, const QString &p_destDirPath, bool p_isCut)
{
    QString srcPath = QDir::cleanPath(p_srcDirPath);
    QString destPath = QDir::cleanPath(p_destDirPath);
    if (srcPath == destPath) {
        return true;
    }

    if (QFileInfo::exists(destPath)) {
        qWarning() << QString("target directory %1 already exists").arg(destPath);
        return false;
    }

    // QDir.rename() could not move directory across drives.

    // Make sure target directory exists.
    QDir destDir(destPath);
    if (!destDir.exists()) {
        if (!destDir.mkpath(destPath)) {
            qWarning() << QString("fail to create target directory %1").arg(destPath);
            return false;
        }
    }

    // Handle directory recursively.
    QDir srcDir(srcPath);
    Q_ASSERT(srcDir.exists() && destDir.exists());
    QFileInfoList nodes = srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden
                                               | QDir::NoSymLinks | QDir::NoDotAndDotDot);
    for (int i = 0; i < nodes.size(); ++i) {
        const QFileInfo &fileInfo = nodes.at(i);
        QString name = fileInfo.fileName();
        if (fileInfo.isDir()) {
            if (!copyDirectory(srcDir.filePath(name), destDir.filePath(name), p_isCut)) {
                return false;
            }
        } else {
            Q_ASSERT(fileInfo.isFile());
            if (!copyFile(srcDir.filePath(name), destDir.filePath(name), p_isCut)) {
                return false;
            }
        }
    }

    if (p_isCut) {
        if (!destDir.rmdir(srcPath)) {
            qWarning() << QString("fail to delete source directory %1 after cut").arg(srcPath);
            return false;
        }
    }

    return true;
}
コード例 #8
0
ファイル: DiskObject.cpp プロジェクト: Cache22/Launchy
BOOL CDiskObject::CopyFile( const CString& sourceFile,const CString& destDirectory, const CString& destFile )
/* ============================================================
	Function :		CDiskObject::CopyFile
	Description :	Will copy "sourceFile" to "destDirectory" 
					with the new name "destFile". 
					An existing file will be overwritten. The 
					directory will be created if it doesn't exist.
	Access :		Public
					
	Return :		BOOL					-	"TRUE" if OK. 
												"GetErrorMessage" 
												will contain 
												errors
	Parameters :	CString sourceFile		-	file to copy
					CString destDirectory	-	destination
					CString destFile		-	destination file name 
												(in "destDirectory")
					
	Usage :			Call to copy a file to a directory.

   ============================================================*/
{
	ClearError( );
	CString source( sourceFile );
	CString destDir( destDirectory );
	CString dest( destFile );

	BOOL result = TRUE;
	if( sourceFile.GetLength( ) )
	{
		QualifyFile( source );
		QualifyFile( dest );
		QualifyPath( destDir );

		// Creating destDirectory if necessary.
		if( ( result = CreateDirectory( destDir ) ) )
		{
			// Copy the file
			Trigger( dest );
			if( !( result = ::CopyFile( source, dest, FALSE ) ) )
				SetSystemErrorMessage( ::GetLastError( ), source );
		}
	}
	else
	{
		SetInternalErrorMessage( );
		result = FALSE;
	}

	return result;
}
コード例 #9
0
ファイル: saveswidget.cpp プロジェクト: georgemoralis/pspudb
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)));
                }
            }*/
        }
}
コード例 #10
0
Calamares::JobResult
SetKeyboardLayoutJob::exec()
{
    // Read the location of the destination's / in the host file system from
    // the global settings
    Calamares::GlobalStorage* gs = Calamares::JobQueue::instance()->globalStorage();
    QDir destDir( gs->value( "rootMountPoint" ).toString() );

    // Get the path to the destination's /etc/vconsole.conf
    QString vconsoleConfPath = destDir.absoluteFilePath( "etc/vconsole.conf" );

    // Get the path to the destination's /etc/X11/xorg.conf.d/00-keyboard.conf
    QString xorgConfDPath;
    QString keyboardConfPath;
    if ( QDir::isAbsolutePath( m_xOrgConfFileName ) )
    {
        keyboardConfPath = m_xOrgConfFileName;
        while ( keyboardConfPath.startsWith( '/' ) )
            keyboardConfPath.remove( 0, 1 );
        keyboardConfPath = destDir.absoluteFilePath( keyboardConfPath );
        xorgConfDPath = QFileInfo( keyboardConfPath ).path();
    }
    else
    {
        xorgConfDPath = destDir.absoluteFilePath( "etc/X11/xorg.conf.d" );
        keyboardConfPath = QDir( xorgConfDPath )
                               .absoluteFilePath( m_xOrgConfFileName );
    }
    destDir.mkpath( xorgConfDPath );

    // Get the path to the destination's path to the converted key mappings
    QString convertedKeymapPath = m_convertedKeymapPath;
    if ( !convertedKeymapPath.isEmpty() )
    {
        while ( convertedKeymapPath.startsWith( '/' ) )
            convertedKeymapPath.remove( 0, 1 );
        convertedKeymapPath = destDir.absoluteFilePath( convertedKeymapPath );
    }

    if ( !writeVConsoleData( vconsoleConfPath, convertedKeymapPath ) )
        return Calamares::JobResult::error( tr( "Failed to write keyboard configuration for the virtual console." ),
                                            tr( "Failed to write to %1" ).arg( vconsoleConfPath ) );

    if ( !writeX11Data( keyboardConfPath ) )
        return Calamares::JobResult::error( tr( "Failed to write keyboard configuration for X11." ),
                                            tr( "Failed to write to %1" ).arg( keyboardConfPath ) );

    return Calamares::JobResult::ok();
}
コード例 #11
0
ファイル: commands.cpp プロジェクト: Suneal/qt
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;
        }
    }
コード例 #12
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;
    }
コード例 #13
0
TEST(FilePersistence, ReSaveList)
{
	QString srcDir(":/FilePersistence/test/persisted");
	QString destDir(QDir::tempPath() + "/Envision/FilePersistence/tests");

	QFile src(srcDir + "/partial/partial");
	QFile dest(destDir + "/partialResave/partialResave");

	if (dest.exists())
	{
		bool removed = dest.remove();
		CHECK_CONDITION(removed);
	}

	if (!QDir(destDir + "/partialResave").exists())
	{
		bool createdDir = QDir().mkpath(destDir + "/partialResave");
		CHECK_CONDITION(createdDir);
	}
	bool copied = src.copy(dest.fileName());
	CHECK_CONDITION(copied);

	bool permissionOk = dest.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
	CHECK_CONDITION(permissionOk);

	Model::Model model;
	FileStore store;
	store.setBaseFolder(destDir);

	model.load(&store, "partialResave");
	TestNodes::PartialList* root = dynamic_cast<TestNodes::PartialList*> (model.root());

	CHECK_CONDITION(root->list()->isFullyLoaded() == false);

	model.beginModification(root->list(), "fake modification ");
	model.endModification();

	CHECK_CONDITION(root->list()->isFullyLoaded() == false);
	model.setName("partialResave");
	model.save(&store);
	CHECK_CONDITION(root->list()->isFullyLoaded() == false);

	CHECK_TEXT_FILES_EQUAL(":/FilePersistence/test/persisted/partialResave/partialResave", destDir + "/partialResave/partialResave");
}
コード例 #14
0
ファイル: filestuff.cpp プロジェクト: Astrognome/MCMx
void filestuff::copyDir(QString src, QString dest)
{
    exMake(dest);
    QDir srcDir(src);
    QDir destDir(dest);
    QStringList srcList(srcDir.entryList(QDir::Files));
    for (int i = 0; i < srcList.count(); i++){
        QString srcName(src + "/" + srcList[i]);
        QString destName(dest + "/" + srcList[i]);
        QFile::copy(srcName, destName);
    }
    srcList.clear();
    srcList = srcDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
    for (int i = 0; i < srcList.count(); i++){
        QString srcName(src + "/" + srcList[i]);
        QString destName(dest + "/" + srcList[i]);
        copyDir(srcName, destName);
    }
}
コード例 #15
0
//---------------------------------------------------------------------------
//  deployInstance
//---------------------------------------------------------------------------
void CConfigGenEngine::deployInstance(IPropertyTree& instanceNode, bool useTempDir)
{
    StringAttr hostDir(m_outDir);
    StringAttr destDir(useTempDir ? getDeployDir(instanceNode).str() : hostDir.get());
    
    const char* pszHostDir = hostDir.get();
    if (pszHostDir && *pszHostDir==PATHSEPCHAR && *(pszHostDir+1)==PATHSEPCHAR)
        connectToHost(instanceNode);
    beforeDeployInstance(instanceNode, destDir);
    copyInstallFiles(instanceNode, destDir);
    afterDeployInstance(instanceNode, destDir);
    
    if (!m_compare && useTempDir)
    {
        checkAbort();
        EnvMachineOS os= m_envDepEngine.lookupMachineOS(instanceNode);
        renameDir(hostDir, NULL, os);
        renameDir(destDir, hostDir, os);
    }
}
コード例 #16
0
ファイル: Workspace.cpp プロジェクト: pporcher/notes-manager
/**
 * Fonction de service
 * \brief Copie un dossier
 * \details Usage : MoveDir(tr(« c:\\dossier_source »), tr(« c:\\dossier_destination »));
 */
bool Workspace::copyDir(QString srcPath, QString destPath){
    QDir srcDir(srcPath);
    QDir destDir(destPath);

    //Créée le répertoire s’il n’existe pas.
    if (!destDir.exists()) {
        if (!destDir.mkdir(destDir.absolutePath())) {
            return false;
        }
    }else if (destDir.entryList(QDir::Files).count() > 0) {
        return false;
    }

    //Récupère la liste des fichiers
    srcDir.setFilter( QDir::Files | QDir::Readable );
    srcDir.setSorting( QDir::Name );
    QFileInfoList srclist = srcDir.entryInfoList();

    //Copie les fichiers dans le nouveau répertoire
    foreach(QFileInfo file, srclist){
        QFile::copy(file.absoluteFilePath(), destDir.absolutePath() + "/" + file.fileName());
    }
コード例 #17
0
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;
}
コード例 #18
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"));
    }

}
コード例 #19
0
CBuildToolbarsetDlg::CBuildToolbarsetDlg()
{
    m_ui.setupUi(this);
    setWindowIcon(QIcon(":/images/fmlideico.ico"));

    QDir destDir( FmlCoreSettings::getDataDir() );
    QString destDirPath = destDir.absolutePath();
    if( !destDir.exists( destDirPath ) )
        destDir.mkpath( destDirPath );
    m_ui.m_path->insert( destDirPath );

    destDir.setPath(FmlCoreSettings::getXmlBtnDir());
    destDirPath = destDir.absolutePath();
    if( !destDir.exists( destDirPath ) )
        destDir.mkpath( destDirPath );
#ifdef Q_WS_MAC
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, __COMPANY_DOMAIN_, QCoreApplication::applicationName() );
#else
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, __COMPANY_NAME__, QCoreApplication::applicationName() );
#endif
    QStringList files = settings.value("XmlBtn/recentFileList").toStringList();
    m_ui.m_src->addItems( files );

    if( m_ui.m_src->count() == 0 )
    {
        m_ui.btnDelete->setEnabled(false);
        m_ui.btnClear->setEnabled(false);
        m_ui.btnBuild->setEnabled(false);
    }
    m_ui.m_msg->setReadOnly(true);

    connect(m_ui.btnBrowse, SIGNAL(clicked()), this, SLOT(slotBrowse()));
    connect(m_ui.btnAdd, SIGNAL(clicked()), this, SLOT(slotAdd()));
    connect(m_ui.btnDelete, SIGNAL(clicked()), this, SLOT(slotDelete()));
    connect(m_ui.btnClear, SIGNAL(clicked()), this, SLOT(slotClear()));
    connect(m_ui.btnBuild, SIGNAL(clicked()), this, SLOT(slotBuild()));
}
コード例 #20
0
ファイル: sandboxinstall.cpp プロジェクト: muromec/qtopia-ezx
/*!
  Remove the destination directory for the sandboxed package and
  everything below it.

  Use this method with care.
  */
void SandboxInstallJob::removeDestination() const
{
    QDir destDir( destination );
    if ( !destDir.exists() )
    {
        qWarning( "Request to remove non-existent directory %s", qPrintable( destination ));
        return;
    }
    QString cmd( "rm -Rf " );
    cmd += destination;
    Q_ASSERT( !destination.isEmpty() && destination != "/" );
    qLog(Package) << "Removing destination by executing:" << cmd;
    ScriptRunner::runScript( cmd );

    QDir dir( Qtopia::packagePath() );
    if ( dir.cd("tmp") )
    {
        QFileInfoList fileList= dir.entryInfoList( QDir::Files );
        QFile f;
        foreach( QFileInfo fi, fileList )
        {
            f.setFileName( fi.absoluteFilePath() );
            f.remove();
        }
コード例 #21
0
ファイル: fileopers.cpp プロジェクト: FaionWeb/WCMCommander
bool OperCFThread::CopyFile( FS* srcFs, FSPath& srcPath, FSNode* srcNode, FS* destFs, FSPath& destPath, bool move )
{
	if ( !srcNode->st.IsReg() && !skipNonRegular )
		switch ( RedMessage( _LT( "Can't copy the links or special file:\n" ), srcFs->Uri( srcPath ).GetUtf8(), bSkipSkipallCancel ) )
		{
			case CMD_SKIPALL:
				skipNonRegular = true; // no break

			case CMD_SKIP:
				return true;

			default:
				return false;
		}

	if ( IsSameFile( srcFs, srcPath, &( srcNode->st ), destFs, destPath ) )
	{
		RedMessage( _LT( "Can't copy file to itself:\n" ) , srcFs->Uri( srcPath ).GetUtf8() );
		return false;
	}

	SendCopyNextFileInfo( srcFs->Uri( srcPath ), destFs->Uri( destPath ) );
	SendProgressInfo( srcNode->st.size, 0, 0 );

	bool stopped = false;

	int ret_err;

	int in = -1;

	if (destFs->Type() == FS::TYPES::TMP)
	{
		// copy and move to tmpfs work the same way. Should we yell on move op instead?
		FSTmp* destTmpFS = static_cast<FSTmp*>(destFs);
		if (!destTmpFS->BaseIsEqual(srcFs))
		{
			RedMessage(_LT("Temporary panel can store only files from the same file system:\n"));
			return false;
		}
		if (srcFs->Type() == FS::TMP && srcNode->IsReg())
		{
			FSString srcFullFSString(srcNode->name.GetUnicode());
			FSPath srcFullFSPath(srcFullFSString);
			//srcFullFSPath.dbg_printf("OperCFThread::CopyFile srcFullFSPath=");
			//destPath.dbg_printf("OperCFThread::CopyFile destPath=");
			FSPath destDir(destPath);
			destDir.Pop();
			return destTmpFS->AddNode(srcFullFSPath, destDir);
		}
		else
			return destTmpFS->AddNode(srcPath, srcNode, destPath);
	}

	while ( true )
	{
		in = srcFs->OpenRead( srcPath, FS::SHARE_READ, &ret_err, Info() );

		if ( in == -2 ) { return false; }

		if ( in >= 0 ) { break; }

		switch ( RedMessage( _LT( "Can't open file:\n" ) , srcFs->Uri( srcPath ).GetUtf8(), bRetrySkipCancel, srcFs->StrError( ret_err ).GetUtf8() ) )
		{
			case CMD_CANCEL:
				return false;

			case CMD_SKIP:
				return true;
		}
	}

	int out =  -1;

	out = destFs->OpenCreate( destPath, false | commitAll, srcNode->st.mode, 0, &ret_err, Info() );

	if ( out < 0 && destFs->IsEEXIST( ret_err ) )
		switch ( RedMessage( _LT( "Overwrite file?\n" ) , destFs->Uri( destPath ).GetUtf8(), bOkAllNoCancel ) )
		{
			case CMD_ALL:
				commitAll = true; //no break

			case CMD_OK:
				out = destFs->OpenCreate( destPath, true, srcNode->st.mode, 0, &ret_err, Info() );
				break;

			case CMD_NO:
				srcFs->Close( in, 0, Info() );
				return true;

			default:
				srcFs->Close( in, 0, Info() );
				return false;
		}

	if ( out < 0 )
	{
		srcFs->Close( in, 0, Info() );
		return RedMessage( _LT( "Can't create file:\n" ), destFs->Uri( destPath ).GetUtf8(), bSkipCancel, destFs->StrError( ret_err ).GetUtf8() ) == CMD_SKIP;
	}

	int  bytes;
	//char    buf[BUFSIZE];
	int64_t doneBytes = 0;

	int blockSize = STARTSIZE;

	while ( true )
	{
		if ( Info()->Stopped() )
		{
			stopped = true;
			goto err;
		}

		time_t timeStart = time( 0 );

		if ( ( bytes = srcFs->Read( in, _buffer, blockSize, &ret_err, Info() ) ) < 0 )
		{
			if ( bytes == -2 ||
			     RedMessage( _LT( "Can't read the file:\n" ), srcFs->Uri( srcPath ).GetUtf8(), bSkipCancel, srcFs->StrError( ret_err ).GetUtf8() ) != CMD_SKIP )
			{
				stopped = true;
			}

			goto err;
		}

		if ( !bytes ) { break; }

		int b;

		if ( ( b = destFs->Write( out, _buffer, bytes, &ret_err, Info() ) ) < 0 )
		{
			if ( b == -2 || RedMessage( _LT( "Can't write the file:\n" ), destFs->Uri( destPath ).GetUtf8(), bSkipCancel, destFs->StrError( ret_err ).GetUtf8() ) != CMD_SKIP )
			{
				stopped = true;
			}

			goto err;
		}


		if ( b != bytes )
		{
			if ( RedMessage( "May be disk full \n(writed bytes != readed bytes)\nwhen write:\n", destFs->Uri( destPath ).GetUtf8(), bSkipCancel ) != CMD_SKIP )
			{
				stopped = true;
			}

			goto err;
		}

		time_t timeStop = time( 0 );

		if ( timeStart == timeStop && blockSize < BSIZE )
		{
			blockSize = blockSize * 2;

			if ( blockSize > BSIZE ) { blockSize = BSIZE; }
		}

		doneBytes += bytes;
		SendProgressInfo( srcNode->st.size, doneBytes, bytes );
	}

	srcFs->Close( in, 0, Info() );
	in = -1;

	SendProgressInfo( srcNode->st.size, srcNode->st.size, 0 );

	{
		int r = destFs->Close( out, &ret_err, Info() );

		if ( r )
		{
			if ( r == -2 || RedMessage( "Can't close the file:\n", destFs->Uri( destPath ).GetUtf8(), bSkipCancel, destFs->StrError( ret_err ).GetUtf8() ) != CMD_SKIP )
			{
				stopped = true;
			}

			goto err;
		}
		else
		{
			out = -1;
		}
	}

	destFs->SetFileTime( destPath, srcNode->st.m_CreationTime, srcNode->st.m_LastWriteTime, srcNode->st.m_LastWriteTime, 0, Info() );

	return !move || Unlink( srcFs, srcPath );

err:

	if ( in >= 0 ) { srcFs->Close( in, 0, Info() ); }

	if ( out >= 0 ) { destFs->Close( out, 0, Info() ); }

	Unlink( destFs, destPath );

	return !stopped;
}
コード例 #22
0
ファイル: jsonmapstorage.cpp プロジェクト: MUME/MMapper
bool JsonMapStorage::saveData(bool baseMapOnly)
{
    emit log("JsonMapStorage", "Writing data to files ...");

    // Collect the room and marker lists. The room list can't be acquired
    // directly apparently and we have to go through a RoomSaver which receives
    // them from a sort of callback function.
    // The RoomSaver acts as a lock on the rooms.
    ConstRoomList roomList{};
    MarkerList &markerList = m_mapData.getMarkersList();
    RoomSaver saver(m_mapData, roomList);
    for (uint i = 0; i < m_mapData.getRoomsCount(); ++i) {
        m_mapData.lookingForRooms(saver, RoomId{i});
    }

    uint roomsCount = saver.getRoomsCount();
    auto marksCount = static_cast<uint>(markerList.size());

    auto &progressCounter = getProgressCounter();
    progressCounter.reset();
    progressCounter.increaseTotalStepsBy(roomsCount * 2 + marksCount);

    BaseMapSaveFilter filter;
    if (baseMapOnly) {
        filter.setMapData(&m_mapData);
        progressCounter.increaseTotalStepsBy(filter.prepareCount());
        filter.prepare(progressCounter);
    }

    JsonWorld world;
    world.addRooms(roomList, filter, progressCounter, baseMapOnly);

    QDir saveDir(m_fileName);
    QDir destDir(QFileInfo(saveDir, "v1").filePath());
    QDir roomIndexDir(QFileInfo(destDir, "roomindex").filePath());
    QDir zoneDir(QFileInfo(destDir, "zone").filePath());
    try {
        if (!saveDir.mkdir("v1")) {
            throw std::runtime_error("error creating dir v1");
        }
        if (!destDir.mkdir("roomindex")) {
            throw std::runtime_error("error creating dir v1/roomindex");
        }
        if (!destDir.mkdir("zone")) {
            throw std::runtime_error("error creating dir v1/zone");
        }

        world.writeMetadata(QFileInfo(destDir, "arda.json"), m_mapData);
        world.writeRoomIndex(roomIndexDir);
        world.writeZones(zoneDir, filter, progressCounter, baseMapOnly);
    } catch (std::exception &e) {
        emit log("JsonMapStorage", e.what());
        return false;
    }

    emit log("JsonMapStorage", "Writing data finished.");

    m_mapData.unsetDataChanged();
    emit onDataSaved();

    return true;
}
コード例 #23
0
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;
}
コード例 #24
0
ファイル: genMouthShapes.cpp プロジェクト: duralakun/OneLife
int main( int inNumArgs, char **inArgs ) {

    if( inNumArgs != 8 ) {
        usage();
        }
    
    File voiceFile( NULL, inArgs[1] );

    if( ! voiceFile.exists() ||
        voiceFile.isDirectory() ) {
        usage();
        }

    int dataLength;
    unsigned char *aiffData = voiceFile.readFileContents( &dataLength );
    
    if( aiffData == NULL ) {
        usage();
        }
    
    
    samples = readMono16AIFFData( aiffData, dataLength, &numSamples,
                                  &sampleRate );

    delete [] aiffData;

    if( samples == NULL ) {
        usage();
        }
    
    

    
    int numRead = sscanf( inArgs[2], "%d", &fps );
    
    if( numRead != 1 ) {
        usage();
        }

    int mps = 0;
    
    numRead = sscanf( inArgs[3], "%d", &mps );
    
    if( numRead != 1 ) {
        usage();
        }
    
    int framesPerMove = ceil( (double)fps / (double)mps );
    
    printf( "%d frames per move\n", framesPerMove );

    double thresh = 0;
    
    numRead = sscanf( inArgs[4], "%lf", &thresh );
    
    if( numRead != 1 ) {
        usage();
        }



    File shapesDir( NULL, inArgs[5] );
    
    if( ! shapesDir.exists() ||
        ! shapesDir.isDirectory() ) {        
        usage();
        }
    
    File destDir( NULL, inArgs[6] );

    if( ! destDir.exists() ||
        ! destDir.isDirectory() ) {
        usage();
        }


    File listFile( NULL, inArgs[7] );

    if( listFile.isDirectory() ) {
        usage();
        }
    
    SimpleVector<char> list;
    

    shapeFiles = shapesDir.getChildFilesSorted( &numShapes );
    
    if( numShapes < 2 ) {
        usage();
        }
    char **shapeStrings = new char*[numShapes];
    

    for( int i=0; i<numShapes; i++ ) {
        shapeStrings[i] = autoSprintf( "%d\n", i );
        }
    
    
    
    double numSec = numSamples / (double)sampleRate;
    
    int numFrames = ceil( numSec * fps );
    
    File **frameShapes = new File*[numFrames];
    
    // default to closed mouth
    for( int i=0; i<numFrames; i++ ) {
        frameShapes[i] = shapeFiles[0];
        }

    int i = 0;
    
    while( i < numFrames ) {

        // avoid flicker by holding quiet frame longer
        int framesQuiet = 0;
        while( i < numFrames && 
               ( ! getTalking( i, thresh ) ||
                 framesQuiet < framesPerMove ) ) {
            frameShapes[i] = shapeFiles[0];
            
            list.appendElementString( shapeStrings[0] );
                                      
            i++;
            framesQuiet++;
            }
        // talking now
        
        int framesTalking = 0;
        int pick = randSource.getRandomBoundedInt( 1, numShapes - 1 );
        File *curShape = shapeFiles[ pick ];
        
        while( i < numFrames && 
               ( getTalking( i, thresh ) ||
                 framesTalking < framesPerMove ) ) {
            frameShapes[i] = curShape;

            list.appendElementString( shapeStrings[pick] );

            framesTalking ++;
            
            if( framesTalking % framesPerMove == 0 ) {
                File *newCurShape = curShape;

                // pick next randomly, but force change
                while( newCurShape == curShape ) {
                    pick = randSource.getRandomBoundedInt( 1, numShapes - 1 );
                    
                    
                    newCurShape = shapeFiles[ pick ];
                    }
                curShape = newCurShape;
                }
            i++;
            }
        }
    
    for( int i=0; i<numFrames; i++ ) {
        char *name = autoSprintf( "frame%05d.tga", i+1 );
        File *dest = destDir.getChildFile( name );
    
        frameShapes[i]->copy( dest );

        delete [] name;
        delete dest;
        }
    
    char *listString = list.getElementString();
    
    listFile.writeToFile( listString );
    

    for( int i=0; i<numShapes; i++ ) {
        delete shapeFiles[i];
        delete [] shapeStrings[i];
        }
    delete [] shapeFiles;
    
    
    delete [] samples;
    
    return 0;
    }
コード例 #25
0
ファイル: HDaemonApp.cpp プロジェクト: HaikuArchives/Scooby
/***********************************************************
 * SaveMails
 ***********************************************************/
void
HDaemonApp::SaveMail(const char* all_content,
						entry_ref* folder_ref,
						entry_ref *file_ref,
						bool *is_delete)
{
	fGotMails = true;
	if(!fHaveNewMails)
		fHaveNewMails = true;
	BString header(""),subject(""),to(""),date(""),cc(""),from("")
			,priority(""),reply(""),mime("");
	Encoding encode;
	
	bool is_multipart = false;
	int32 org_len = strlen(all_content);
	// Probably deleted with Spam filter
	if(org_len == 0)
	{
		*is_delete = false;
		return;
	}
	//
	int32 header_len = 0;
	for(int32 i = 0;i < org_len;i++)
	{
		if(strncasecmp(&all_content[i],"Subject:",8) == 0 && all_content[i-1] == '\n')
			i = GetHeaderParam(subject,all_content,i+8);
		else if(strncasecmp(&all_content[i],"Date:",5) == 0 && all_content[i-1] == '\n')
			i = GetHeaderParam(date,all_content,i+5);
		else if(strncasecmp(&all_content[i],"Cc:",3) == 0 && all_content[i-1] == '\n')
			i = GetHeaderParam(cc,all_content,i+3);
		else if(strncasecmp(&all_content[i],"To:",3) == 0 && all_content[i-1] == '\n')
			i = GetHeaderParam(to,all_content,i+3);
		else if(strncasecmp(&all_content[i],"From:",5) == 0 && all_content[i-1] == '\n')
			i = GetHeaderParam(from,all_content,i+5);
		else if(strncasecmp(&all_content[i],"X-Priority:",11) == 0 && all_content[i-1] == '\n')
			i = GetHeaderParam(priority,all_content,i+11);
		else if(strncasecmp(&all_content[i],"Mime-Version:",13) == 0 && all_content[i-1] == '\n')
			i = GetHeaderParam(mime,all_content,i+13);
		else if(strncasecmp(&all_content[i],"Reply-To:",9) == 0 && all_content[i-1] == '\n')
			i = GetHeaderParam(reply,all_content,i+9);
		else if(all_content[i] == '\r'||all_content[i] == '\n')
		{
			if(all_content[i-2] == '\r'||all_content[i-1] == '\n')
			{
				header_len = i+2;
				break;
			}
		}
	}
	
	header.Append(all_content,header_len);
	
	if(subject.Length() == 0)
		subject = "Untitled";
	if(strstr(header.String(),"Content-Type: multipart"))
		is_multipart = true;
	
	//PRINT(("From:%s\n",from.String()));
	encode.Mime2UTF8(from);
	//PRINT(("Decoded From:%s\n",from.String()));
	encode.Mime2UTF8(to);
	encode.Mime2UTF8(cc);
	encode.Mime2UTF8(reply);
	// convert mime subject to UTF8
	encode.Mime2UTF8(subject);
	
	// Filter mails
	BString folder_path;
	FilterMail(subject.String(),
				from.String(),
				to.String(),
				cc.String(),
				reply.String(),
				folder_path);
	//PRINT(("path:%s\n",folder_path.String() ));
	
	// Save to disk
	BPath path = folder_path.String();
	::create_directory(path.Path(),0777);
	BDirectory destDir(path.Path());
	path.Append(subject.String());
	//PRINT(("path:%s\n",path.Path() ));
	// create the e-mail file
	BFile file;

	TrackerUtils().SmartCreateFile(&file,&destDir,path.Leaf(),"_");
	// write e-mail attributes
	file.Write(all_content,strlen(all_content));
	file.SetSize(strlen(all_content));
	
	file.WriteAttr(B_MAIL_ATTR_STATUS,B_STRING_TYPE,0,"New",4);
	file.WriteAttrString(B_MAIL_ATTR_PRIORITY,&priority);
	file.WriteAttrString(B_MAIL_ATTR_TO,&to);
	file.WriteAttrString(B_MAIL_ATTR_CC,&cc);
	file.WriteAttrString(B_MAIL_ATTR_FROM,&from);
	file.WriteAttrString(B_MAIL_ATTR_SUBJECT,&subject);
	file.WriteAttrString(B_MAIL_ATTR_REPLY,&reply);
	file.WriteAttrString(B_MAIL_ATTR_MIME,&mime);
	file.WriteAttr(B_MAIL_ATTR_ATTACHMENT,B_BOOL_TYPE,0,&is_multipart,sizeof(bool));
	int32 content_len = strlen(all_content)-header_len;
	//PRINT(("header:%d, content%d\n",header_len,content_len));
	file.WriteAttr(B_MAIL_ATTR_HEADER,B_INT32_TYPE,0,&header_len,sizeof(int32));
	file.WriteAttr(B_MAIL_ATTR_CONTENT,B_INT32_TYPE,0,&content_len,sizeof(int32));	
	time_t when = MakeTime_t(date.String());
	time_t now = time(NULL);
	float diff = difftime(now,when);
	switch(fRetrievingType )
	{
	case 0:
		*is_delete = false;
		break;
	case 1:
		*is_delete = true;
		break;
	case 2:
		*is_delete = ( diff/3600 > fDeleteDays*24)?true:false;
		break;
	}
	file.WriteAttr(B_MAIL_ATTR_WHEN,B_TIME_TYPE,0,&when,sizeof(time_t));
	
	BNodeInfo ninfo(&file);
	ninfo.SetType("text/x-email");
	entry_ref ref;
	::get_ref_for_path(path.Path(),&ref);
	*file_ref = ref;
	
	AddNewMail(new BEntry(file_ref));
	
	path.GetParent(&path);
	::get_ref_for_path(path.Path(),&ref);
	*folder_ref =ref;
	return;
}
コード例 #26
0
ファイル: CreateUserJob.cpp プロジェクト: AOSC-Dev/calamares
Calamares::JobResult
CreateUserJob::exec()
{
    Calamares::GlobalStorage* gs = Calamares::JobQueue::instance()->globalStorage();
    QDir destDir( gs->value( "rootMountPoint" ).toString() );

    if ( gs->contains( "sudoersGroup" ) &&
         !gs->value( "sudoersGroup" ).toString().isEmpty() )
    {
        QFileInfo sudoersFi( destDir.absoluteFilePath( "etc/sudoers.d/10-installer" ) );

        if ( !sudoersFi.absoluteDir().exists() )
            return Calamares::JobResult::error( tr( "Sudoers dir is not writable." ) );

        QFile sudoersFile( sudoersFi.absoluteFilePath() );
        if (!sudoersFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
            return Calamares::JobResult::error( tr( "Cannot create sudoers file for writing." ) );

        QString sudoersGroup = gs->value( "sudoersGroup" ).toString();

        QTextStream sudoersOut( &sudoersFile );
        sudoersOut << QString( "%%1 ALL=(ALL) ALL\n" ).arg( sudoersGroup );

        if ( QProcess::execute( "chmod", { "440", sudoersFi.absoluteFilePath() } ) )
            return Calamares::JobResult::error( tr( "Cannot chmod sudoers file." ) );
    }

    QFileInfo groupsFi( destDir.absoluteFilePath( "etc/group" ) );
    QFile groupsFile( groupsFi.absoluteFilePath() );
    if ( !groupsFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
        return Calamares::JobResult::error( tr( "Cannot open groups file for reading." ) );
    QString groupsData = QString::fromLocal8Bit( groupsFile.readAll() );
    QStringList groupsLines = groupsData.split( '\n' );
    for ( QStringList::iterator it = groupsLines.begin();
          it != groupsLines.end(); ++it )
    {
        int indexOfFirstToDrop = it->indexOf( ':' );
        it->truncate( indexOfFirstToDrop );
    }

    foreach ( const QString& group, m_defaultGroups )
        if ( !groupsLines.contains( group ) )
            CalamaresUtils::System::instance()->
                    targetEnvCall( { "groupadd", group } );

    QString defaultGroups = m_defaultGroups.join( ',' );
    if ( m_autologin )
    {
        QString autologinGroup;
        if ( gs->contains( "autologinGroup" ) &&
             !gs->value( "autologinGroup" ).toString().isEmpty() )
            autologinGroup = gs->value( "autologinGroup" ).toString();
        else
            autologinGroup = QStringLiteral( "autologin" );

        CalamaresUtils::System::instance()->targetEnvCall( { "groupadd", autologinGroup } );
        defaultGroups.append( QString( ",%1" ).arg( autologinGroup ) );
    }

    int ec = CalamaresUtils::System::instance()->
             targetEnvCall( { "useradd",
                              "-m",
                              "-s",
                              "/bin/bash",
                              "-U",
                              "-G",
                              defaultGroups,
                              m_userName } );
    if ( ec )
        return Calamares::JobResult::error( tr( "Cannot create user %1." )
                                                .arg( m_userName ),
                                            tr( "useradd terminated with error code %1." )
                                                .arg( ec ) );

    ec = CalamaresUtils::System::instance()->targetEnvCall( { "chfn", "-f", m_fullName, m_userName } );
    if ( ec )
        return Calamares::JobResult::error( tr( "Cannot set full name for user %1." )
                                                .arg( m_userName ),
                                            tr( "chfn terminated with error code %1." )
                                                .arg( ec ) );

    ec = CalamaresUtils::System::instance()->
                      targetEnvCall( { "chown",
                                       "-R",
                                       QString( "%1:%2" ).arg( m_userName )
                                                         .arg( m_userName ),
                                       QString( "/home/%1" ).arg( m_userName ) } );
    if ( ec )
        return Calamares::JobResult::error( tr( "Cannot set home directory ownership for user %1." )
                                                .arg( m_userName ),
                                            tr( "chown terminated with error code %1." )
                                                .arg( ec ) );

    return Calamares::JobResult::ok();
}