Пример #1
0
KArchiveDirectory *KArchive::findOrCreate(const QString &path)
{
    //qCDebug(KArchiveLog) << path;
    if (path.isEmpty() || path == QLatin1String("/") || path == QLatin1String(".")) { // root dir => found
        //qCDebug(KArchiveLog) << "returning rootdir";
        return rootDir();
    }
    // Important note : for tar files containing absolute paths
    // (i.e. beginning with "/"), this means the leading "/" will
    // be removed (no KDirectory for it), which is exactly the way
    // the "tar" program works (though it displays a warning about it)
    // See also KArchiveDirectory::entry().

    // Already created ? => found
    const KArchiveEntry *ent = rootDir()->entry(path);
    if (ent) {
        if (ent->isDirectory())
            //qCDebug(KArchiveLog) << "found it";
        {
            const KArchiveDirectory *dir = static_cast<const KArchiveDirectory *>(ent);
            return const_cast<KArchiveDirectory *>(dir);
        } else {
            const KArchiveFile *file = static_cast<const KArchiveFile *>(ent);
            if (file->size() > 0) {
                qCWarning(KArchiveLog) << path << "is normal file, but there are file paths in the archive assuming it is a directory, bailing out";
                return nullptr;
            }

            qCDebug(KArchiveLog) << path << " is an empty file, assuming it is actually a directory and replacing";
            KArchiveEntry *myEntry = const_cast<KArchiveEntry*>(ent);
            rootDir()->removeEntry(myEntry);
            delete myEntry;
        }
    }

    // Otherwise go up and try again
    int pos = path.lastIndexOf(QLatin1Char('/'));
    KArchiveDirectory *parent;
    QString dirname;
    if (pos == -1) { // no more slash => create in root dir
        parent =  rootDir();
        dirname = path;
    } else {
        QString left = path.left(pos);
        dirname = path.mid(pos + 1);
        parent = findOrCreate(left);   // recursive call... until we find an existing dir.
    }

    //qCDebug(KArchiveLog) << "found parent " << parent->name() << " adding " << dirname << " to ensure " << path;
    // Found -> add the missing piece
    KArchiveDirectory *e = new KArchiveDirectory(this, dirname, d->rootDir->permissions(),
                                                 d->rootDir->date(), d->rootDir->user(),
                                                 d->rootDir->group(), QString());
    parent->addEntry(e);
    return e; // now a directory to <path> exists
}
Пример #2
0
KArchiveDirectory * KArchiveHandler::findOrCreate( const QString & path )
{
    //qDebug() << path;
    if ( path.isEmpty() || path == QLatin1String("/") || path == QLatin1String(".") ) // root dir => found
    {
        //qDebug() << "returning rootdir";
        return rootDir();
    }
    // Important note : for tar files containing absolute paths
    // (i.e. beginning with "/"), this means the leading "/" will
    // be removed (no KDirectory for it), which is exactly the way
    // the "tar" program works (though it displays a warning about it)
    // See also KArchiveDirectory::entry().

    // Already created ? => found
    const KArchiveEntry* ent = rootDir()->entry( path );
    if ( ent )
    {
        if ( ent->isDirectory() )
            //qDebug() << "found it";
            return (KArchiveDirectory *) ent;
        else {
            //qWarning() << "Found" << path << "but it's not a directory";
        }
    }

    // Otherwise go up and try again
    int pos = path.lastIndexOf( QLatin1Char('/') );
    KArchiveDirectory * parent;
    QString dirname;
    if ( pos == -1 ) // no more slash => create in root dir
    {
        parent =  rootDir();
        dirname = path;
    }
    else
    {
        QString left = path.left( pos );
        dirname = path.mid( pos + 1 );
        parent = findOrCreate( left ); // recursive call... until we find an existing dir.
    }

    //qDebug() << "found parent " << parent->name() << " adding " << dirname << " to ensure " << path;
    // Found -> add the missing piece
    KArchiveDirectory * e = new KArchiveDirectory( d->archive, dirname, d->rootDir->permissions(),
                                                   d->rootDir->date(), d->rootDir->user(),
                                                   d->rootDir->group(), QString() );
    parent->addEntry( e );
    return e; // now a directory to <path> exists
}
Пример #3
0
WrapperStr UmlPackage::source_path(const WrapperStr & f)
{
    if (!dir.read) {
        dir.src = cppSrcDir();
        dir.h = cppHDir();

        QDir d_root(rootDir(cppLanguage));

        if (dir.src.isEmpty())
            dir.src = RootDir;
        else if (QDir::isRelativePath(dir.src))
            dir.src = d_root.filePath(dir.src);

        if (dir.h.isEmpty())
            dir.h = RootDir;
        else if (QDir::isRelativePath(dir.h))
            dir.h = d_root.filePath(dir.h);

        if (dir.src.isEmpty()) {
            UmlCom::trace(WrapperStr("<font color=\"red\"><b><b> The generation directory "
                                    "must be specified for the package<i> ") + name()
                          + "</i>, edit the <i> generation settings</i> (tab 'directory') "
                          "or edit the package (tab 'C++')</b></font><br>");
            UmlCom::bye(n_errors() + 1);
            UmlCom::fatal_error("UmlPackage::source_path");
        }

        dir.read = TRUE;
    }

    QDir d(dir.src);

    return WrapperStr(d.filePath(f).toLatin1().constData()) + WrapperStr(".") + CppSettings::sourceExtension();
}
Пример #4
0
void CProject::updateStr()
{
	typeStr = settings->value("Type").toString();
	nameStr = settings->value("Name").toString();
	developModeStr = settings->value("DevelopMode", "Debug").toString();
	warningsStr = settings->value("Warnings").toString();
	platformStr = settings->value("Platform").toString();
	stdStr = settings->value("Std").toString();
	ccStr = settings->value("CC", "gcc").toString();
	cccStr = settings->value("CCC", "g++").toString();
	makeStr = settings->value("Make").toString();
	makefileStr = settings->value("Makefile").toString();
	if (!makefileStr.isEmpty()) {
		QDir rootDir(rootPathStr);
		QFileInfo fileInfo(makefileStr);
		if (rootDir.cd(fileInfo.path())) {
			makefileStr = rootDir.absolutePath() + "/" + fileInfo.fileName();
			if (!QFile::exists(makefileStr))
				makefileStr = QString();
		} else {
			makefileStr = QString();
		}
	}
	otherFlagStr = settings->value("OtherFlag").toString();
}
void DirectoryWorker::process()
{
    QDir rootDir(m_path);
    scanDir(rootDir);
    emit finished(this);
    QCoreApplication::processEvents();
}
Пример #6
0
	AsyncValue<void*> DefaultServer::loadModuleFromFile(CP::Poll& p, String path) {
		auto tmp = mgr->loadPage(p, rootDir(), path);
		if (tmp) return tmp()->dlHandle;
		auto* st = new moduleLoaderState();
		tmp.wait(st);
		return Future<void*>(&st->cb);
	}
Пример #7
0
	AsyncValue<Page*> DefaultServer::loadPageFromFile(CP::Poll& p, String path, RGC::Allocator& a) {
		auto tmp = mgr->loadPage(p, rootDir(), path);
		if (tmp) return tmp()->doCreate(&a);
		auto* st = a.New<pageLoaderState>(pageLoaderState { &a });
		tmp.wait(st);
		return Future<Page*>(&st->cb);
	}
Пример #8
0
bool Path::LoadPath(const QString& path){
	mPath.clear();
	QDir rootDir(path);
	FAIL_RET(rootDir.exists());
	if(!rootDir.exists(ASSET_INNER_PATH)){
		FAIL_RET(rootDir.mkpath(ASSET_INNER_PATH));
	}
    if(!rootDir.exists(OBJECT_INNER_PATH)){
        FAIL_RET(rootDir.mkpath(OBJECT_INNER_PATH));
    }
	if(!rootDir.exists(MAP_INNER_PATH)){
		FAIL_RET(rootDir.mkpath(MAP_INNER_PATH));
	}
    if(!rootDir.exists(MAP_INNER_PATH_JSON)){
        FAIL_RET(rootDir.mkpath(MAP_INNER_PATH_JSON));
    }
	if(!rootDir.exists(ZIP_INNER_PATH)){
		FAIL_RET(rootDir.mkpath(ZIP_INNER_PATH));
	}
	mAssetDir.setPath(rootDir.absoluteFilePath(ASSET_INNER_PATH));
	FAIL_RET(mAssetDir.exists());
    mObjectDir.setPath(rootDir.absoluteFilePath(OBJECT_INNER_PATH));
    FAIL_RET(mObjectDir.exists());
	mPath = rootDir.absolutePath();
	AddRecentProject(mPath);
	return true;
}
void StatGetterThread::GetSubdirsCount() const
{
    subdirsInPathDir_ = 0;

    QDir rootDir(path_);
    rootDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
    subdirsInPathDir_ = rootDir.count();
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void RicFileHierarchyDialog::appendToFileList(const QString& fileName)
{
    QString itemText = fileName;
    itemText.remove(0, rootDir().size());
    QListWidgetItem* item = new QListWidgetItem(itemText, m_fileList);
    item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
    item->setCheckState(Qt::Checked);
}
Пример #11
0
 openstudio::path WorkflowJSON_Impl::absoluteRootDir() const
 {
   openstudio::path result = rootDir();
   if (result.is_relative()){
     return canonicalOrAbsolute(result, oswDir());
   }
   return result;
 }
Пример #12
0
bool ZLibrary::init(int& aArgc, char** &aArgv)
{
    HDEBUG("initializing");

    ZLibrary::parseArguments(aArgc, aArgv);

    std::string rootDir("/");
    Dl_info info;
    void* addr = NULL;
    if (backtrace(&addr, 1) && dladdr(addr, &info)) {
        // Step two levels up. For an application deployed from QtCreator
        // it's going to be /opt/sdk/<app-name> directory, for a normally
        // installed app - the root directory.
        HDEBUG("app path" << info.dli_fname);
        char* slash = (char*)strrchr(info.dli_fname, '/');
        if (slash) {
            slash[0] = 0;
            HDEBUG("app dir" << info.dli_fname);
            slash = (char*)strrchr(info.dli_fname, '/');
            if (slash) {
                slash[0] = 0;
                slash = (char*)strrchr(info.dli_fname, '/');
                if (slash) {
                    slash[1] = 0;
                    HDEBUG("root dir" << info.dli_fname);
                    rootDir = info.dli_fname;
                }
            }
        }
    }

    ((std::string&)BaseDirectory) = rootDir;
    ourApplicationName = BOOKS_APP_NAME;
    ourZLibraryDirectory = BaseDirectory + BOOKS_DATA_DIR;
    ourImageDirectory = BaseDirectory + BOOKS_ICONS_DIR;
    ourDefaultFilesPathPrefix  = ourZLibraryDirectory + "/";
    ourApplicationDirectory = ourZLibraryDirectory;
    ourApplicationImageDirectory = ourImageDirectory;
    ourApplicationWritableDirectory =
        (QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) +
         QLatin1String("/" BOOKS_APP_NAME)).toStdString();

    HDEBUG("zlibrary dir" << ourZLibraryDirectory.c_str());
    HDEBUG("image dir" << ourImageDirectory.c_str());
    HDEBUG("writable dir" << ourApplicationWritableDirectory.c_str());

    BooksStorageManager::instance();
    ZLQtTimeManager::createInstance();
    ZLQtFSManager::createInstance();
    BooksDialogManager::createInstance();
    ZLQtImageManager::createInstance();
    ZLEncodingCollection::Instance().registerProvider(new IConvEncodingConverterProvider());
    ZLApplication::Instance();
    ZLFile::initCache();
    return true;
}
Пример #13
0
// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupStoreAccounts::Create(int32_t, int, int64_t, int64_t, const std::string &)
//		Purpose: Create a new account on the specified disc set.
//			 If rAsUsername is not empty, then the account information will be written under the
//			 username specified.
//		Created: 2003/08/21
//
// --------------------------------------------------------------------------
void BackupStoreAccounts::Create(int32_t ID, int DiscSet, int64_t SizeSoftLimit, int64_t SizeHardLimit, const std::string &rAsUsername)
{
	// Create the entry in the database
	BackupStoreAccountDatabase::Entry Entry(mrDatabase.AddEntry(ID,
		DiscSet));
	
	{
		// Become the user specified in the config file?
		std::auto_ptr<UnixUser> user;
		if(!rAsUsername.empty())
		{
			// Username specified, change...
			user.reset(new UnixUser(rAsUsername.c_str()));
			user->ChangeProcessUser(true /* temporary */);
			// Change will be undone at the end of this function
		}

		// Get directory name
		std::string dirName(MakeAccountRootDir(ID, DiscSet));
	
		// Create a directory on disc
		RaidFileWrite::CreateDirectory(DiscSet, dirName, true /* recursive */);
		
		// Create an info file
		BackupStoreInfo::CreateNew(ID, dirName, DiscSet, SizeSoftLimit, SizeHardLimit);
		
		// And an empty directory
		BackupStoreDirectory rootDir(BACKUPSTORE_ROOT_DIRECTORY_ID, BACKUPSTORE_ROOT_DIRECTORY_ID);
		int64_t rootDirSize = 0;
		// Write it, knowing the directory scheme
		{
			RaidFileWrite rf(DiscSet, dirName + "o01");
			rf.Open();
			rootDir.WriteToStream(rf);
			rootDirSize = rf.GetDiscUsageInBlocks();
			rf.Commit(true);
		}
	
		// Update the store info to reflect the size of the root directory
		std::auto_ptr<BackupStoreInfo> info(BackupStoreInfo::Load(ID, dirName, DiscSet, false /* ReadWrite */));
		info->ChangeBlocksUsed(rootDirSize);
		info->ChangeBlocksInDirectories(rootDirSize);
		info->AdjustNumDirectories(1);
		
		// Save it back
		info->Save();

		// Create the refcount database
		BackupStoreRefCountDatabase::Create(Entry)->Commit();
	}

	// As the original user...
	// Write the database back
	mrDatabase.Write();
}
Пример #14
0
bool PlaylistImporter::importPlaylist(QStringList &fileList, const QString &playlistFile)
{
	QFileInfo file(playlistFile);
	QDir baseDir(file.canonicalPath());

	QDir rootDir(baseDir);
	while(rootDir.cdUp());

	//Sanity check
	if(file.size() < 3 || file.size() > 512000)
	{
		return false;
	}
	
	//Detect playlist type
	playlist_t playlistType = isPlaylist(file.canonicalFilePath());

	//Exit if not a playlist
	if(playlistType == notPlaylist)
	{
		return false;
	}
	
	QFile data(playlistFile);

	//Open file for reading
	if(!data.open(QIODevice::ReadOnly))
	{
		return false;
	}

	//Skip very large files (parsing could take very long)
	if(data.size() >= 10485760i64)
	{
		qWarning("File is very big. Probably not a Playlist. Rejecting...");
		return false;
	}

	//Parse playlist depending on type
	switch(playlistType)
	{
	case m3uPlaylist:
		return parsePlaylist_m3u(data, fileList, baseDir, rootDir);
		break;
	case plsPlaylist:
		return parsePlaylist_pls(data, fileList, baseDir, rootDir);
		break;
	case wplPlaylist:
		return parsePlaylist_wpl(data, fileList, baseDir, rootDir);
		break;
	default:
		return false;
		break;
	}
}
void WizUpdaterDialog::doUpdateAppSetSteps()
{
    int steps = 0;

    QString strUpdate = ::WizGetUpgradePath();
    QDir rootDir(strUpdate);

    steps = rootDir.entryList().count();

    ui->progressUpdate->setMaximum(steps);
}
void WizUpdaterDialog::doOldDatabaseUpgradeSetSteps()
{
    int steps = 0;

    QString oldDataStorePath = QDir::homePath() + "/WizNote/";
    QDir rootDir(oldDataStorePath);

    steps = rootDir.entryList().count();

    ui->progressUpdate->setMaximum(steps + 10);
}
Пример #17
0
QList<Snapshot> SnapshotsFile::getSnapshots( const QString& sessionId ) const {
    QString rootDirName = _getRootDir(sessionId);
    QDir rootDir( rootDirName );
    QMap<QString,Snapshot> snapshotList;
    if ( rootDir.exists() ){
        _processDirectory( sessionId, rootDir, snapshotList );
    }
    else {
        qWarning()<<"Please check installation to make sure snapshot directory exists.";
    }
    return snapshotList.values();
}
Пример #18
0
QList<Snapshot> SnapshotsFile::_updateSnapshots( const QString& sessionId ){
    QString rootDirName = _getRootDir(sessionId);
    QDir rootDir( rootDirName );
    QMap<QString,Snapshot> snapshotList;
    if ( rootDir.exists() ){
        _processDirectory( sessionId, rootDir, snapshotList );
    }
    else {
        qWarning()<<"Please check that the snapshot directories exist";
    }
    return snapshotList.values();
}
Пример #19
0
InstanceFactory::InstCreateError InstanceFactory::createInstance(InstancePtr &inst, BaseVersionPtr version,
								const QString &instDir, const InstanceFactory::InstType type)
{
	QDir rootDir(instDir);

	QLOG_DEBUG() << instDir.toUtf8();
	if (!rootDir.exists() && !rootDir.mkpath("."))
	{
		return InstanceFactory::CantCreateDir;
	}
	auto mcVer = std::dynamic_pointer_cast<MinecraftVersion>(version);
	if (!mcVer)
		return InstanceFactory::NoSuchVersion;

	auto m_settings = new INISettingsObject(PathCombine(instDir, "instance.cfg"));
	m_settings->registerSetting("InstanceType", "Legacy");

	if (type == NormalInst)
	{
		m_settings->set("InstanceType", "OneSix");
		inst.reset(new OneSixInstance(instDir, m_settings, this));
		inst->setIntendedVersionId(version->descriptor());
		inst->setShouldUseCustomBaseJar(false);
	}
	else if (type == FTBInstance)
	{
		if(mcVer->usesLegacyLauncher())
		{
			m_settings->set("InstanceType", "LegacyFTB");
			inst.reset(new LegacyFTBInstance(instDir, m_settings, this));
			inst->setIntendedVersionId(version->descriptor());
			inst->setShouldUseCustomBaseJar(false);
		}
		else
		{
			m_settings->set("InstanceType", "OneSixFTB");
			inst.reset(new OneSixFTBInstance(instDir, m_settings, this));
			inst->setIntendedVersionId(version->descriptor());
			inst->setShouldUseCustomBaseJar(false);
		}
	}
	else
	{
		delete m_settings;
		return InstanceFactory::NoSuchVersion;
	}

	inst->init();

	// FIXME: really, how do you even know?
	return InstanceFactory::NoCreateError;
}
Пример #20
0
WrapperStr UmlPackage::source_path(const WrapperStr & f, WrapperStr relto)
{
    if (!dir.read) {
        dir.src = cppSrcDir();
        dir.h = cppHDir();
        dir.src_absolute = dir.h_absolute = FALSE;

        QDir d_root(rootDir());

        if (dir.src.isEmpty())
            // considered given relative
            dir.src = RootDir;
        else if (QDir::isRelativePath(dir.src))
            dir.src = d_root.filePath(dir.src);
        else
            dir.src_absolute = TRUE;

        if (dir.h.isEmpty())
            // considered given relative
            dir.h = RootDir;
        else if (QDir::isRelativePath(dir.h))
            dir.h = d_root.filePath(dir.h);
        else
            dir.h_absolute = TRUE;

        if (dir.src.isEmpty()) {
            UmlCom::trace(WrapperStr("<font color=\"red\"><b><b> The generation directory "
                                    "must be specified for the package<i> ") + name()
                          + "</i>, edit the <i> generation settings</i> (tab 'directory') "
                          "or edit the package (tab 'C++')</b></font><br>");
            UmlCom::bye(n_errors() + 1);
            UmlCom::fatal_error("UmlPackage::source_path");
        }

        dir.read = TRUE;
    }

    if (f.isEmpty())
        return dir.src;

    QDir d(dir.src);

    if (! d.exists())
        create_directory(dir.src);	// don't return on error

    QByteArray temp = d.filePath(f).toLatin1();
    WrapperStr df = (dir.src_absolute || relto.isEmpty())
                   ? WrapperStr(temp.constData())
                   : relative_path(d, relto) + f;

    return df + WrapperStr(".") + CppSettings::sourceExtension();
}
Пример #21
0
QStringList DBThread::getValidDownloadDirs() const
{
    QStringList docPaths=QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
    QString s = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    docPaths.prepend(s.left(s.lastIndexOf("/osmscout")));

#ifdef __UBUNTU__
    ///TODO: search removable drives using QStorageInfo, will be available in Vivid
    //QList<QStorageInfo> volumes = QStorageInfo::mountedVolumes();
    QDir mediaPath("/media");
    QStringList removableUserList = mediaPath.entryList(QDir::NoDotAndDotDot | QDir::Dirs);
    for(int i=0; i<removableUserList.size(); i++) //find <user directories in media
    {
        std::cout<<"Found user: "******"/media/"+removableUserList[i]);
        QStringList removablePaths = removablePath.entryList(QDir::NoDotAndDotDot | QDir::Dirs);
        for(int j=0; j<removablePaths.size(); j++)
        {
            std::cout<<"Found removable path: "<<("/media/"+removableUserList[i]+"/"+removablePaths[j]).toLocal8Bit().data()<<std::endl;
            docPaths.append("/media/"+removableUserList[i]+"/"+removablePaths[j]);
        }
    }
#endif
    for(int i=0; i<docPaths.size(); i++)
    {
        QDir _rootDir(docPaths[i]);
        _rootDir.mkdir(docPaths[i]);
        QDir rootDir(docPaths[i]+"/Maps"); //last one is preferred first
        QFileInfo fi(docPaths[i]);
        if(!rootDir.exists()||!fi.isDir())
        {
            if(!rootDir.mkdir(docPaths[i]+"/Maps")){
                docPaths.removeAt(i);
                i--;
                qDebug()<<"Could not create "<<docPaths[i]<<"/Maps";
                continue;
            }

        }
        if(!this->testWritable(docPaths[i]+"/Maps"))
        {
            docPaths.removeAt(i);
            i--;
            qDebug()<<"Path not writable";
            continue;
        }
    }
    return docPaths;
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void RicFileHierarchyDialog::slotDialogOkClicked()
{
    m_files.clear();

    int itemCount = m_fileList->count();
    for (int i = 0; i < itemCount; i++)
    {
        const QListWidgetItem* item = m_fileList->item(i);
        if ((item->flags() & Qt::ItemIsUserCheckable) != 0 && item->checkState())
        {
            m_files.push_back(rootDir() + item->text());
        }
    }
    accept();
}
Пример #23
0
// -----------------------------------------------------------------------------
// Reads bzip2 format data from a MemChunk
// Returns true if successful, false otherwise
// -----------------------------------------------------------------------------
bool BZip2Archive::open(MemChunk& mc)
{
	size_t size = mc.size();
	if (size < 14)
		return false;

	// Read header
	uint8_t header[4];
	mc.read(header, 4);

	// Check for BZip2 header (reject BZip1 headers)
	if (!(header[0] == 'B' && header[1] == 'Z' && header[2] == 'h' && (header[3] >= '1' && header[3] <= '9')))
		return false;

	// Build name from filename
	string     name = filename(false);
	wxFileName fn(name);
	if (!fn.GetExt().CmpNoCase("tbz") || !fn.GetExt().CmpNoCase("tb2") || !fn.GetExt().CmpNoCase("tbz2"))
		fn.SetExt("tar");
	else if (!fn.GetExt().CmpNoCase("bz2"))
		fn.ClearExt();
	name = fn.GetFullName();

	// Let's create the entry
	setMuted(true);
	auto     entry = std::make_shared<ArchiveEntry>(name, size);
	MemChunk xdata;
	if (Compression::bzip2Decompress(mc, xdata))
	{
		entry->importMemChunk(xdata);
	}
	else
	{
		setMuted(false);
		return false;
	}
	rootDir()->addEntry(entry);
	EntryType::detectEntryType(entry.get());
	entry->setState(ArchiveEntry::State::Unmodified);

	setMuted(false);
	setModified(false);
	announce("opened");

	// Finish
	return true;
}
Пример #24
0
InstanceFactory::InstCreateError InstanceFactory::createInstance( BaseInstance*& inst, BaseVersionPtr version, const QString& instDir )
{
	QDir rootDir(instDir);
	
	QLOG_DEBUG() << instDir.toUtf8();
	if (!rootDir.exists() && !rootDir.mkpath("."))
	{
		return InstanceFactory::CantCreateDir;
	}
	auto mcVer = std::dynamic_pointer_cast<MinecraftVersion>(version);
	if(!mcVer)
		return InstanceFactory::NoSuchVersion;
	
	auto m_settings = new INISettingsObject(PathCombine(instDir, "instance.cfg"));
	m_settings->registerSetting(new Setting("InstanceType", "Legacy"));
	
	switch(mcVer->type)
	{
		case MinecraftVersion::Legacy:
			m_settings->set("InstanceType", "Legacy");
			inst = new LegacyInstance(instDir, m_settings, this);
			inst->setIntendedVersionId(version->descriptor());
			inst->setShouldUseCustomBaseJar(false);
			break;
		case MinecraftVersion::OneSix:
			m_settings->set("InstanceType", "OneSix");
			inst = new OneSixInstance(instDir, m_settings, this);
			inst->setIntendedVersionId(version->descriptor());
			inst->setShouldUseCustomBaseJar(false);
			break;
		case MinecraftVersion::Nostalgia:
			m_settings->set("InstanceType", "Nostalgia");
			inst = new NostalgiaInstance(instDir, m_settings, this);
			inst->setIntendedVersionId(version->descriptor());
			inst->setShouldUseCustomBaseJar(false);
			break;
		default:
		{
			delete m_settings;
			return InstanceFactory::NoSuchVersion;
		}
	}
	
	//FIXME: really, how do you even know?
	return InstanceFactory::NoCreateError;
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
QStringList RicFileHierarchyDialog::buildDirectoryListRecursive(const QString& currentDir, int level)
{
    QStringList allDirs;

    if (cancelPressed()) return allDirs;

    QString currPathFilter = pathFilter();
    bool subStringFilter = false;

    // Optimizing for speed by a refined match at first directory level
    if (level == 1)
    {
        QString pathFilter = this->pathFilter();
        if (!pathFilter.startsWith("*"))
        {
            int wildcardIndex = pathFilter.indexOf(QRegExp(QString("[*%1]").arg(SEPARATOR)));
            if (wildcardIndex >= 0)
            {
                currPathFilter = pathFilter.left(wildcardIndex + 1);
                subStringFilter = true;
            }
        }
    }

    QString currRelPath = RiaFilePathTools::relativePath(rootDir(), currentDir);
    if (pathFilterMatch(currPathFilter, currRelPath))
    {
        allDirs.push_back(currentDir);
    }
    else if(level == 1 && subStringFilter)
    {
        return QStringList();
    }

    QDir qdir(currentDir);
    QStringList subDirs = qdir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    for (QString subDir : subDirs)
    {
        QString subDirFullPath = qdir.absoluteFilePath(subDir);
        updateStatus(SEARCHING_FOR_DIRS, subDirFullPath);
        QApplication::processEvents();
        allDirs += buildDirectoryListRecursive(subDirFullPath, level + 1);
    }
    return cancelPressed() ? QStringList() : allDirs;
}
Пример #26
0
void LoacalFileServer::display(QString* currentPath)
{
	//QString currentPath = root;
	this->setWindowTitle("LocalFileServer : "+(*currentPath));
	QDir rootDir(*currentPath);
	QList<QTreeWidgetItem *> itemList;
	QStringList tmplist;
	tmplist << "*";
	QFileInfoList list = rootDir.entryInfoList(tmplist);

	for(unsigned int i = 0;i<list.count();i++)
	{
		QFileInfo tmpFileInfo = list.at(i);

		QTreeWidgetItem *item = new QTreeWidgetItem;
		
		if(tmpFileInfo.fileName() == "." || tmpFileInfo.fileName() == "..")
				continue;

		item->setText(0,tmpFileInfo.fileName());
		
		if(tmpFileInfo.isDir())
		{
			item->setText(1,QString(""));
		}
		else
		{
			item->setText(1,QString::number(tmpFileInfo.size()));
		}
		
		item->setText(2,tmpFileInfo.created().toString("MMM dd yyyy"));
		
		item->setText(3,tmpFileInfo.lastModified().toString("MMM dd yyyy"));

		QPixmap pixmap(tmpFileInfo.isDir()?"./dir.png":"./file.png");
		item->setIcon(0,pixmap);
		
		itemList.push_back(item);

		//the path is whether the directory
		isDirectory[tmpFileInfo.fileName()] = tmpFileInfo.isDir();
	}

	fileWidget->addTopLevelItems(itemList);
}
Пример #27
0
/**
  * Returns in m_newFiles the newly found sub directories of root.
  */
void Watcher::getNewSubDirectories(QString root) {
    if (root.isEmpty() || m_stop)
        return;

    //  add new root to the list of directories
    m_newFiles.addPath(root, true);

    // signal new directory
    directoryAdded(root);

    // create a directory
    QDirExt rootDir(root);

    // get the directory entries
    QStringList entries = rootDir.entryList();

    if (entries.isEmpty())
        return;

    // give the user a hint about what's going on down here
    displayActivity(tr("Exploring directory %1").arg(root));

    // walk down recursively through the directories
    for (QList<QString>::iterator i = entries.begin(); !m_stop && i != entries.end(); i++) {
        QString entryPath = root;
        entryPath.append(QDirExt::separator(root));
        entryPath.append(*i);
        QFileInfoExt entry(entryPath);

        if (entry.isHidden())
            continue;

        if (entry.isDir()) {
            // recursively go through children dirs if required
            if (m_recursive && !m_files.findPath(entryPath)) {
                getNewSubDirectories(entryPath);

#ifdef _VERBOSE_WATCHER
                qDebug() << "Detected new directory " << entryPath;
#endif
            }
        }
    }
}
Пример #28
0
bool Path::NewPath(const QString& path,const QString& folderName){
	mPath.clear();
	QDir rootDir(path);
	FAIL_RET(rootDir.exists());
	FAIL_RET(rootDir.mkdir(folderName));
	FAIL_RET(rootDir.cd(folderName));
	FAIL_RET(rootDir.mkpath(ASSET_INNER_PATH));
    FAIL_RET(rootDir.mkpath(OBJECT_INNER_PATH));
	FAIL_RET(rootDir.mkpath(MAP_INNER_PATH));
    FAIL_RET(rootDir.mkpath(MAP_INNER_PATH_JSON));
	FAIL_RET(rootDir.mkpath(ZIP_INNER_PATH));
	mAssetDir.setPath(rootDir.absoluteFilePath(ASSET_INNER_PATH));
	FAIL_RET(mAssetDir.exists());
    mObjectDir.setPath(rootDir.absoluteFilePath(OBJECT_INNER_PATH));
    FAIL_RET(mObjectDir.exists());
	mPath = rootDir.absolutePath();
	AddRecentProject(mPath);
	return true;
}
Пример #29
0
void NewDatabaseDlg::buildButtonPressed()
{
    QDir rootDir(ui->directoryEdit->text());
    QFileInfo outFileInfo(ui->nameEdit->text());
    if ("" == ui->nameEdit->text() || outFileInfo.isDir()) {
        QMessageBox::warning(this,
                             tr("Error"),
                             tr("You have to specify a file for the new database."),
                             QMessageBox::Ok);
        return;
    } else if (!rootDir.exists()) {
        QMessageBox::warning(this,
                             tr("Error"),
                             tr("You have to specify a valid directory."),
                             QMessageBox::Ok);
        return;
    }
    if (outFileInfo.exists()) {
        if (QMessageBox::question(this,
                                  tr("The database file exists already"),
                                  tr("The chosen database file already exists. Do you want to override it?"),
                                  QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
            return;
        }
    }
    QFile outFile(ui->nameEdit->text());
    if (!outFile.open(QIODevice::WriteOnly)) {
        QMessageBox::warning(this,
                             tr("Error"),
                             tr("The database file you specified can not be written. Specify another one."),
                             QMessageBox::Ok);
        return;
    }
    outFile.close();
    outFile.remove();
    m_canceled = false;
    this->m_directory = ui->directoryEdit->text();
    this->m_name = ui->nameEdit->text();
    this->m_includeSubdirs = ui->includeSubdirectories->isChecked();
    this->writeSettings();
    close();
}
void WizUpdaterDialog::doOldDatabaseUpgrade()
{
    QDir homeDir(QDir::homePath());
    QString oldDataStorePath = QDir::homePath() + "/WizNote/";
    QString newDataStorePath = QDir::homePath() + "/.wiznote/";

    bool ret = homeDir.rmdir(newDataStorePath);

    if (ret) {
        homeDir.rename(oldDataStorePath, newDataStorePath);
    } else {
        QMessageBox::critical(this, tr("Error"), tr("the .wiznote directory should be empty, please contect R&D team!"));
        return;
    }

    QDir rootDir(newDataStorePath);

    rootDir.remove("wiznote.ini");
    setGuiNotify("Remove wiznote.ini");
    rootDir.remove("wiznote.log");
    setGuiNotify("Remove wiznote.log");

    // enum each user
    CWizStdStringArray folders;
    WizEnumFolders(newDataStorePath, folders, 0);
    foreach (const QString& folder, folders) {
        QDir userDir(folder);

        QString strOldNotes = folder + "Notes/";
        QString strOldAttaches = folder + "Attachments/";

        // rename notes data
        CWizStdStringArray notes;
        WizEnumFiles(strOldNotes, "*.ziw", notes, 0);
        foreach (const QString& note, notes) {
            QDir dirNote(strOldNotes);
            // 36 chars for GUID and 4 chars for extention
            QString strNewName = strOldNotes + "{" + note.right(40).left(36) + "}";
            dirNote.rename(note, strNewName);
            setGuiNotify(QString("Rename %1").arg(note));
        }