Esempio n. 1
0
void TestSearchPath::onEnter()
{
    FileUtilsDemo::onEnter();
    CCFileUtils *sharedFileUtils = CCFileUtils::sharedFileUtils();
    
    string ret;
    
    sharedFileUtils->purgeCachedEntries();
    m_defaultSearchPathArray = sharedFileUtils->getSearchPaths();
    vector<string> searchPaths = m_defaultSearchPathArray;
    string writablePath = sharedFileUtils->getWritablePath();
    string fileName = writablePath+"external.txt";
    char szBuf[100] = "Hello Cocos2d-x!";
    FILE* fp = fopen(fileName.c_str(), "wb");
    if (fp)
    {
        fwrite(szBuf, 1, strlen(szBuf), fp);
        fclose(fp);
        CCLog("Writing file to writable path succeed.");
    }
    
    searchPaths.insert(searchPaths.begin(), writablePath);
    searchPaths.insert(searchPaths.begin()+1,   "Misc/searchpath1");
    searchPaths.insert(searchPaths.begin()+2, "Misc/searchpath2");
    sharedFileUtils->setSearchPaths(searchPaths);
    
    m_defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder();
    vector<string> resolutionsOrder = m_defaultResolutionsOrderArray;
    
    resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipad");
    sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder);
    
    for( int i=1; i<3; i++) {
        CCString *filename = CCString::createWithFormat("file%d.txt", i);
        ret = sharedFileUtils->fullPathForFilename(filename->getCString());
        CCLog("%s -> %s", filename->getCString(), ret.c_str());
    }
    
    // Gets external.txt from writable path
    string fullPath = sharedFileUtils->fullPathForFilename("external.txt");
    CCLog("\nexternal file path = %s\n", fullPath.c_str());
    if (fullPath.length() > 0) {
        fp = fopen(fullPath.c_str(), "rb");
        if (fp)
        {
            char szReadBuf[100] = {0};
            fread(szReadBuf, 1, strlen(szBuf), fp);
            CCLog("The content of file from writable path: %s", szReadBuf);
            fclose(fp);
        }
    }
}
Esempio n. 2
0
void initLuaGlobalVariables(const std::string& entry)
{
	//GLOBAL_ROOT_DIR
	CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
	CCLuaStack* pStack = pEngine->getLuaStack();
	CCFileUtils* pFileUtils = CCFileUtils::sharedFileUtils();
	using namespace std;
	string path = pFileUtils->fullPathForFilename(entry.c_str());
	// replace "\" with "/", normalize the path
	int pos = string::npos;
	while ((pos = path.find_first_of("\\")) != string::npos)
	{
		path.replace(pos, 1, "/");
	}

	string script_dir = path.substr(0, path.find_last_of("/"));
	string root_dir = script_dir.substr(0, script_dir.find_last_of("/"));
	CCLOG("RootDir: %s\nScriptDir: %s \n",root_dir.c_str(), script_dir.c_str());

	std::string env = "GLOBAL_ROOT_DIR=\""; env.append(root_dir); env.append("\"");
	pEngine->executeString(env.c_str());

	env = "__LUA_STARTUP_FILE__=\"";env.append(path);env.append("\"");
	pEngine->executeString(env.c_str());

	pStack->addSearchPath(script_dir.c_str());
	pFileUtils->addSearchPath(root_dir.c_str());
	pFileUtils->addSearchPath(script_dir.c_str());

    ScutExt::Init(root_dir+"/");
}
Esempio n. 3
0
void Recipe76::doStep2()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    CCMessageBox("iOS Only", "RecipeBook");
    return;
#else
    std::string zipFilename = "archive.zip";
    
    CCFileUtils* fileUtils = CCFileUtils::sharedFileUtils();
    // フルパスを取得
    std::string fullPath = fileUtils->fullPathForFilename(zipFilename.c_str());
    // 書き込み可能なディレクトリを取得
    std::string path = fileUtils->getWritablePath();
    std::string unzipdPath = path + "unzipd/";
    // zipの展開
    unzipFileToDir(fullPath.c_str(), unzipdPath.c_str());
    
    // 展開したzip中のテキストファイル取得
    std::string txtPath = unzipdPath + "test-step2.txt";
    unsigned long size;
    unsigned char* data = fileUtils->getFileData(txtPath.c_str(), "rb", &size);
    std::string text;
    if (data != NULL) {
        text.assign((const char*)data, size);
        delete [] data;
    }
    CCString *msg = CCString::createWithFormat("read from zip file'%s'", text.c_str());
    CCLabelTTF *label = (CCLabelTTF*)this->getChildByTag(10);
    label->setString(msg->getCString());
#endif
}
Esempio n. 4
0
void Recipe76::doStep1()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    CCMessageBox("iOS Only", "RecipeBook");
    return;
#else
    std::string zipFilename = "archive.zip";
    std::string filename = "test.txt";
    
    CCFileUtils* fileUtils = CCFileUtils::sharedFileUtils();
    // フルパスを取得
    std::string fullPath = fileUtils->fullPathForFilename(zipFilename.c_str());
    // archivezipファイルから test.txtデータをメモリに展開
    unsigned long size;
    unsigned char *data = fileUtils->getFileDataFromZip(fullPath.c_str(), filename.c_str(), &size);
    CCLOG("data:%08X, fullPath:%s", data, fullPath.c_str());
    std::string text;
    if (data!=NULL)
    {
        text.assign((const char*)data, size);
        //「delete [] data;」を忘れると、メモリーリークになるので注意
        delete [] data;
    }
    CCString *msg = CCString::createWithFormat("read from zip file'%s'", text.c_str());
    CCLabelTTF *label = (CCLabelTTF*)this->getChildByTag(10);
    label->setString(msg->getCString());
#endif
}
Esempio n. 5
0
void TestResolutionDirectories::onEnter()
{
    FileUtilsDemo::onEnter();
    CCFileUtils *sharedFileUtils = CCFileUtils::sharedFileUtils();

    string ret;
    
    sharedFileUtils->purgeCachedEntries();
    m_defaultSearchPathArray = sharedFileUtils->getSearchPaths();
    vector<string> searchPaths = m_defaultSearchPathArray;
    searchPaths.insert(searchPaths.begin(),   "Misc");
    sharedFileUtils->setSearchPaths(searchPaths);
    
    m_defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder();
    vector<string> resolutionsOrder = m_defaultResolutionsOrderArray;

    resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipadhd");
    resolutionsOrder.insert(resolutionsOrder.begin()+1, "resources-ipad");
    resolutionsOrder.insert(resolutionsOrder.begin()+2, "resources-widehd");
    resolutionsOrder.insert(resolutionsOrder.begin()+3, "resources-wide");
    resolutionsOrder.insert(resolutionsOrder.begin()+4, "resources-hd");
    resolutionsOrder.insert(resolutionsOrder.begin()+5, "resources-iphone");
    
    sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder);
    
    for( int i=1; i<7; i++) {
        CCString *filename = CCString::createWithFormat("test%d.txt", i);
        ret = sharedFileUtils->fullPathForFilename(filename->getCString());
        CCLog("%s -> %s", filename->getCString(), ret.c_str());
    }
}
Esempio n. 6
0
time_t XFileAssist::GetFileModifyTime(const char szFileName[])
{
    CCFileUtils* pFileUtils = CCFileUtils::sharedFileUtils();
    
	// 注意有个坑: 安卓下面,fullPathForFilename返回的不见得是fullPath
	// 如果根据规则(searchPath + RelativePath + Resolution + FileName),在APK(Zip)包里面找到了这个文件
	// 那么返回的就只是一个相对路径(相对于APK的root)
    std::string strFullPath = pFileUtils->fullPathForFilename(szFileName);

    return XFileHelper::GetFileModifyTime(strFullPath.c_str());
}
/**
 * 从数据包加载任务
 */
bool
MCTaskManager::loadTasks()
{
    bool result = false;
    
    do {
        CCFileUtils *fileUtils = CCFileUtils::sharedFileUtils();
        
        /* 加载任务 */
        taskAccessor_ = new MCTaskAccessor;
        taskAccessor_->loadTasks(fileUtils->fullPathForFilename(kMCTaskPackageFilepath).c_str());
        
        result = true;
    } while (0);
    
    return result;
}
Esempio n. 8
0
void Recipe56::onEnter()
{
    RecipeBase::onEnter();

    CCFileUtils* fileUtils = CCFileUtils::sharedFileUtils();
    std::string fullpath = fileUtils->fullPathForFilename("tweet_sample.json");
    unsigned long size;
    unsigned char* data = fileUtils->getFileData(fullpath.c_str(), "rb", &size);
    if (data != NULL)
    {
        std::string err;
        // パースを実行し、picojson::valueにパース結果を格納する
        picojson::value v;
        picojson::parse(v, data, data+size, &err);
        delete [] data;
        if (err.empty())
        {
            // JSONのルートのobject(std::map<std::string, value>) を取得する
            picojson::object &root = v.get<picojson::object>();
            // 検索結果一覧を取得する
            picojson::array &results = root["results"].get<picojson::array>();
            picojson::array::iterator it;
            for (it = results.begin(); it != results.end(); it++)
            {
                // Tweetのテキストとユーザを取得する
                picojson::object& tweet = it->get<picojson::object>();
                std::string& from_user = tweet["from_user"].get<std::string>();
                std::string& text = tweet["text"].get<std::string>();
                CCLOG("%s:%s", from_user.c_str(), text.c_str());
            }
        }
    }
    
    CCLabelTTF *label = (CCLabelTTF*)this->getChildByTag(10);
    label->setString("tweet データのパース処理が完了しました。\nログとソースを確認してください");
}
Esempio n. 9
0
int CCLuaStack::lua_loadChunksFromZIP(lua_State *L)
{
    if (lua_gettop(L) < 1)
    {
        CCLOG("lua_loadChunksFromZIP() - invalid arguments");
        return 0;
    }

    const char *zipFilename = lua_tostring(L, -1);
    lua_settop(L, 0);
    CCFileUtils *utils = CCFileUtils::sharedFileUtils();
    string zipFilePath = utils->fullPathForFilename(zipFilename);
    zipFilename = NULL;

    CCLuaStack *stack = CCLuaStack::stack(L);

    do
    {
        unsigned long size = 0;
        void *buffer = NULL;
        unsigned char *zipFileData = utils->getFileData(zipFilePath.c_str(), "rb", &size);
        CCZipFile *zip = NULL;

        bool isXXTEA = stack && stack->m_xxteaEnabled && zipFileData;
        for (unsigned int i = 0; isXXTEA && i < stack->m_xxteaSignLen && i < size; ++i)
        {
            isXXTEA = zipFileData[i] == stack->m_xxteaSign[i];
        }

        if (isXXTEA)
        {
            // decrypt XXTEA
            xxtea_long len = 0;
            buffer = xxtea_decrypt(zipFileData + stack->m_xxteaSignLen,
                                   (xxtea_long)size - (xxtea_long)stack->m_xxteaSignLen,
                                   (unsigned char*)stack->m_xxteaKey,
                                   (xxtea_long)stack->m_xxteaKeyLen,
                                   &len);
            delete []zipFileData;
            zipFileData = NULL;
            zip = CCZipFile::createWithBuffer(buffer, len);
        }
        else
        {
            if (zipFileData) {
                zip = CCZipFile::createWithBuffer(zipFileData, size);
            }
        }

        if (zip)
        {
            CCLOG("lua_loadChunksFromZIP() - load zip file: %s%s", zipFilePath.c_str(), isXXTEA ? "*" : "");
            lua_getglobal(L, "package");
            lua_getfield(L, -1, "preload");

            int count = 0;
            string filename = zip->getFirstFilename();
            while (filename.length())
            {
                unsigned long bufferSize = 0;
                unsigned char *buffer = zip->getFileData(filename.c_str(), &bufferSize);
                if (bufferSize)
                {
                    if (lua_loadbuffer(L, (char*)buffer, (int)bufferSize, filename.c_str()) == 0)
                    {
                        lua_setfield(L, -2, filename.c_str());
                        ++count;
                    }
                    delete []buffer;
                }
                filename = zip->getNextFilename();
            }
            CCLOG("lua_loadChunksFromZIP() - loaded chunks count: %d", count);
            lua_pop(L, 2);
            lua_pushboolean(L, 1);
        }
        else
        {
            CCLOG("lua_loadChunksFromZIP() - not found or invalid zip file: %s", zipFilePath.c_str());
            lua_pushboolean(L, 0);
        }

        if (zipFileData)
        {
            delete []zipFileData;
        }
        if (buffer)
        {
            free(buffer);
        }
    } while (0);

    return 1;
}
int CCLuaStack::loadChunksFromZip(lua_State *L)
{
    const char *zipFilename = lua_tostring(L, -1);
    CCFileUtils *utils = CCFileUtils::sharedFileUtils();
    string zipFilePath = utils->fullPathForFilename(zipFilename);
    
    lua_pop(L, 1);
    zipFilename = NULL;
    
    do
    {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
        string tmpFilePath = utils->getWriteablePath().append("cc_load_chunks.tmp");
        unsigned long size = 0;
        unsigned char *buffer = utils->getFileData(zipFilePath.c_str(), "rb", &size);
        bool success = false;
        do
        {
            if (size == 0 || !buffer)
            {
                CCLOG("CCLoadChunksFromZip() - read source file %s failure", zipFilePath.c_str());
                break;
            }
            
            FILE *tmp = fopen(tmpFilePath.c_str(), "wb");
            if (!tmp)
            {
                CCLOG("CCLoadChunksFromZip() - create tmp file %s failure", tmpFilePath.c_str());
                break;
            }
            
            success = fwrite(buffer, 1, size, tmp) > 0;
            fclose(tmp);
            
            if (success)
            {
                zipFilePath = tmpFilePath;
                CCLOG("CCLoadChunksFromZip() - copy zip file to %s ok", tmpFilePath.c_str());
            }
        } while (0);

        if (buffer)
        {
            delete []buffer;
        }

        if (!success)
        {
            lua_pushboolean(L, 0);
            break;
        }
#endif
        
        CCZipFile *zip = CCZipFile::create(zipFilePath.c_str());
        if (zip)
        {
            CCLOG("CCLoadChunksFromZip() - load zip file: %s", zipFilePath.c_str());
            lua_getglobal(L, "package");
            lua_getfield(L, -1, "preload");
            
            CCLOG("CCLoadChunksFromZip() - began");
            int count = 0;
            string filename = zip->getFirstFilename();
            while (filename.length())
            {
                unsigned long bufferSize = 0;
                unsigned char *buffer = zip->getFileData(filename.c_str(), &bufferSize);
                if (bufferSize)
                {
                    luaL_loadbuffer(L, (char*)buffer, bufferSize, filename.c_str());
                    lua_pushcclosure(L, &cc_lua_require, 1);
                    lua_setfield(L, -2, filename.c_str());
                    delete []buffer;
                    ++count;
                    // CCLOG("CCLoadChunksFromZip() - chunk %s", filename.c_str());
                }
                filename = zip->getNextFilename();
            }
            
            CCLOG("CCLoadChunksFromZip() - ended, chunks count %d", count);
            
            lua_pop(L, 2);
            lua_pushboolean(L, 1);
        }
        else
        {
            CCLOG("CCLoadChunksFromZip() - not found zip file: %s", zipFilePath.c_str());
            lua_pushboolean(L, 0);
        }
        
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
        unlink(tmpFilePath.c_str());
#endif
    } while (0);
    
    return 1;
}
Esempio n. 11
0
 int loader_Android(lua_State *L)
 {
     std::string filename(luaL_checkstring(L, 1));
     int pos = filename.rfind(".lua");
     if (pos != std::string::npos)
     {
         filename = filename.substr(0, pos);
     }
     
     pos = filename.find_first_of(".");
     while (pos != std::string::npos)
     {
         filename.replace(pos, 1, "/");
         pos = filename.find_first_of(".");
     }
     filename.append(".lua");
     
     // search file in package.path
     unsigned char* codeBuffer = NULL;
     unsigned long codeBufferSize = 0;
     std::string codePath;
     CCFileUtils* utils = CCFileUtils::sharedFileUtils();
     
     lua_getglobal(L, "package");
     lua_getfield(L, -1, "path");
     std::string searchpath(lua_tostring(L, -1));
     lua_pop(L, 1);
     int begin = 0;
     int next = searchpath.find_first_of(";", 0);
     
     do
     {
         if (next == std::string::npos) next = searchpath.length();
         std::string prefix = searchpath.substr(begin, next);
         if (prefix[0] == '.' && prefix[1] == '/')
         {
             prefix = prefix.substr(2);
         }
         
         pos = prefix.find("?.lua");
         codePath = prefix.substr(0, pos).append(filename);
         codePath = utils->fullPathForFilename(codePath.c_str());
         if (utils->isFileExist(codePath))
         {
             codeBuffer = utils->getFileData(codePath.c_str(), "rb", &codeBufferSize);
             break;
         }
         
         begin = next + 1;
         next = searchpath.find_first_of(";", begin);
     } while (begin < (int)searchpath.length());
     
     if (codeBuffer)
     {
         if (luaL_loadbuffer(L, (char*)codeBuffer, codeBufferSize, codePath.c_str()) != 0)
         {
             luaL_error(L, "error loading module %s from file %s :\n\t%s",
                 lua_tostring(L, 1), filename.c_str(), lua_tostring(L, -1));
         }
         delete []codeBuffer;
     }
     else
     {
         CCLog("can not get file data of %s", filename.c_str());
     }
     
     return 1;
 }