const char *GStringList::RemoveFirst(__int64 *pnLen/* = 0*/)
{
	m_strSerializeDest = "";
	if (pnLen)
	{
		*pnLen = 0;
	}

	GString *pG = (GString *)GList::First();
	if (pG)
	{
		GList::RemoveFirst();
		m_strSerializeDest = (const char *)*pG;
		if (pnLen)
		{
			*pnLen = pG->Length();
		}
		delete pG;
	}
	return m_strSerializeDest;
}
Beispiel #2
0
void GProfile::GetLine(GString &strLine, const char *szBuffer,  __int64 *nIdx,  __int64 dwSize)
{
	strLine.Empty();
	while (*nIdx < dwSize)
	{
		if (szBuffer[*nIdx] == '\n')
			break;
		strLine += szBuffer[*nIdx];
		(*nIdx)++;
	}
	(*nIdx)++;
}
Beispiel #3
0
/** @brief 
	vs外部工具中命令:$(ProjectDir) *.h luaRegister.cpp
 **/
int _tmain ( int argc, _TCHAR* argv[] )
{
	//TLuaRegister luaregister;
	//luaregister.init ( "..\\FiGameDemo\\", "*.h", "..\\FiGameDemo\\luaRegister.cpp" );

    if ( argc < 4 )
    {
        std::cout << "\nArgs is invalid!" ;
        std::cout << "Right args:path ext outfile";
        return 1;
    }
    GString out;
    out.Format ( _T ( "Args:\nPath:%s,Ext:%s,OutFile:%s" ), argv[1], argv[2], argv[3] );
    std::cout << ( out  );
    GString outfile = argv[1];
    outfile += argv[3];

	TLuaRegister luaregister;
	luaregister.init ( argv[1], argv[2], outfile );
    return 0;
}
// 初始化表情数据
bool TextureFontInfo::Init(IGraphic* pGraphic, uint32 idx, GString texname, CFRect pos, GWString des)
{
	ITexture* pTexture = NULL;

	SafeRelease(EmtImg.pTexture);
	if ( texname.c_str() && texname[0] )
	{
		HRESULT hr = pGraphic->CreateTexture( PATH_ALIAS_GUITEX.c_str(), texname.c_str(), &pTexture ); // szTextName
		if(FAILED(hr))
			OutputDebugString(texname.c_str());
		if ( !pTexture )
			return false;
	}

	EmtImg.pTexture	= pTexture;
	EmtImg.texRt	= pos;
	EmtIdx			= idx;
	EmtTexName		= texname;
	EmtDes			= des;
	return true;
}
Beispiel #5
0
void ReadMetadata (GString line, OsuLoadInfo* Info)
{
	auto Command = line.substr(0, line.find_first_of(":")); // Lines are Information:Content
	auto Content = line.substr(line.find_first_of(":") + 1, line.length() - line.find_first_of(":"));

#ifdef VERBOSE_DEBUG
	printf("Command found: %s | Contents: %s\n", Command.c_str(), Content.c_str());
#endif

	Utility::Trim(Content);
	if (Command == "Title")
	{
		Info->OsuSong->SongName = Content;
	}else if (Command == "Artist")
	{
		Info->OsuSong->SongAuthor = Content;
	}else if (Command == "Version")
	{
		Info->Diff->Name = Content;
	}else if (Command == "TitleUnicode")
	{
		if (Content.length() > 1)
			Info->OsuSong->SongName = Content;
	}else if (Command == "ArtistUnicode")
	{
		if (Content.length() > 1)
			Info->OsuSong->SongAuthor = Content;
	}
	else if (Command == "Creator")
	{
		Info->Diff->Author = Content;
	}
}
Beispiel #6
0
void GProfile::ThrowLastError(const char *pzFile)
{
	DWORD dwExp = GetLastError();
#ifdef __WINPHONE
	char pzMsgBuf[256];
	FormatMessage( 
					FORMAT_MESSAGE_FROM_SYSTEM | 
					FORMAT_MESSAGE_IGNORE_INSERTS,
					0,
					dwExp,
					MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
					pzMsgBuf,
					0,
					NULL 
				);

	GString strTemp = pzMsgBuf;
#else
	LPVOID lpMsgBuf;
	FormatMessage( 
					FORMAT_MESSAGE_ALLOCATE_BUFFER | 
					FORMAT_MESSAGE_FROM_SYSTEM | 
					FORMAT_MESSAGE_IGNORE_INSERTS,
					NULL,
					dwExp,
					MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
					(LPTSTR) &lpMsgBuf,
					0,
					NULL 
				);
	GString strTemp = (char *)lpMsgBuf;
	LocalFree( lpMsgBuf );
#endif
	strTemp.TrimRightWS();

	GString strFile;
	strFile.Format("%s - %s", (const char *)strTemp,pzFile);
	GException exp(dwExp,(const char *)strFile);
	throw exp;
}
Beispiel #7
0
void GException::AddErrorDetail(const char* szSystem, int error, ...)
{
	int nSubSystem = 0;
	int nError = error;
	try
	{

		GProfile &ErrorProfile = GetErrorProfile();
		nSubSystem = atoi(ErrorProfile.GetString(szSystem, "SubSystem"));

		GString strKey;
		strKey.Format("%ld", (int)error);
		strKey = ErrorProfile.GetString(szSystem, (const char *)strKey);

		GString strTemp;
		va_list argList;
		va_start(argList, error);
		strTemp.FormatV((const char *)strKey, argList);
		va_end(argList);


		GString strAddedToUserStack;
		strAddedToUserStack.Format("[Error %ld:%ld] %s\n", (int)nSubSystem, (int)nError, (const char *)strTemp);
		_ErrorDetail.AddLast(strAddedToUserStack);

	}
	catch (GException &e)
	{
		_subSystem = e._subSystem;
		_error = e._error;
		_strExceptionReason = e._strExceptionReason;
		return;
	}
}
void SwitchBoard::ViewCurrentState()
{
    gthread_mutex_lock(&m_cs);

    InfoLog(14, "Waiting for:");
    GBTreeIterator it(&m_hshState,2);
    while (it())
    {
        SwitchEntry *pSE = (SwitchEntry *)it++;
        if (pSE)
        {
            GString str;
            str.Format("%s -- %s",(const char *)pSE->strKey, pSE->pzCreateTime);
            InfoLog(15, str);
        }
        else
        {
            // InfoLog(16,"Error - A (null) Switch Entry exists"); // this never happens
        }
    }

    InfoLog(17,"Waiting to Service:");
    GBTreeIterator it2(&m_hshPending,2);
    while (it2())
    {
        SwitchEntry *pSE = (SwitchEntry *)it2++;
        if (pSE)
        {
            GString str;
            str.Format("%s -- %s",(const char *)pSE->strKey, pSE->pzCreateTime);
            InfoLog(18,str);
        }
        else
        {
            // InfoLog(19,"Error - A (null) Switch Entry exists"); // this never happens
        }
    }
    gthread_mutex_unlock(&m_cs);
}
void InitApp() {

#ifdef _DEBUG
	SysUtils::RedirectIOToConsole();
#endif

	GError err;

	// create a new kernel
	gKernel = new GKernel();

	// build path for data
	GString dataPath = SysUtils::AmanithPath();
	if (dataPath.length() > 0)
		dataPath += "data/";

	// load glyphs and triangulate them
	err = LoadAndTesselateGlyphs(dataPath + "cards.ttf", (GReal)1e-7);
	if (err != G_NO_ERROR) {
		perror("Fail to load cards.ttf");
		abort();
	}
	// load cards and animations
	err = LoadCardsAndAnimations(dataPath + "cards.xml");
	if (err != G_NO_ERROR) {
		perror("Fail to load cards.xml");
		abort();
	}
	// load and initialize background
	LoadBackGraoundAndLogo(dataPath + "stars.png");
	// initialize random generator
	GMath::SeedRandom();
	// begin with 7 cards
	gMaxCards = 7;
	gLogicTick = 0.13;
	gBackGroundTime = 0;
	gBackGroundTimeStep = 0.0003;
	gAnimCards.resize(gMaxCards);
}
Beispiel #10
0
extern "C" JNIEXPORT jstring JNICALL Java_com_Server_app_Server_serverInteract  (JNIEnv *env, jobject obj, jint nOperation, jstring jsArg1, jstring jsArg2)
{
	int nRet = 0;
	env->GetJavaVM(&g_javaVM);
	jclass cls = env->GetObjectClass(obj);
	g_activityClass = (jclass) env->NewGlobalRef(cls);
	g_activityObj = env->NewGlobalRef(obj);

	const char *str1 = env->GetStringUTFChars(jsArg1,0);
	const char *str2 = env->GetStringUTFChars(jsArg2,0);




	GString strResultForJava;
	if (nOperation == 1) // in your java app you will set 1 to dispatch here
	{
		GStringList list("&&",str1);  // example arg1 is a list of strings
		GStringIterator it(&list);
		const char *p1 = it++;
		const char *p2 = it++;
		const char *p3 = it++;
		const char *p4 = it++;
		const char *p5 = it++;
		strResultForJava.Format(pzBoundStartupConfig,p1,p2,p3,p4,p5);
	}
	if (nOperation == 2) // do your own thing
	{
		strResultForJava = "nOperation 2 was called with [";
		strResultForJava << str1 << "] and [" << str2 << "]";
	}


	env->ReleaseStringUTFChars(jsArg1, str1);
	env->ReleaseStringUTFChars(jsArg2, str2);
	return env->NewStringUTF(strResultForJava.Buf());
	
}
static void setGlobalParameter(const char* type, const char* arg1, const char* arg2 = NULL) {
	GString line;
	line.append(type);
	line.append(" ");
	line.append(arg1);
	if (arg2 != NULL) {
		line.append(" ");
		line.append(arg2);
	}
	GString name("BepdfApplication");
	globalParams->parseLine(line.getCString(), &name, 0);
}
Beispiel #12
0
bool ReadGeneral (GString line, OsuLoadInfo* Info)
{
	GString Command = line.substr(0, line.find_first_of(" ")); // Lines are Information:<space>Content
	GString Content = line.substr(line.find_first_of(":") + 1);

	Content = Content.substr(Content.find_first_not_of(" "));

	if (Command == "AudioFilename:")
	{
		if (Content == "virtual")
		{
			Info->Diff->IsVirtual = true;
			return true;
		}
		else
		{
#ifdef VERBOSE_DEBUG
			printf("Audio filename found: %s\n", Content.c_str());
#endif
			Utility::Trim(Content);
			Info->OsuSong->SongFilename = Content;
			Info->OsuSong->SongPreviewSource = Content;
		}
	}else if (Command == "Mode:")
	{
		Info->ReadAModeTag = true;
		if (Content != "3") // It's not a osu!mania chart, so we can't use it.
			return false;
	}else if (Command == "SampleSet:")
	{
		Utility::ToLower(Content); Utility::Trim(Content);
		Info->DefaultSampleset = Content;
	}
	else if (Command == "PreviewTime:")
	{
		if (Content != "-1")
		{
			if (Info->OsuSong->PreviewTime == 0)
				Info->OsuSong->PreviewTime = latof(Content) / 1000;
		}																							
	} else if (Command == "SpecialStyle:")
	{
		if (Content == "1")
			Info->Diff->Data->Turntable = true;
	}

	return true;
}
int InitGL(GLvoid) {

	gKernel = new GKernel();
	gImage = (GPixelMap *)gKernel->CreateNew(G_PIXELMAP_CLASSID);

	// build path for data (textures)
	gDataPath = SysUtils::AmanithPath();
	if (gDataPath.length() > 0)
		gDataPath += "data/";

	gRotAngle = 0;
	gRotationVel = (GReal)0.05;
	gStrokeOpacity = 1;
	gFillOpacity = 1;
	gZoomFactor = 2;
	gAnim = G_FALSE;
	gTranslation.Set(256, 256);
	gStrokeCompOp = G_SRC_OVER_OP;
	gFillCompOp = G_SRC_OVER_OP;

	gDrawBoard->SetRenderingQuality(G_HIGH_RENDERING_QUALITY);

	GString s;
	GError err;
	GDynArray<GKeyValue> colKeys;

	// color gradient
	colKeys.clear();
	colKeys.push_back(GKeyValue((GReal)0.00, GVector4((GReal)0.95, (GReal)0.92, (GReal)0.0, (GReal)1.0)));
	colKeys.push_back(GKeyValue((GReal)1.00, GVector4((GReal)0.1, (GReal)0.3, (GReal)0.8, (GReal)0.7)));
	gLinGrad = gDrawBoard->CreateLinearGradient(GPoint2(-60, -44), GPoint2(60, 44), colKeys, G_HERMITE_COLOR_INTERPOLATION, G_PAD_COLOR_RAMP_SPREAD);

	// background
	s = gDataPath + "compground.png";
	err = gImage->Load(StrUtils::ToAscii(s), "expandpalette=true");
	if (err == G_NO_ERROR) {
		gBackGround = gDrawBoard->CreatePattern(gImage, G_LOW_IMAGE_QUALITY, G_REPEAT_TILE);
		gBackGround->SetLogicalWindow(GPoint2(0, 0), GPoint2(512, 512));
	}
	else
		gBackGround = NULL;

	gDrawBoard->SetStrokeWidth(10);
	gDrawBoard->SetStrokeGradient(gLinGrad);
	gDrawBoard->SetFillGradient(gLinGrad);
	gDrawBoard->SetFillPattern(gBackGround);
	DrawTitle();

	return TRUE;
}
Beispiel #14
0
GString RemoveComments(const GString Str)
{
	GString Result;
	int k = 0;
	int AwatingEOL = 0;
	ptrdiff_t len = Str.length() - 1;

	for (ptrdiff_t i = 0; i < len; i++)
	{
		if (AwatingEOL)
		{
			if (Str[i] != '\n')
				continue;
			else
			{
				AwatingEOL = 0;
				continue;
			}
		}
		else
		{
			if (Str[i] == '/' && Str[i + 1] == '/')
			{
				AwatingEOL = true;
				continue;
			}
			else
			{
				Result.push_back(Str.at(i));
				k++;
			}
		}
	}

	Utility::ReplaceAll(Result, "[\\n\\r ]", "");
	return Result;
}
Beispiel #15
0
int GRegExp::burnRight(GString str)
{
	for (unsigned int i = str.Size(); i > 0; i--)
	{
		bool test = false;
		for (unsigned int j = 0; j < _burn.Size(); j++)
		{
			if (str[i] == _burn[j])
				test = true;
		}
		if (!test)
			return i;
	}
	return -1;
}
void	WriteKeyLogger(GString Name)
{
	if (!_map[Name].IsEmpty())
	{
		GFile f(_path + _fileName);
		f.Open(true);
		if (!f.IsOpen())
			return ;
		GDateTime d;
		f.GoToEnd();
		f.Write(d.GetDateTime("%dd/%MM/%yyyy %hh:%mm:%ss - "));
		f.Write(Name.LeftJustified(25) + "- " + _map[Name] + "\r\n");
		_map.EraseKey(Name);
		f.Close();
	}
}
Beispiel #17
0
void JavaInfoLog(int nMsgID, GString &strSrc)
{
    JNIEnv *env;
	if (g_javaVM)
	{
		g_javaVM->AttachCurrentThread(&env, NULL);

		jmethodID messageMe = env->GetMethodID(g_activityClass, "messageMe", "(Ljava/lang/String;)V");
		if (messageMe)
		{
			// Construct a String
			jstring jstr = env->NewStringUTF( strSrc.Buf() );
			env->CallVoidMethod(g_activityObj, messageMe, jstr);
		}
	}
}
void	GXmlWriter::WriteData(const GString &Content)
{
    if (this->_rest.Size() != 0)
    {
        if (this->_container.ExistKey(this->_rest[0]))
        {
            for (unsigned int i = 0; i < this->_space; ++i)
                this->_xml += "\t";
            this->_xml += "<" + this->_rest[0] + ">\n";
            ++this->_space;
            GStringList l = this->_container[this->_rest[0]];
            this->_current.PushFront(this->_rest[0]);
            this->_rest.Erase(0);
            for (int i = l.Size() - 1; i >= 0; --i)
                this->_rest.PushFront(l[i]);
            this->WriteData(Content);
        }
        else
        {
            for (unsigned int i = 0; i < this->_space; ++i)
                this->_xml += "\t";
            if (Content.IsEmpty())
                this->_xml += "</" + this->_rest[0] + ">\n";
            else
                this->_xml += "<" + this->_rest[0] + ">" + Content + "</" + this->_rest[0] + ">\n";
            this->_rest.Erase(0);
        }
    }
    else
    {
        if (this->_current.Size() >= 1)
        {
            --this->_space;
            for (unsigned int i = 0; i < this->_space; ++i)
                this->_xml += "\t";
            this->_xml += "</" + this->_current[0] + ">\n";
            this->_current.Erase(0);
            this->WriteData(Content);
        }
        else
        {
            this->_rest.PushBack(this->_main);
            this->WriteData(Content);
        }
    }

}
// Setup Application Window and initialize Direct3D.
bool FxPlayerTiny::SetupWindow(const GString& name)
{
    hInstance = GetModuleHandle(NULL);
    // Register the window class
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, StaticWindowProc,
                      0L, sizeof(FxPlayerTiny*),
                      hInstance, NULL, NULL, NULL, NULL,
                      pWndClassName, NULL };
    RegisterClassEx(&wc);

    // Create the application's window.
    RECT r = { 100, 100, 100 + Width, 100 + Height };
    ::AdjustWindowRect(&r, WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU, 0);

    HWND hWnd = CreateWindow(pWndClassName, name.ToCStr(),
        WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU,
        r.left, r.top, r.right-r.left, r.bottom - r.top,
        GetDesktopWindow(), NULL, wc.hInstance, (LPVOID) this );


    if (!pD3D)return 0;


    // Set up the structure used to create the D3DDevice    
    ZeroMemory(&PresentParams, sizeof(PresentParams));
    PresentParams.Windowed                = TRUE;
    PresentParams.SwapEffect              = D3DSWAPEFFECT_DISCARD;
    PresentParams.BackBufferFormat        = D3DFMT_UNKNOWN;  
    PresentParams.BackBufferWidth         = Width;
    PresentParams.BackBufferHeight        = Height;
    PresentParams.EnableAutoDepthStencil  = 1;
    PresentParams.AutoDepthStencilFormat  = D3DFMT_D24S8;
    //PresentParams.MultiSampleQuality        = D3DMULTISAMPLE_4_SAMPLES;

    // Create the D3DDevice
    if (FAILED( pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
        D3DCREATE_SOFTWARE_VERTEXPROCESSING,
        &PresentParams, &pDevice ) ))
    {
        return 0;
    }

    return 1;
}
Beispiel #20
0
GString		GHttp::Get(const GString &g)
{
	GString	page(g);
	if (!page.StartWith("http://"))
	{
		page = this->_host + page;
		if (!page.StartWith("http://"))
			page = "http://" + page;
	}
	GString	str = "GET " + page + " HTTP/1.1\r\n";
	str += "Host: " + this->_host + "\r\n";
	if (!this->_proxyUser.IsEmpty())
	{
		str += "Proxy-Authorization: Basic " + GCryptography::GBase64::Encode(this->_proxyUser + ":" + this->_proxyPass) + "\r\n";
		str += "Proxy-Connection : keep-alive\r\n";
	}
	else
	{
		str += "Keep-Alive: 20000\r\n";
		str += "Connection : keep-alive\r\n";
	}
	if (!this->_user.IsEmpty())
		str += "Authorization: Basic " + GCryptography::GBase64::Encode(this->_user + ":" + this->_pass) + "\r\n";
	str += "\r\n";
	this->_socket.Send(str);
	GString rectot;
	while (true)
	{
		GString rec;
		rec = this->_socket.Receive();
		if (rec.Size() < 1024)
		{
			rectot += rec;
			GString	sub = rec.Substr(0, rec.Find("\r\n"));
			GStringList	tab = sub.Split(" ");
			if (tab.Size() > 2)
			{
				//GESTION DES ERREUR
			}
			int	pos = rec.Find("\r\n\r\n");
			if (pos != GString::NotFound)
				;//this->_response = this->_response.Substr(pos + 4);
		}
	}
	return (rectot);
}
Beispiel #21
0
int GRegExp::isPos(GString str1, GString str2)
{
	if (str1.Size() < str2.Size())
		return -1;
	for (unsigned int i = 0; i <= str1.Size() - str2.Size(); i++)
	{
		unsigned int j = 0;
		while (str1[i + j] == str2[j] && j < str2.Size())
			j++;
		if (j == str2.Size())
			return i;
	}
	return -1;
}
GString SP2::GGeneralEventHandler::ReplaceNextPattern(GString in_sSentence, GString in_ReplacingString, GString in_sPattern) const
{
	UINT32 l_iCurrentPosition = 0;
	UINT32 l_iStartPosition = 0;

	bool l_bSuccess = false;

	for(UINT32 i=0; i<in_sSentence.size(); i++)
	{
		if(in_sSentence.at(i) == in_sPattern.at(l_iCurrentPosition))
		{
			if(l_iCurrentPosition == 0)
				l_iStartPosition = i;			
			l_iCurrentPosition++;
			if(l_iCurrentPosition == in_sPattern.size())
			{
				l_bSuccess = true;
				break;
			}
		}
		else
		{
			if(l_iCurrentPosition > 0)
			{
				l_iCurrentPosition = 0;
				i = l_iStartPosition + 1;
			}
		}			
	}
	if(l_bSuccess)
	{
		GString l_Results;
		l_Results += in_sSentence.substr(0,l_iStartPosition);
		l_Results += in_ReplacingString;
		l_Results += in_sSentence.substr(l_iStartPosition+in_sPattern.size(),in_sSentence.size());
		return l_Results;
	}
	return L"";
}
// Android has no popen() implemented, so we will JNI up to the Java bootloader application
// which executes the same as popen() via code in the JVM.
void JavaShellExec(GString &strCommand, GString &strResult)
{
	JNIEnv *env;
	if (g_javaVM)	{
		g_javaVM->AttachCurrentThread(&env, NULL);
		// Get the instance of [public class GAppGlobal], then find the [String ShellExec(String)]
		jclass java_class = env->FindClass(g_JNIFoundationClass);
		if (java_class) {
			jmethodID shellexec = env->GetStaticMethodID(java_class, "ShellExec",	 "(Ljava/lang/String;)Ljava/lang/String;");
			if (shellexec) {
				// Construct a JNI String from the GString - then pass it to the java code in the 3rd arg to CallStaticObjectMethod()
				jstring jstr = env->NewStringUTF(strCommand.Buf());
				jstring strJava = (jstring) env->CallStaticObjectMethod(java_class, shellexec, jstr);
				// put the JNI String into the a GString strResult
				const char *strCpp = env->GetStringUTFChars(strJava, 0);
				strResult = strCpp;
				env->ReleaseStringUTFChars(strJava, strCpp);
			}
		}
	}
}
Beispiel #24
0
	GString GetSha256ForFile(GString Filename)
	{
		SHA256 SHA;
#ifndef WIN32
		std::ifstream InStream(Filename.c_str());
#else
		std::ifstream InStream(Utility::Widen(Filename).c_str());
#endif
		unsigned char tmpbuf[256];

		if (!InStream.is_open())
			return "";

		while (!InStream.eof())
		{
			InStream.read((char*)tmpbuf, 256);
			size_t cnt = InStream.gcount();

			SHA.add(tmpbuf, cnt);
		}

		return GString(SHA.getHash());
	}
Beispiel #25
0
// Inserts a filename, if it already exists, updates it.
// Returns the ID of the filename.
int SongDatabase::InsertFilename(Directory Fn)
{
	int ret;
	int idOut;
	int lmt;
	SC(sqlite3_bind_text(st_FilenameQuery, 1, Fn.c_path(), Fn.path().length(), SQLITE_STATIC));

	if (sqlite3_step(st_FilenameQuery) == SQLITE_ROW)
	{
		idOut = sqlite3_column_int(st_FilenameQuery, 0);
		lmt = sqlite3_column_int(st_FilenameQuery, 1);

		int lastLmt = Utility::GetLMT(Fn.path());

		// Update the last-modified-time of this file, and its hash if it has changed.
		if (lmt != lastLmt)
		{
			GString Hash = Utility::GetSha256ForFile(Fn);
			SC(sqlite3_bind_int(st_UpdateLMT, 1, lastLmt));
			SC(sqlite3_bind_text(st_UpdateLMT, 2, Hash.c_str(), Hash.length(), SQLITE_STATIC));
			SC(sqlite3_bind_text(st_UpdateLMT, 3, Fn.c_path(), Fn.path().length(), SQLITE_STATIC));
			SCS(sqlite3_step(st_UpdateLMT));
			SC(sqlite3_reset(st_UpdateLMT));
		}
	}else
	{
		GString Hash = Utility::GetSha256ForFile(Fn);

		// There's no entry, got to insert it.
		SC(sqlite3_bind_text(st_FilenameInsertQuery, 1, Fn.c_path(), Fn.path().length(), SQLITE_STATIC));
		SC(sqlite3_bind_int(st_FilenameInsertQuery, 2, Utility::GetLMT(Fn.path())));
		SC(sqlite3_bind_text(st_FilenameInsertQuery, 3, Hash.c_str(), Hash.length(), SQLITE_STATIC));
		SCS(sqlite3_step(st_FilenameInsertQuery)); // This should not fail. Otherwise, there are bigger problems to worry about...
		SC(sqlite3_reset(st_FilenameInsertQuery));

		// okay, then return the ID.
		SC(sqlite3_reset(st_FilenameQuery));
		SC(sqlite3_bind_text(st_FilenameQuery, 1, Fn.c_path(), Fn.path().length(), SQLITE_STATIC));
		sqlite3_step(st_FilenameQuery);
		idOut = sqlite3_column_int(st_FilenameQuery, 0);
	}

	SC(sqlite3_reset(st_FilenameQuery));
	return idOut;
}
Beispiel #26
0
	GString SJIStoU8 (GString Line)
	{
#ifdef WIN32
		wchar_t u16s[MAX_STRING_SIZE];
		char mbs[MAX_STRING_SIZE];
		size_t len = MultiByteToWideChar(932, 0, Line.c_str(), Line.length(), u16s, MAX_STRING_SIZE);
		len = WideCharToMultiByte(CP_UTF8, 0, u16s, len, mbs, MAX_STRING_SIZE, NULL, NULL);
		mbs[len] = 0;
		return GString(mbs);
#elif defined(DARWIN)
        // Note: for OS X/Darwin/More than likely most BSD variants, iconv behaves a bit differently.
        iconv_t conv;
        char buf[MAX_STRING_SIZE];
        char* out = buf;
        size_t srcLength = Line.length();
        size_t dstLength = MAX_STRING_SIZE;
        const char* in = Line.c_str();
        
        conv = iconv_open("UTF-8", "SHIFT_JIS");
        iconv(conv, (char**)&in, &srcLength, (char**)&out, &dstLength);
        iconv_close(conv);
        // We have to use buf instead of out here.  For whatever reason, iconv on Darwin doesn't get us what we would expect if we just use out.
        return GString(buf);
#else
        char buf[MAX_STRING_SIZE];
		iconv_t conv;
		char** out = &buf;
		const char* in = Line.c_str();
		size_t BytesLeftSrc = Line.length();
		size_t BytesLeftDst = MAX_STRING_SIZE;

		conv = iconv_open("UTF-8", "SHIFT_JIS");
		bool success = (iconv(conv, (char **)&in, &BytesLeftSrc, out, &BytesLeftDst) > -1);

		iconv_close(conv);
		if (success)
			return GString(*out);
		else
		{
			Log::Printf("Failure converting character sets.");
			return GString();
		}
#endif
	}
Beispiel #27
0
	GArray<GString> GString::Split(GString& str, char const token)
	{
		str.Trim(token);
		GArray<GString> arr;

		size_t lastPos = 0;
		size_t tokenPos = str.Find(token);

		while (tokenPos != -1)
		{
			arr.Add(str.SubString(lastPos, tokenPos - 1));

			lastPos = tokenPos + 1;

			tokenPos = str.Find(token, tokenPos + 1);
		}

		arr.Add(str.SubString(lastPos, str.Size() - 1));

		return arr;
	}	
KPDFLink * KPDFOutputDev::generateLink( LinkAction * a )
// note: this function is called when processing a page, when the MUTEX is already LOCKED
{
    KPDFLink * link = NULL;
    if ( a ) switch ( a->getKind() )
    {
        case actionGoTo:
            {
            LinkGoTo * g = (LinkGoTo *) a;
            // ceate link: no ext file, namedDest, object pointer
            link = new KPDFLinkGoto( QString::null, decodeViewport( g->getNamedDest(), g->getDest() ) );
            }
            break;

        case actionGoToR:
            {
            LinkGoToR * g = (LinkGoToR *) a;
            // copy link file
            const char * fileName = g->getFileName()->getCString();
            // ceate link: fileName, namedDest, object pointer
            link = new KPDFLinkGoto( (QString)fileName, decodeViewport( g->getNamedDest(), g->getDest() ) );
            }
            break;

        case actionLaunch:
            {
            LinkLaunch * e = (LinkLaunch *)a;
            GString * p = e->getParams();
            link = new KPDFLinkExecute( e->getFileName()->getCString(), p ? p->getCString() : 0 );
            }
            break;

        case actionNamed:
            {
            const char * name = ((LinkNamed *)a)->getName()->getCString();
            if ( !strcmp( name, "NextPage" ) )
                link = new KPDFLinkAction( KPDFLinkAction::PageNext );
            else if ( !strcmp( name, "PrevPage" ) )
                link = new KPDFLinkAction( KPDFLinkAction::PagePrev );
            else if ( !strcmp( name, "FirstPage" ) )
                link = new KPDFLinkAction( KPDFLinkAction::PageFirst );
            else if ( !strcmp( name, "LastPage" ) )
                link = new KPDFLinkAction( KPDFLinkAction::PageLast );
            else if ( !strcmp( name, "GoBack" ) )
                link = new KPDFLinkAction( KPDFLinkAction::HistoryBack );
            else if ( !strcmp( name, "GoForward" ) )
                link = new KPDFLinkAction( KPDFLinkAction::HistoryForward );
            else if ( !strcmp( name, "Quit" ) )
                link = new KPDFLinkAction( KPDFLinkAction::Quit );
            else if ( !strcmp( name, "GoToPage" ) )
                link = new KPDFLinkAction( KPDFLinkAction::GoToPage );
            else if ( !strcmp( name, "Find" ) )
                link = new KPDFLinkAction( KPDFLinkAction::Find );
            else if ( !strcmp( name, "Close" ) )
                link = new KPDFLinkAction( KPDFLinkAction::Close );
            else
                kdDebug() << "Unknown named action: '" << name << "'" << endl;
            }
            break;

        case actionURI:
            link = new KPDFLinkBrowse( ((LinkURI *)a)->getURI()->getCString() );
            break;

        case actionMovie:
/*          { TODO this (Movie link)
            m_type = Movie;
            LinkMovie * m = (LinkMovie *) a;
            // copy Movie parameters (2 IDs and a const char *)
            Ref * r = m->getAnnotRef();
            m_refNum = r->num;
            m_refGen = r->gen;
            copyString( m_uri, m->getTitle()->getCString() );
            }
*/          break;

        case actionUnknown:
            kdDebug() << "Unknown link." << endl;
            break;
    }

    // link may be zero at that point
    return link;
}
void CSocketHTTPDataSource::SendHelper(const char *pzRequest, int nRequestLen, GString &destinationStream, const char *pzNamespace)
{
	int fd, numbytes;  
#ifdef _WIN32
	WSADATA wsaData;
	WSAStartup(MAKEWORD( 1, 0 ), &wsaData);
#endif

	int nNamespaceLen = (int)strlen(pzNamespace);


	struct sockaddr_in their_addr; 
	their_addr.sin_family = AF_INET;      
	their_addr.sin_port = htons(m_nPort); 
	their_addr.sin_addr.s_addr = inet_addr (GetServerAddress());
	if (their_addr.sin_addr.s_addr == -1)
	{
		// resolve a DNS server name if inet_addr() came up empty.
		struct hostent *pHE = (struct hostent *)gethostbyname(GetServerAddress());
		if (pHE == 0)
		{ 
			GString strError;
			strError.Format("gethostbyname() failed to resolve[%s]",GetServerAddress());
			throw CSocketError(errno,(const char *)strError);
		}
		memcpy((char *)&(their_addr.sin_addr), pHE->h_addr,pHE->h_length); 
	}
	memset(&(their_addr.sin_zero),0, 8);//zero the rest of the struct


	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) 
	{	
		throw CSocketError(0,"socket");
	}
	CSocketWrap sockfd(fd); 


	// local bind() is not required on WIN32 platform
	struct sockaddr_in localAddr; 
	localAddr.sin_family = AF_INET;
	localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	localAddr.sin_port = htons(0);
	int rc = bind(fd, (struct sockaddr *) &localAddr, sizeof(localAddr));
	if(rc<0) 
	{
		GString strError;
		strError.Format("failed to bind([%s]:%d)",GetServerAddress(),(int)m_nPort);
		throw CSocketError(errno,(const char *)strError);
	}


	if (connect(fd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) 
	{
		GString strError;
		strError.Format("failed to connect([%s]:%d)",GetServerAddress(),(int)m_nPort);
		throw CSocketError(errno,(const char *)strError);
	}

	// 200 bytes in excess
	char *pSendBuf = new char[200 + nRequestLen + nNamespaceLen];
	sprintf(pSendBuf,"POST /XMLServer/UBT.dll?%s HTTP/1.1\r\nUser-Agent: XML_Object_Framework_DataSource\r\nHost: 100.100.100.100\r\nContent-Length:  ",pzNamespace);
	
	GString strTemp;
	strTemp.Format("%d\r\n\r\n%s",(int)nNamespaceLen + nRequestLen,pzNamespace);
	strcat(&pSendBuf[120],(const char *)strTemp);
	int nHeaderLen = (int)strlen(&pSendBuf[120]) + 120;
	strcat(&pSendBuf[120],pzRequest);


	int nTotalMessageLength = nHeaderLen + nRequestLen;


	if ((numbytes=sendto(sockfd, pSendBuf, nTotalMessageLength, 0, 
		 (struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1) 
	{
		delete[] pSendBuf;
		throw CSocketError(sockfd,"sendto");
	}
	delete[] pSendBuf;

	int nCumulativeBytes = 0;
	numbytes = 0;
	do
	{
		if ((numbytes=recv(sockfd, m_winsockBuffer, sizeof(m_winsockBuffer), 0)) == -1) 
		{
			continue;
		}
		destinationStream.write(m_winsockBuffer,numbytes);
		nCumulativeBytes += numbytes;
	}while( numbytes != 0 );
}
Beispiel #30
0
GException::GException(const char* szSystem, int error, ...)
{
	_subSystem = 0;
	_error = error;

	try
	{
		GProfile &ErrorProfile = GetErrorProfile();
		if (ErrorProfile.DoesExist(szSystem, "SubSystem"))
		{
			_subSystem = atoi(ErrorProfile.GetStringOrDefault(szSystem, "SubSystem","0"));
		}
		else
		{
			_subSystem = 0;
		}

		if (_subSystem == 0) // string resources not loaded
		{
			_subSystem = 0;
			_error = error;
			_strExceptionReason = "String resource descriptions not loaded";
			return;
		}

		GString strKey;
		strKey.Format("%ld", (int)error);
		if (ErrorProfile.DoesExist(szSystem, (const char *)strKey))
		{
			strKey = ErrorProfile.GetStringOrDefault(szSystem, (const char *)strKey, "String Resource Not Found");
		}
		else
		{
			strKey = "String Resource Not Found";
		}

		va_list argList;
		va_start(argList, error);
		_strExceptionReason.FormatV((const char *)strKey, argList);
		va_end(argList);
	}
	catch (GException &e)
	{
		_subSystem = e._subSystem;
		_error = e._error;
		_strExceptionReason = e._strExceptionReason;
		return;
	}

#if defined ( _WIN32) && defined (_DEBUG) && !defined(__WINPHONE)

	// this can only be executed if we are NOT out of memory
	char *pMemTest = new char[128000];
	if (pMemTest)
	{
		delete pMemTest;


		_se_translator_function	f;
		f = _set_se_translator(_stack_se_translator);
		try
		{
			int div = 0;
			#ifdef _MyOwnSlash // breakin the law.  Intentionally dividing by 0 to invoke the exception handler.
				int crash = 1\div;
			#else
				int crash = 1/div;
			#endif
			crash++; // so that the local variable is used.
		}
		catch (GCallStack *gcs)// Note: if the library is not built with the /EHa flag == (Enable C++ Exceptions - Yes with Structured Exceptions) THEN this catch is ignored
		{
			_stk.AppendList( gcs->GetStack() );
			_set_se_translator(f);
			delete gcs;
		}
		_set_se_translator(f);
	}


#endif
}