Error DirAccessAndroid::change_dir(String p_dir){

	p_dir=p_dir.simplify_path();

	if (p_dir=="" || p_dir=="." || (p_dir==".." && current_dir==""))
		return OK;

	String new_dir;

	if (p_dir.begins_with("/"))
		new_dir=p_dir.substr(1,p_dir.length());
	else if (p_dir.begins_with("res://"))
		new_dir=p_dir.substr(6,p_dir.length());
	else  //relative
		new_dir=new_dir+"/"+p_dir;

//test if newdir exists
	new_dir=new_dir.simplify_path();

	AAssetDir* aad = AAssetManager_openDir(FileAccessAndroid::asset_manager,new_dir.utf8().get_data());
	if (aad) {

		current_dir=new_dir;
		AAssetDir_close(aad);
		return OK;
	}

	return ERR_INVALID_PARAMETER;
}
 AndroidAssetDir(AAssetDir* ad)
 {
     const char *fileName;
     while ((fileName = AAssetDir_getNextFileName(ad)))
         m_items.push_back(QString::fromUtf8(fileName));
     AAssetDir_close(ad);
 }
	FileInfoListPtr APKFileSystemArchive::listFileInfo(bool recursive, bool dirs)
	{
		FileInfoListPtr files(new FileInfoList);

		AAssetDir* dir = AAssetManager_openDir(mAssetMgr, mName.c_str());
		const char* fileName = NULL;
		while((fileName = AAssetDir_getNextFileName(dir)) != NULL)
		{
			AAsset* asset = AAssetManager_open(mAssetMgr, (mPathPreFix + String(fileName)).c_str(), AASSET_MODE_UNKNOWN);
			if(asset)
			{
				FileInfo info;
				info.archive = this;
				info.filename = fileName;
				info.path = mName;
				info.basename = fileName;
				info.compressedSize = AAsset_getLength(asset);
				info.uncompressedSize = info.compressedSize;
				files->push_back(info);

				AAsset_close(asset);
			}

		}
		AAssetDir_close(dir);

		return files;
	}
Example #4
0
//--------------------------------------------------------------------------
void VeAssetPath::FindFileList(const VeChar8* pcDesc,
	VeVector<VeFixedString>& kOut) const noexcept
{
	const VeChar8* pcFile = VeStrrchr(pcDesc, '/');
	pcFile = pcFile ? (pcFile + 1) : pcDesc;
	AAssetDir* pkDir(nullptr);
	if (pcFile == pcDesc)
	{
		pkDir = AAssetManager_openDir(s_pkAssetManager, m_kPath);
	}
	else
	{
		VeChar8 acBuffer[VE_MAX_PATH_LEN];
		VeChar8* pcTemp = acBuffer;
		if (m_kPath.GetLength())
		{
			pcTemp += VeSprintf(acBuffer, "%s/", m_kPath.GetStr());
		}
		VeStrncpy(pcTemp, VE_MAX_PATH_LEN, pcDesc, pcFile - pcDesc - 1);
		pkDir = AAssetManager_openDir(s_pkAssetManager, acBuffer);
	}
	if (pkDir)
	{
		const VeChar8* pcEntry;
		while ((pcEntry = AAssetDir_getNextFileName(pkDir)))
		{
			if (VeWildNameMatch(pcEntry, pcFile))
			{
				kOut.push_back(pcEntry);
			}
		}
		AAssetDir_close(pkDir);
	}
}
CPUTFileSystem::CPUTandroidifstream::~CPUTandroidifstream()
{
    if (mpAsset)
        AAsset_close(mpAsset);
    if (mpAssetDir)
        AAssetDir_close(mpAssetDir);    
}
void CPUTFileSystem::CPUTandroidifstream::close()
{
    if (mpAsset)
        AAsset_close(mpAsset);
    if (mpAssetDir)
        AAssetDir_close(mpAssetDir);    
    mpAsset = NULL;
    mpAssetDir = NULL;
}
void DirAccessAndroid::list_dir_end(){

	if (aad==NULL)
		return;

	AAssetDir_close(aad);
	aad=NULL;

}
Example #8
0
void print_assets()
{
    AAssetManager* assetManager = GetJavaAssetManager();
    AAssetDir* assetDir = AAssetManager_openDir(assetManager, "images");
    const char* filename;
	__android_log_print(ANDROID_LOG_INFO,"Frogatto","print_assets()");
    while((filename = AAssetDir_getNextFileName(assetDir)) != 0) {
		__android_log_print(ANDROID_LOG_INFO,"Frogatto","File: %s",filename);
	}
    AAssetDir_close(assetDir);
}
Example #9
0
Player* engine_load_player (
	Context* context
	, Engine* engine
	, char* basename
	, int centre_x
	, int centre_y
) {
	Player* player = (Player*) malloc(sizeof(Player));
	Bitmap** bmps = (Bitmap**) malloc(MAX_BMPS * sizeof(Bitmap*));
	int len = 0;
	
	AAssetDir* dir = AAssetManager_openDir(
		context->app->activity->assetManager
		, "sprites"
	);
	
	char* name;
	char fpath[64] = "sprites/";
	
	if (dir == NULL) {
		LOGE("Unable to load sprites.");
		exit(EXIT_FAILURE);
	}
	
	do {
		name = (char*) AAssetDir_getNextFileName(dir);
		
		if (name == NULL) {
			break;
		}
		
		if (strncasecmp(name, basename, strlen(basename)) != 0) {
			continue;
		}
		
		memset(fpath + 8, 0, 56 * sizeof(char));
		strlcat(fpath, name, 64);
		bmps[len] = engine_load_asset(context, fpath);
		len++;
	} while (name != NULL);
	
	if (len == 0) {
		LOGE("Unable to load sprite.");
		exit(EXIT_FAILURE);
	}
	
	AAssetDir_close(dir);
	
	bmps = (Bitmap**) realloc(bmps, len * sizeof(Bitmap*));
	engine_init_player(context, engine, player, centre_x, centre_y, bmps);
	
	return player;
}
QAbstractFileEngine * AndroidAssetsFileEngineHandler::create(const QString &fileName) const
{
	__android_log_print(ANDROID_LOG_INFO, g_kjpbsTag, QString("In AndroidAssetsFileEngineHandler::create for \"%1\"").arg(fileName).toUtf8().data());
	if (m_assetManager == NULL) {
		__android_log_print(ANDROID_LOG_FATAL, g_kjpbsTag, "AndroidAssetsFileEngineHandler::create - assetManager is NULL");
		return NULL;
	}

	if (fileName.isEmpty()) {
		__android_log_print(ANDROID_LOG_WARN, g_kjpbsTag, "AndroidAssetsFileEngineHandler::create - fileName is empty");
		return NULL;
	}

	if (!fileName.startsWith(QLatin1String("assets:/"))) {
		__android_log_print(ANDROID_LOG_WARN, g_kjpbsTag, "AndroidAssetsFileEngineHandler::create - fileName not in \"assets:/\" namespace");
		return NULL;
	}

    int prefixSize=8;

    m_path.clear();
    if (!fileName.endsWith(QLatin1Char('/'))) {
        m_path = fileName.toUtf8();
        AAsset *asset = AAssetManager_open(m_assetManager,
                                           m_path.constData() + prefixSize,
                                           AASSET_MODE_BUFFER);
		if (asset) {
			__android_log_print(ANDROID_LOG_INFO, g_kjpbsTag, QString("AndroidAssetsFileEngineHandler::create - Open File : \"%1\" SUCCESS").arg(fileName).toUtf8().data());
            return new AndroidAbstractFileEngine(asset, fileName);
		} else {
			__android_log_print(ANDROID_LOG_WARN, g_kjpbsTag, QString("AndroidAssetsFileEngineHandler::create - open \"%1\" as file failed").arg(fileName).toUtf8().data());
		}
    }

	if (!m_path.size())
		 m_path = fileName.left(fileName.length() - 1).toUtf8();

    AAssetDir *assetDir = AAssetManager_openDir(m_assetManager, m_path.constData() + prefixSize);
    if (assetDir) {
		__android_log_print(ANDROID_LOG_INFO, g_kjpbsTag, QString("AndroidAssetsFileEngineHandler::create - Open Dir : \"%1\" SUCCESS").arg(fileName).toUtf8().data());
		if (AAssetDir_getNextFileName(assetDir)) {
			__android_log_print(ANDROID_LOG_INFO, g_kjpbsTag, "GetNextFileName for Dir SUCCESS");
            return new AndroidAbstractFileEngine(assetDir, fileName);
		} else {
			__android_log_print(ANDROID_LOG_INFO, g_kjpbsTag, "GetNextFileName for Dir AT END");
            AAssetDir_close(assetDir);
		}
	} else {
		__android_log_print(ANDROID_LOG_WARN, g_kjpbsTag, QString("AndroidAssetsFileEngineHandler::create - open \"%1\" as dir failed").arg(fileName).toUtf8().data());
	}

	return NULL;
}
Example #11
0
int
asset_extract(const char *assetdir, const char *topath, const char *ext) {
    char fromdir[PATH_MAX];
    if (assetdir[0] == '\0') {
        strcpy(fromdir, "files");
    } else {
        snprintf(fromdir, sizeof(fromdir), "files/%s", assetdir);
    }
    AAssetDir *dir = AAssetManager_openDir(__A, fromdir);
    if (dir == NULL) {
        pf_log("[!no asset dir] %s", fromdir);
        return 1;
    }
    char buf[2048];
    char todir[PATH_MAX];
    if (assetdir[0] == '\0') {
        strcpy(todir, topath);
    } else {
        snprintf(todir, sizeof(todir), "%s/%s", topath, assetdir);
    }
    mkdir(todir, 0770);

    size_t extlen = strlen(ext);

    char fromfile[PATH_MAX];
    char tofile[PATH_MAX];
    const char *fname;
    while (fname = AAssetDir_getNextFileName(dir)) {
        if (endswith(fname, ext, extlen)) {
            snprintf(fromfile, sizeof(fromfile), "%s/%s", fromdir, fname);
            snprintf(tofile, sizeof(tofile), "%s/%s", todir, fname);
            pf_log("%s -> %s", fromfile, tofile);
            AAsset *asset = AAssetManager_open(__A, fromfile, 2);
            if (asset) {
                FILE *fp = fopen(tofile, "w+");
                if (fp == NULL) {
                    pf_log("asset extract fail: %s", tofile);
                }
                int rd;
                while ((rd = AAsset_read(asset, buf, sizeof(buf))) > 0) {
                    fwrite(buf, rd, 1, fp);
                }
                fclose(fp);
                AAsset_close(asset);
            } else {
                pf_log("[!no asset] %s", fromfile);
            }
        }
    }
    AAssetDir_close(dir);
    return 0;
}
Example #12
0
void get_files_in_dir(const std::string& sdirectory,
					  std::vector<std::string>* files,
					  std::vector<std::string>* dirs,
					  FILE_NAME_MODE mode)
{
    AAssetManager* assetManager = GetJavaAssetManager();
    AAssetDir* assetDir; 
	std::string directory(sdirectory);
	int len = directory.length()-1;
	if(directory[len] == '/') {
		directory = directory.substr(0,len);
	}
	if(directory[0] == '.' && directory[1] == '/') {
		directory = directory.substr(2);
	}
	//LOG("get_files_in_dir() : " << directory << " : " << sdirectory);
	assetDir = AAssetManager_openDir(assetManager, directory.c_str());
    const char* filename;
	bool read_dirs_txt = false;
    while((filename = AAssetDir_getNextFileName(assetDir)) != 0) {
	//	__android_log_print(ANDROID_LOG_INFO,"Frogatto:get_files_in_dir","File: %s",filename);
		//LOG("get_files_in_dir() : " << filename);
        if(filename[0] != '.') {
			std::string s(filename);
			if(dirs != 0 && s.compare("dirs.txt") == 0) {
				read_dirs_txt = true;
			} else {
            	if(files) {
                	files->push_back(s);
				}
            }
        }
    }
    AAssetDir_close(assetDir);
	//LOG("get_files_in_dir() : after close");
	if(read_dirs_txt) {
		//LOG("get_files_in_dir() : read_files : " << directory << "/dirs.txt");
		std::string dir_list = read_file(directory + "/dirs.txt");
		while(dir_list[dir_list.length()-1] == '\n') {
			dir_list = dir_list.substr(0,dir_list.length()-1);
		}
		boost::split(*dirs, dir_list, std::bind2nd(std::equal_to<char>(), '\n'));
		//LOG("get_files_in_dir() : after split");
	}

	if(files != NULL)
		std::sort(files->begin(),files->end());
	if (dirs != NULL)
		std::sort(dirs->begin(),dirs->end());
	//LOG("get_files_in_dir : after sorts");
}
	StringVectorPtr APKFileSystemArchive::list(bool recursive, bool dirs)
	{
		StringVectorPtr files(new StringVector);

		AAssetDir* dir = AAssetManager_openDir(mAssetMgr, mName.c_str());
		const char* fileName = NULL;
		while((fileName = AAssetDir_getNextFileName(dir)) != NULL)
		{
			files->push_back(fileName);
		}
		AAssetDir_close(dir);

		return files;
	}
Example #14
0
//--------------------------------------------------------------------------
VeDirectoryPtr VeAssetPath::Create(const VeChar8* pcPath,
	bool bTryCreate) noexcept
{
	AAssetDir* pkDir = AAssetManager_openDir(s_pkAssetManager, pcPath);
	if (pkDir)
	{
		AAssetDir_close(pkDir);
		return VE_NEW VeAssetPath(pcPath);
	}
	else
	{
		return nullptr;
	}
}
Example #15
0
//--------------------------------------------------------------------------
bool VeAssetPath::HasSubDir(const VeChar8* pcDir) const noexcept
{
	VeChar8 acBuffer[VE_MAX_PATH_LEN];
	PATH_CAT(acBuffer, m_kPath, pcDir);
	AAssetDir* pkDir = AAssetManager_openDir(s_pkAssetManager, acBuffer);
	if (pkDir)
	{
		AAssetDir_close(pkDir);
		return true;
	}
	else
	{
		return false;
	}
}
	StringVectorPtr APKFileSystemArchive::find(const String& pattern, bool recursive, bool dirs)
	{
		StringVectorPtr files(new StringVector);

		AAssetDir* dir = AAssetManager_openDir(mAssetMgr, mName.c_str());
		const char* fileName = NULL;
		while((fileName = AAssetDir_getNextFileName(dir)) != NULL)
		{
			if(StringUtil::match(fileName, pattern))
					files->push_back(fileName);
		}
		AAssetDir_close(dir);

		return files;
	}
Example #17
0
bool AssetArchive::fixCase(String& streamName)
{
	String dir = _dir;
	String patternDir;
	String filePattern;

	size_t slashPos = streamName.find_last_of('/');

	if (slashPos != streamName.npos)
	{
		patternDir = streamName.substr(0, slashPos+1);
		dir += patternDir;
		filePattern = streamName.substr(slashPos+1);
	}
	else
	{
		filePattern = streamName;
	}

	// openDir() requires no trailing '/'
	if (!dir.empty() && dir[dir.length()-1] == '/')
		dir.resize(dir.length()-1);

	AAssetDir* assetDir = AAssetManager_openDir(_assetManager, dir.c_str());
	if (assetDir == NULL)
		return false;

	bool fixed = false;
	while (true)
	{
		const char* filename = AAssetDir_getNextFileName(assetDir);
		if (filename == NULL) break;

		// filename returned as all directory part extracted and only the last component

		if (_strcmpi(filename, filePattern.c_str()) == 0)
		{
			LOG(0, "?? fixed case: '%s' -> '%s'\n", makeUrl(streamName).c_str(), makeUrl(patternDir + filename).c_str());
			streamName = patternDir + filename;
			fixed = true;
			break;
		}
	}

	AAssetDir_close(assetDir);

	return fixed;
}
Example #18
0
void AssetArchive::findLocal(const String& pattern, StreamSourceMap& varResults)
{
	if (_assetManager == NULL)
		NIT_THROW_FMT(EX_IO, "AssetManager not available");

	String dir = _dir;
	String patternDir;
	String filePattern;

	size_t slashPos = pattern.find_last_of('/');

	if (slashPos != pattern.npos)
	{
		patternDir = pattern.substr(0, slashPos+1);
		dir += patternDir;
		filePattern = pattern.substr(slashPos+1);
	}
	else
	{
		filePattern = pattern;
	}

	// openDir() requires no trailing '/'
	if (!dir.empty() && dir[dir.length()-1] == '/')
		dir.resize(dir.length()-1);

	AAssetDir* assetDir = AAssetManager_openDir(_assetManager, dir.c_str());
	if (assetDir == NULL)
		return;

	while (true)
	{
		const char* filename = AAssetDir_getNextFileName(assetDir);
		if (filename == NULL) break;

		// filename returned as all directory part extracted and only the last component

		if (Wildcard::match(filePattern, filename))
		{
			String streamName = patternDir + filename;
			varResults.insert(std::make_pair(streamName, new Asset(this, streamName)));
		}
	}

	AAssetDir_close(assetDir);
}
Example #19
0
	void ListFiles_android(behaviac::vector<behaviac::string>& files, const char* szDirName, bool bRecurrsive)
	{
        AAssetManager* mgr = behaviac::CFileManager::GetInstance()->GetAssetManager();
		if (mgr != NULL)
		{
			const char* validDir = szDirName;
            //skip "assets:/"
			if (behaviac::StringUtils::StartsWith(validDir, "assets:/"))
			{
				validDir = validDir + 8;
			}

			AAssetDir* dir = AAssetManager_openDir(mgr, validDir);
			if (dir != NULL)
			{
				bool bEndsWithSlash = behaviac::StringUtils::EndsWith(szDirName, "/");
				if (!bEndsWithSlash)
				{
					bEndsWithSlash = behaviac::StringUtils::EndsWith(szDirName, "\\");
				}

				while (true)
				{
					const char* fileName = AAssetDir_getNextFileName(dir);
					if (fileName == NULL)
					{
						break;
					}

                    if (bEndsWithSlash)
					{
						fileName = behaviac::FormatString("%s%s", szDirName, fileName);
					}
					else
					{
						fileName = behaviac::FormatString("%s/%s", szDirName, fileName);
					}

					files.push_back(fileName);
				}

				AAssetDir_close(dir);
			}
		}
	}
Example #20
0
bool androidExtractAll() {
	AAssetDir* assetDir = AAssetManager_openDir(gActivity->assetManager, "");
	const char* filename = (const char*)NULL;
	std::string assetContent;
	while ((filename = AAssetDir_getNextFileName(assetDir)) != NULL) {
		std::string newPath = androidGetPath(filename);
		AAsset* asset = AAssetManager_open(gActivity->assetManager, filename,
		                                   AASSET_MODE_STREAMING);
		FLOG_DEBUG("File %s opened for extraction ...", filename );
		// Find size
		off_t assetSize = AAsset_getLength(asset);

		// Prepare input buffer
		assetContent.resize(assetSize);

		// Store input buffer
		AAsset_read(asset, &assetContent[0], assetSize);

		// Close
		AAsset_close(asset);

		// Check if file exists
		std::ifstream f(newPath.c_str());
		if (f.good()) {
			f.close();
			FLOG_DEBUG("Asset %s already extracted", filename);
		} else {
			// Prepare output buffer
			std::ofstream assetExtracted(newPath.c_str(),
			                             std::ios::out | std::ios::binary);
			if (!assetExtracted) {
				FLOG_ERROR("File %s not extracted", newPath.c_str());
				return false;
			}

			// Write output buffer into a file
			assetExtracted.write(assetContent.c_str(), assetSize);
			assetExtracted.close();

			FLOG_DEBUG("File %s extracted", filename);
		}
	}
	return true;
	AAssetDir_close(assetDir);
}
Example #21
0
bool DirAccessAndroid::current_is_dir() const{

	String sd;
	if (current_dir=="")
		sd=current;
	else
		sd=current_dir+"/"+current;

	AAssetDir* aad2 = AAssetManager_openDir(FileAccessAndroid::asset_manager,sd.utf8().get_data());
	if (aad2) {

		AAssetDir_close(aad2);
		return true;
	}

	return false;

}
// eng: Finds the next ptc-file in emitters folder
// rus: Поиск очередного ptc-файла в папке с эмиттерами
const char* MP_Platform_COCOS::GetNextFile()
{
	const char* result=AAssetDir_getNextFileName(asset_dir);
	while(result)
	{
		int len=strlen(result);
		if (len>4)
		{
			const char* ext=&(result[len-4]);
			if (strcmp(ext, ".ptc")==0)
				return result;
		}
		result=AAssetDir_getNextFileName(asset_dir);
	}
	AAssetDir_close(asset_dir);
	asset_dir=NULL;
	return NULL;
}
QAbstractFileEngine * AndroidAssetsFileEngineHandler::create(const QString &fileName) const
{
    if (fileName.isEmpty())
        return 0;

    if (!fileName.startsWith(QLatin1String("assets:/")))
        return 0;

    int prefixSize=8;

    QByteArray path;
    if (!fileName.endsWith(QLatin1Char('/'))) {
        path = fileName.toUtf8();
        AAsset *asset = AAssetManager_open(m_assetManager,
                                           path.constData() + prefixSize,
                                           AASSET_MODE_BUFFER);
        if (asset)
            return new AndroidAbstractFileEngine(asset, fileName);
    }

    if (!path.size())
         path = fileName.left(fileName.length() - 1).toUtf8();

    m_assetsCacheMutext.lock();
    QSharedPointer<AndroidAssetDir> *aad = m_assetsCache.object(path);
    m_assetsCacheMutext.unlock();
    if (!aad) {
        AAssetDir *assetDir = AAssetManager_openDir(m_assetManager, path.constData() + prefixSize);
        if (assetDir) {
            if (AAssetDir_getNextFileName(assetDir)) {
                aad = new QSharedPointer<AndroidAssetDir>(new AndroidAssetDir(assetDir));
                m_assetsCacheMutext.lock();
                m_assetsCache.insert(path, aad);
                m_assetsCacheMutext.unlock();
                return new AndroidAbstractFileEngine(*aad, fileName);
            } else {
                AAssetDir_close(assetDir);
            }
        }
    } else {
        return new AndroidAbstractFileEngine(*aad, fileName);
    }
    return 0;
}
Example #24
0
void OS_Android::set_main_loop( MainLoop * p_main_loop ) {

	main_loop=p_main_loop;
	input->set_main_loop(p_main_loop);
#if 0

	print_line("preGS");
	FileAccess *f=memnew( FileAccessAndroid );
	print("made f %p\n",f);
	Error err = f->open("AndroidManifest.xml",FileAccess::READ);
	if (err) {

		print("************NO FILE!!\n");
	} else {
		print("************YES FILE!!\n");
	}
	f->close();
	print_line("end");


	AAssetDir* aad = AAssetManager_openDir(FileAccessAndroid::asset_manager,".");

	if (aad) {

		print_line("DIR OPEN OK");

		const char *fn= AAssetDir_getNextFileName(aad);

		while(fn) {

			print_line("FNAME: "+String(fn));
			fn= AAssetDir_getNextFileName(aad);
		}

		AAssetDir_close(aad);
	} else {

		print_line("DIR NO OPEN");
	}

#endif

}
Example #25
0
static int engine_init_shaders(struct engine* engine) {
    LOGI("from engine_init_shaders \n");
    
    setupGraphics(engine->width, engine->height);
    AAssetDir* assetDir = AAssetManager_openDir(engine->assetManager, "");
    AAssetDir_rewind(assetDir);
    const char* name=NULL;
    const char* vert=NULL, *frag=NULL;
    while ( (name = AAssetDir_getNextFileName(assetDir)) != NULL)
    {
        if (frag == NULL && NULL != strstr(name, gTagFrag)) //if we haven't found the fragment shader and 'name' is the fragment shader, save it.
            frag = name;
        if (vert == NULL && NULL != strstr(name, gTagVert)) //if we haven't found the vertex shader and the 'name' is the vertex shader, save it.
            vert = name;
        if (!vert && !frag) //if we found both files, we're done
            break;
    }
    //open the shader assets
    AAsset* fragAsset = AAssetManager_open(engine->assetManager, frag, AASSET_MODE_BUFFER);
    if (!fragAsset)
    {
        LOGE(" error opening %s\n", fragAsset);
        return;
    }
    AAsset* vertAsset = AAssetManager_open(engine->assetManager, vert, AASSET_MODE_BUFFER);
    if (!vertAsset)
    {
        LOGE(" error opening %s\n", vertAsset);
        return;
    }
    //access the shader asset buffer in preperation for reading
    const char* fragBuff = (const char*)AAsset_getBuffer(fragAsset);
    const char* vertBuff = (const char*)AAsset_getBuffer(vertAsset);
    
    setupGraphics(engine->width, engine->height); //minimaly initialize client graphics state
    LoadShaders(fragBuff, AAsset_getLength(fragAsset), vertBuff, AAsset_getLength(vertAsset)); //load the shaders
    
    AAssetDir_close(assetDir);
}
Example #26
0
int AndroidAssetArchive::listMembers(Common::ArchiveMemberList &member_list) const {
	if (_hasCached) {
		member_list.insert(member_list.end(), _cachedMembers.begin(), _cachedMembers.end());
		return _cachedMembers.size();
	}

	int count = 0;
	AAssetDir *dir = AAssetManager_openDir(_am, "");
	const char *file = AAssetDir_getNextFileName(dir);

	while (file) {
		member_list.push_back(getMember(file));
		++count;
		file = AAssetDir_getNextFileName(dir);
	}
	AAssetDir_close(dir);

	_cachedMembers = Common::ArchiveMemberList(member_list);
	_hasCached = true;

	return count;
}
Example #27
0
void ExportAssets( void )
{
	AAssetManager* mgr;
	mgr = engine.app->activity->assetManager;
	AAssetDir* assetDir = AAssetManager_openDir(engine.app->activity->assetManager, "");
	const char* filename = (const char*)NULL;
	while ((filename = AAssetDir_getNextFileName(assetDir)) != NULL) {
		AAsset* asset = AAssetManager_open(mgr, filename, AASSET_MODE_STREAMING);
		char buf[BUFSIZ];
		int nb_read = 0;
		//LOGI( "Asset:[%s]", filename );
		FILE* out = OpenFile(filename);
		if( out )
		{
			while ((nb_read = AAsset_read(asset, buf, BUFSIZ)) > 0)
				fwrite(buf, nb_read, 1, out);
			fclose(out);
		}
		else
			LOGI( "Failed to open asset copy: %s", filename );
		AAsset_close(asset);
	}
	AAssetDir_close(assetDir);
}
// Read the entire contents of a file and return a pointer/size to it
//-----------------------------------------------------------------------------
CPUTResult CPUTFileSystem::ReadFileContents(const cString &fileName, UINT *pSizeInBytes, void **ppData, bool bAddTerminator, bool bLoadAsBinary)
{
#ifdef CPUT_OS_ANDROID
    // Extract the file and dir
    int length = fileName.length();
    int index = fileName.find_last_of("\\/");
    cString file = fileName.substr(index + 1, (length - 1 - index));
    cString dir  = fileName.substr(0, index);
    
    DEBUG_PRINT("ReadFileContents(%s) : dir [%s], file [%s]", fileName.c_str(), dir.c_str(), file.c_str());
    
    
    // On Android, all files are in the APK and are compressed.
    // We do not have access to the standard file system, so
    // all files need streaming from memory through the android asset manager
    AAssetManager* assetManager = CPUTWindowAndroid::GetAppState()->activity->assetManager;
    
    AAssetDir* assetDir = AAssetManager_openDir(assetManager, dir.c_str());
    if (!assetDir)
        DEBUG_PRINT("Failed to load asset Dir");
    
    const char* assetFileName = NULL;
    while ((assetFileName = AAssetDir_getNextFileName(assetDir)) != NULL) 
    {
        if (strcmp(file.c_str(), assetFileName) == 0)
        {
            // For some reason we need to pass in the fully pathed filename here, rather than the relative filename
            // that we have just been given. This feels like a bug in Android!
            AAsset* asset = AAssetManager_open(assetManager, fileName.c_str()/*assetFileName*/, AASSET_MODE_STREAMING);
            if (!asset)
            {
                DEBUG_PRINT("Asset failed to load for file %s", fileName.c_str());
                return CPUT_ERROR;
            }
            
            *pSizeInBytes = AAsset_getLength(asset);
            
            // allocate buffer
            if (bAddTerminator)
                *ppData = (void*) new char[*pSizeInBytes + 1];
            else
                *ppData = (void*) new char[*pSizeInBytes];
            
            if (!*ppData)
            {
                DEBUG_PRINT("Out of memory loading %s", fileName.c_str());
                return CPUT_ERROR;
            }
                
            // read it all in
            int numBytesRead = AAsset_read(asset, *ppData, *pSizeInBytes);
            if (bAddTerminator)
            {
                ((char *)(*ppData))[numBytesRead++] = '\0';
                *pSizeInBytes++;
            }
            ASSERT( numBytesRead == *pSizeInBytes, _L("File read byte count mismatch.") );
            
            AAsset_close(asset);
            AAssetDir_close(assetDir);    
            return CPUT_SUCCESS;
        }
    }
    AAssetDir_close(assetDir);    
#else
    FILE *pFile = NULL;

    if (bLoadAsBinary) {
#if defined (UNICODE) || defined(_UNICODE)
    	_wfopen_s(&pFile, fileName.c_str(), _L("r"));
#else
    	pFile = fopen(fileName.c_str(), "r");
#endif
    } else {
#if defined (UNICODE) || defined(_UNICODE)
    	_wfopen_s(&pFile, fileName.c_str(), _L("r"));
#else
    	pFile = fopen(fileName.c_str(), "r");
#endif
    }

    if(pFile)
    {
        // get file size
        fseek(pFile, 0, SEEK_END);
        *pSizeInBytes = ftell(pFile);
        fseek (pFile, 0, SEEK_SET);

        // allocate buffer
        *ppData = (void*) new char[*pSizeInBytes];
        ASSERT( *ppData, _L("Out of memory") );

        // read it all in
        UINT numBytesRead = (UINT) fread(*ppData, sizeof(char), *pSizeInBytes, pFile);
        if (bAddTerminator)
        {
            ((char *)(*ppData))[numBytesRead++] = '\0';
            *pSizeInBytes++;
        }
        ASSERT( numBytesRead == *pSizeInBytes, _L("File read byte count mismatch.") );

        // close and return
        fclose(pFile);
        return CPUT_SUCCESS;
    }

#endif    
    // some kind of file error, translate the error code and return it
    return CPUT_ERROR;
//    return TranslateFileError(err);

}
Example #29
0
bool FileSystem::listFiles(const char* dirPath, std::vector<std::string>& files)
{
#ifdef WIN32
    std::string path(FileSystem::getResourcePath());
    if (dirPath && strlen(dirPath) > 0)
    {
        path.append(dirPath);
    }
    path.append("/*");
    // Convert char to wchar
    std::basic_string<TCHAR> wPath;
    wPath.assign(path.begin(), path.end());

    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = FindFirstFile(wPath.c_str(), &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE) 
    {
        return false;
    }
    do
    {
        // Add to the list if this is not a directory
        if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
        {
            // Convert wchar to char
            std::basic_string<TCHAR> wfilename(FindFileData.cFileName);
            std::string filename;
            filename.assign(wfilename.begin(), wfilename.end());
            files.push_back(filename);
        }
    } while (FindNextFile(hFind, &FindFileData) != 0);

    FindClose(hFind);
    return true;
#else
    std::string path(FileSystem::getResourcePath());
    if (dirPath && strlen(dirPath) > 0)
    {
        path.append(dirPath);
    }
    path.append("/.");
    bool result = false;

    struct dirent* dp;
    DIR* dir = opendir(path.c_str());
    if (dir != NULL)
    {
        while ((dp = readdir(dir)) != NULL)
        {
            std::string filepath(path);
            filepath.append("/");
            filepath.append(dp->d_name);

            struct stat buf;
            if (!stat(filepath.c_str(), &buf))
            {
                // Add to the list if this is not a directory
                if (!S_ISDIR(buf.st_mode))
                {
                    files.push_back(dp->d_name);
                }
            }
        }
        closedir(dir);
        result = true;
    }

#ifdef __ANDROID__
    // List the files that are in the android APK at this path
    AAssetDir* assetDir = AAssetManager_openDir(__assetManager, dirPath);
    if (assetDir != NULL)
    {
        AAssetDir_rewind(assetDir);
        const char* file = NULL;
        while ((file = AAssetDir_getNextFileName(assetDir)) != NULL)
        {
            std::string filename(file);
            // Check if this file was already added to the list because it was copied to the SD card.
            if (find(files.begin(), files.end(), filename) == files.end())
            {
                files.push_back(filename);
            }
        }
        AAssetDir_close(assetDir);
        result = true;
    }
#endif

    return result;
#endif
}
Example #30
0
/* Return a list of files for a directory */
static YAP_Bool list_directory(void) {
  YAP_Term tf = YAP_MkAtomTerm(YAP_LookupAtom("[]"));
  long sl = YAP_InitSlot(tf);

  char *buf = (char *)YAP_AtomName(YAP_AtomOfTerm(YAP_ARG1));
#if defined(__MINGW32__) || _MSC_VER
  struct _finddata_t c_file;
  char bs[BUF_SIZE];
  long hFile;

  bs[0] = '\0';
#if HAVE_STRNCPY
  strncpy(bs, buf, BUF_SIZE);
#else
  strcpy(bs, buf);
#endif
#if HAVE_STRNCAT
  strncat(bs, "/*", BUF_SIZE);
#else
  strcat(bs, "/*");
#endif
  if ((hFile = _findfirst(bs, &c_file)) == -1L) {
    return (YAP_Unify(YAP_ARG2, tf));
  }
  YAP_PutInSlot(sl, YAP_MkPairTerm(YAP_MkAtomTerm(YAP_LookupAtom(c_file.name)),
                                   YAP_GetFromSlot(sl)));
  while (_findnext(hFile, &c_file) == 0) {
    YAP_Term ti = YAP_MkAtomTerm(YAP_LookupAtom(c_file.name));
    YAP_PutInSlot(sl, YAP_MkPairTerm(ti, YAP_GetFromSlot(sl)));
  }
  _findclose(hFile);
#else
#if __ANDROID__
  {
    extern  AAssetManager *Yap_assetManager(void);

    const char *dirName = buf + strlen("/assets/");
    AAssetManager *mgr = Yap_assetManager();
    AAssetDir *de;
    const char *dp;

    if ((de = AAssetManager_openDir(mgr, dirName)) == NULL) {
      return (YAP_Unify(YAP_ARG3, YAP_MkIntTerm(errno)));
    }
    while ((dp = AAssetDir_getNextFileName(de))) {
      YAP_Term ti = YAP_MkAtomTerm(YAP_LookupAtom(dp));
      YAP_PutInSlot(sl, YAP_MkPairTerm(ti, YAP_GetFromSlot(sl)));
    }
    AAssetDir_close(de);
  }
#endif
#if HAVE_OPENDIR
  {
    DIR *de;
    struct dirent *dp;

    if ((de = opendir(buf)) == NULL) {
      return (YAP_Unify(YAP_ARG3, YAP_MkIntTerm(errno)));
    }
    while ((dp = readdir(de))) {
      YAP_Term ti = YAP_MkAtomTerm(YAP_LookupAtom(dp->d_name));
      YAP_PutInSlot(sl, YAP_MkPairTerm(ti, YAP_GetFromSlot(sl)));
    }
    closedir(de);
  }
#endif /* HAVE_OPENDIR */
#endif
  tf = YAP_GetFromSlot(sl);
  return YAP_Unify(YAP_ARG2, tf);
}