Exemple #1
0
void UIScrollViewTest::ButtonPressed(BaseObject *obj, void *data, void *callerData)
{
	UIControl *control = dynamic_cast<UIControl*>(obj);
	if (control)
	{
		String msg = Format("Tap on control - %s", control->GetName().c_str());
		testMessageText->SetText(StringToWString(msg));
	}
	else
	{
		testMessageText->SetText(L"");
	}

	if (obj == finishTestBtn)
	{
		testFinished = true;
	}
}
Exemple #2
0
ID3DBlob* PixelShaderCache::CompilePixelShaderFromFile(
	const std::string& filename,
	const std::string& shader )
{
	DWORD shader_flags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
	shader_flags |= D3DCOMPILE_DEBUG;
#endif

	std::wstring wfilename = std::wstring( L"Data//Shaders//" )
						   + StringToWString( filename );
	ID3D10Blob* shader_blob = 0;
	ID3D10Blob* error_blob = 0;
	HR( D3DX11CompileFromFile( wfilename.c_str(), 0, 0, shader.c_str(),
		"ps_4_0", shader_flags, 0, 0, &shader_blob, &error_blob, 0 ) );

	return shader_blob;
}
Exemple #3
0
CLoLChecker::LoginResponse CLoLChecker::CheckLogin(CList::UserData LoginData, std::string strRegion)
{
	LoginResponse Response;

	if (this->captcha.strChallange.size() > 0)
	{
		if (this->HTTP->IsOpen() &&
			this->HTTP->Connect(L"account.leagueoflegends.com", 443))
		{
			for (int i = 0; i < this->captcha.strChallange.size(); i++)
				if (this->captcha.strChallange.at(i) == 0x20) 
					this->captcha.strChallange.at(i) = '+';

			std::string strRequest = 
				std::string("username="******"&password="******"&recaptcha_challenge_field=").append(this->captcha.strChallange)
					.append("&recaptcha_response_field=").append(this->captcha.strAnswer);

			std::string strHeader =
				std::string("X-Requested-With: XMLHttpRequest\r\n")
					.append("Referer: https://account.leagueoflegends.com/pm.html\r\n")
					.append("Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n")
					.append("Cookie: PVPNET_REGION=").append(strRegion);

			if (this->HTTP->SendRequest(L"POST", L"/auth", StringToWString(strHeader), strRequest))
			{
				std::string strResponse = reinterpret_cast<const char*>(this->HTTP->GetResponse().c_str());

				DWORD dwSuccessStart = strResponse.find("\"success\":") + 10,
					dwSuccessEnd = strResponse.find(",", dwSuccessStart);
				
				Response.strSuccess = strResponse.substr(dwSuccessStart, dwSuccessEnd - dwSuccessStart);

				DWORD dwErrorStart = strResponse.find(",\"error\":\"") + 10,
					dwErrorEnd = strResponse.find("\"", dwErrorStart);

				Response.strError = strResponse.substr(dwErrorStart, dwErrorEnd - dwErrorStart);		
			}
		}
	}

	return Response;
}
Exemple #4
0
void FGdbDriver::OpenGeodatabase(std::string conn, Geodatabase** ppGeodatabase)
{
    *ppGeodatabase = NULL;

    std::wstring wconn = StringToWString(conn);

    long hr;

    Geodatabase* pGeoDatabase = new Geodatabase;

    if (S_OK != (hr = ::OpenGeodatabase(wconn, *pGeoDatabase)))
    {
        delete pGeoDatabase;

        return;
    }

    *ppGeodatabase = pGeoDatabase;
}
UIListCell *ComboBox::CellAtIndex(UIList *forList, int32 index)
{
    UIListCell *c = forList->GetReusableCell("Combo cell");
    if (!c) 
    {
        c = new UIListCell(Rect(0, 0, listWidth, size.y), "Combo cell");
    }
    ControlsFactory::CustomizeButton(c, StringToWString(items[index]));
    if (index == selectionIndex) 
    {
        c->SetSelected(true);
    }
    else 
    {
        c->SetSelected(false);
    }

    return c;
}
void OpenGLES30FormatTest::LoadFormat(const String & format)
{
    if(currentFormatName == format) return;
    
    currentFormatName = format;
    
    formatName->SetText(StringToWString(format));
    
    Sprite *sprSource = Sprite::CreateFromSourceFile(Format("~res:/TestData/OpenGLES30FormatTest/%s/source.png", format.c_str()));
    Sprite *sprEncoded = Sprite::CreateFromSourceFile(Format("~res:/TestData/OpenGLES30FormatTest/%s/source_encoded.pvr", format.c_str()));
    Sprite *sprDecoded = Sprite::CreateFromSourceFile(Format("~res:/TestData/OpenGLES30FormatTest/%s/source_decoded.png", format.c_str()));
    
    source->SetSprite(sprSource, 0);
    encodedSource->SetSprite(sprEncoded, 0);
    decodedSource->SetSprite(sprDecoded, 0);
    
    SafeRelease(sprSource);
    SafeRelease(sprEncoded);
    SafeRelease(sprDecoded);
}
Exemple #7
0
bool STDCALL ConfigureCloudSource(XElement *element, bool bCreating)
{
    if (!element)
    {
        AppWarning(TEXT("ConfigureIVASource: NULL element"));
        return false;
    }

    XElement *data = element->GetElement(TEXT("data"));
    if (!data)
        data = element->CreateElement(TEXT("data"));

    ConfigIVAInfo configInfo;
    configInfo.data = data;

    if (OBSDialogBox(hinstMain, MAKEINTRESOURCE(IDD_IVACLOUD), API->GetMainWindow(), IVACloudProc, (LPARAM)&configInfo) == IDOK)
    {
        int nIndex = data->GetInt(TEXT("SelIndex"));

        std::string strPath = g_pCloudData->m_vIPicDesc[nIndex].strFileName;
        std::wstring wstrPath;
        StringToWString(strPath, wstrPath);

        CTSTR lpBitmap = wstrPath.c_str();

        D3DX10_IMAGE_INFO ii;
        if (SUCCEEDED(D3DX10GetImageInfoFromFile(lpBitmap, NULL, &ii, NULL)))
        {
            element->SetInt(TEXT("cx"), ii.Width);
            element->SetInt(TEXT("cy"), ii.Height);
        }
        else
            AppWarning(TEXT("ConfigureBitmapSource: could not get image info for bitmap '%s'"), lpBitmap);

        return true;
    }

    return false;
}
UIListCell *UIFileTree::CellAtIndex(UIList *forList, int32 index)
{
	UIFileTreeCell *c = (UIFileTreeCell *)forList->GetReusableCell("FileTreeCell"); //try to get cell from the reusable cells store
	if(!c)
	{ //if cell of requested type isn't find in the store create new cell
		c = new UIFileTreeCell(Rect(0, 0, 200, 20), "FileTreeCell");
	}
	//fill cell whith data
	//c->serverName = GameServer::Instance()->totalServers[index].name + LocalizedString("'s game");

	UITreeItemInfo * entry = treeHead->EntryByIndex(index);

//	String empty;
//	for (int k = 0; k < entry->GetLevel(); ++k)
//	{
//		empty += ' ';
//		empty += ' ';
//	}
	float32 shiftX = entry->GetLevel() * 10.0f;
	c->SetRect(Rect(shiftX, 0, 200 - shiftX, 16));
	c->SetStateText(UIControl::STATE_NORMAL, StringToWString(entry->GetName()));
	c->GetStateTextControl(UIControl::STATE_NORMAL)->SetAlign(ALIGN_LEFT | ALIGN_VCENTER);
	c->SetItemInfo(entry);
	
	/*
		WTF ??? I can't call RemoveAllEvents here.
	 */
	c->RemoveEvent(UIControl::EVENT_TOUCH_DOWN, Message(this, &UIFileTree::OnDirectoryChange));
	
	if (entry->IsDirectory())
		c->AddEvent(UIControl::EVENT_TOUCH_DOWN, Message(this, &UIFileTree::OnDirectoryChange));
	
	//c->connection = GameServer::Instance()->totalServers[index].connection;
	//c->serverIndex = GameServer::Instance()->totalServers[index].index;

	return c;//returns cell
	//your application don't need to manage cells. UIList do all cells management.
	//you can create cells of your own types derived from the UIListCell
}
Exemple #9
0
OGRDataSource *FGdbDriver::Open( const char* pszFilename, int bUpdate )

{
    // First check if we have to do any work.
    int nLen = strlen(pszFilename);
    if(! ((nLen >= 4 && EQUAL(pszFilename + nLen - 4, ".gdb")) ||
          (nLen >= 5 && EQUAL(pszFilename + nLen - 5, ".gdb/"))) )
        return NULL;

    long hr;


    Geodatabase* pGeoDatabase = new Geodatabase;

    hr = ::OpenGeodatabase(StringToWString(pszFilename), *pGeoDatabase);

    if (FAILED(hr) || pGeoDatabase == NULL)
    {
        delete pGeoDatabase;

        GDBErr(hr, "Failed to open Geodatabase");
        return NULL;
    }

    FGdbDataSource* pDS;

    pDS = new FGdbDataSource();

    if(!pDS->Open( pGeoDatabase, pszFilename, bUpdate ) )
    {
        delete pDS;
        return NULL;
    }
    else
        return pDS;
}
	UIListCell *EditorListDelegate::CellAtIndex(UIList *forList, int32 index)
	{
    	// Try to get cell from the reusable cells store
    	UIListCell *cell = forList->GetReusableCell("Cell");
		if (!cell)
		{
			cell = new UIListCell(Rect(0.0f, 0.0f, cellSize.x, cellSize.y), "Cell");
		}
		else
		{
			cell->SetSize(Vector2(cellSize.x, cellSize.y));
			// Reset reusable cells relative positions - new proper positions will be calculated at UIList::AddCellAtPost() method
			cell->SetPosition(Vector2(0.0f, 0.0f));
		}
	
		cell->RemoveAllControls();
		// Get aggregator control
		UIControl *aggregatorControl = GetCurrentAggregatorControl();
		if (aggregatorControl)
		{
			UIAggregatorControl* control = new UIAggregatorControl();
			control->CopyDataFrom(aggregatorControl);
			// DF-1770 - Reset aggregator's background draw type
			control->GetBackground()->SetDrawType(UIControlBackground::DRAW_ALIGNED);
			cell->AddControl(control);
            SafeRelease(control);
		}
		else
		{			
			cell->SetStateFont(UIControl::STATE_NORMAL, EditorFontManager::Instance()->GetDefaultFont());
			cell->SetStateText(UIControl::STATE_NORMAL, StringToWString(Format("Cell %d",index)));
			cell->SetSelected(true);
		}
   
    	return cell;
	}
std::wstring ParseFile(std::wstring& str)
{
	std::string LowerWorkingDir = lower_string(WStringToString((std::wstring(WorkingDirectory))));

	bool InDirectory = str.find(StringToWString(LowerWorkingDir)) != std::string::npos;
	if (str.find(L"\\") == std::string::npos && str.find(L":") == std::string::npos || InDirectory && str.find(L"resource.h")==std::string::npos)
	{
		if (str.find(L".cpp") != std::string::npos || str.find(L".h") != std::string::npos)
		{
			std::wstring InputFileName;
			std::wstring OutputFileName;
			if (InDirectory)
			{
				/*If we are a file such as D:\\Path\\Project\\Main.cpp
				  We need to strip Main.cpp off the end, and append it to 
				  the temp directory*/
				InputFileName = str;
				size_t IndexOfSlash = str.find_last_of(L"\\");
				if (IndexOfSlash == std::string::npos)
					return str;

				std::wstring FileDirRemoved = str.substr(IndexOfSlash + 1, str.length() - IndexOfSlash + 1);
				str.erase(IndexOfSlash + 1, str.length() - IndexOfSlash + 1);

				std::wstringstream ssTempFile;
				ssTempFile << WorkingDirectory << L"\\Temp\\" << FileDirRemoved;
				OutputFileName = ssTempFile.str();
			} else{
				/*If we are a file such as main.cpp we need to append it to the
				temp directory, and build up the input directory based on our 
				working directory (the project folder)*/
				std::wstringstream ssInFile;
				ssInFile << WorkingDirectory << L"\\" << str;
				InputFileName = ssInFile.str();

				std::wstringstream ssTempFile;
				ssTempFile << WorkingDirectory << L"\\Temp\\" << str;
				OutputFileName = ssTempFile.str();
			}
			std::wifstream InputFile;
			std::wofstream OutputFile;
			SkipNextHook = true;
			InputFile.open(InputFileName.c_str());
			OutputFile.open(OutputFileName.c_str());
			if (InputFile.is_open())
			{
				while (!InputFile.eof())
				{
					//Read Input File, Replace with Xor Contents, Write to output
					wchar_t Buffer[2048];
					InputFile.getline(Buffer, 2048);
					OutputFile << ParseXORContents(std::wstring(Buffer)) << L"\n";
				}
			}
			InputFile.close();
			OutputFile.close();
			SkipNextHook = false;
			return OutputFileName;
		}
		return str;
	}
	return str;
}
OGRDataSource *FGdbDriver::Open( const char* pszFilename, int bUpdate )

{
    // First check if we have to do any work.
    int nLen = strlen(pszFilename);
    if(! ((nLen >= 4 && EQUAL(pszFilename + nLen - 4, ".gdb")) ||
          (nLen >= 5 && EQUAL(pszFilename + nLen - 5, ".gdb/"))) )
        return NULL;

    long hr;

    /* Check that the filename is really a directory, to avoid confusion with */
    /* Garmin MapSource - gdb format which can be a problem when the FileGDB */
    /* driver is loaded as a plugin, and loaded before the GPSBabel driver */
    /* (http://trac.osgeo.org/osgeo4w/ticket/245) */
    VSIStatBuf stat;
    if( CPLStat( pszFilename, &stat ) != 0 || !VSI_ISDIR(stat.st_mode) )
    {
        return NULL;
    }

    CPLMutexHolderD(&hMutex);
    Geodatabase* pGeoDatabase = NULL;

    FGdbDatabaseConnection* pConnection = oMapConnections[pszFilename];
    if( pConnection != NULL )
    {
        pGeoDatabase = pConnection->m_pGeodatabase;
        pConnection->m_nRefCount ++;
        CPLDebug("FileGDB", "ref_count of %s = %d now", pszFilename,
                 pConnection->m_nRefCount);
    }
    else
    {
        pGeoDatabase = new Geodatabase;
        hr = ::OpenGeodatabase(StringToWString(pszFilename), *pGeoDatabase);

        if (FAILED(hr) || pGeoDatabase == NULL)
        {
            delete pGeoDatabase;

            GDBErr(hr, "Failed to open Geodatabase");
            return NULL;
        }

        CPLDebug("FileGDB", "Really opening %s", pszFilename);
        oMapConnections[pszFilename] = new FGdbDatabaseConnection(pGeoDatabase);
    }

    FGdbDataSource* pDS;

    pDS = new FGdbDataSource(this);

    if(!pDS->Open( pGeoDatabase, pszFilename, bUpdate ) )
    {
        delete pDS;
        return NULL;
    }
    else
        return new OGRMutexedDataSource(pDS, TRUE, hMutex);
}
OGRDataSource* FGdbDriver::CreateDataSource( const char * conn,
                                           char **papszOptions)
{
    long hr;
    Geodatabase *pGeodatabase;
    std::wstring wconn = StringToWString(conn);
    int bUpdate = TRUE; // If we're creating, we must be writing.
    VSIStatBuf stat;

    CPLMutexHolderD(&hMutex);

    /* We don't support options yet, so warn if they send us some */
    if ( papszOptions )
    {
        /* TODO: warning, ignoring options */
    }

    /* Only accept names of form "filename.gdb" and */
    /* also .gdb.zip to be able to return FGDB with MapServer OGR output (#4199) */
    const char* pszExt = CPLGetExtension(conn);
    if ( !(EQUAL(pszExt,"gdb") || EQUAL(pszExt, "zip")) )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "FGDB data source name must use 'gdb' extension.\n" );
        return NULL;
    }

    /* Don't try to create on top of something already there */
    if( CPLStat( conn, &stat ) == 0 )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "%s already exists.\n", conn );
        return NULL;
    }

    /* Try to create the geodatabase */
    pGeodatabase = new Geodatabase; // Create on heap so we can store it in the Datasource
    hr = CreateGeodatabase(wconn, *pGeodatabase);

    /* Handle creation errors */
    if ( S_OK != hr )
    {
        const char *errstr = "Error creating geodatabase (%s).\n";
        if ( hr == -2147220653 )
            errstr = "File already exists (%s).\n";
        delete pGeodatabase;
        CPLError( CE_Failure, CPLE_AppDefined, errstr, conn );
        return NULL;
    }

    oMapConnections[conn] = new FGdbDatabaseConnection(pGeodatabase);

    /* Ready to embed the Geodatabase in an OGR Datasource */
    FGdbDataSource* pDS = new FGdbDataSource(this);
    if ( ! pDS->Open(pGeodatabase, conn, bUpdate) )
    {
        delete pDS;
        return NULL;
    }
    else
        return new OGRMutexedDataSource(pDS, TRUE, hMutex);
}
	bool CoreWin32Platform::CreateWin32Window(HINSTANCE hInstance)
	{	
		this->hInstance = hInstance;

		//single instance check
		TCHAR fileName[MAX_PATH];
		GetModuleFileName(NULL, fileName, MAX_PATH);
		fileName[MAX_PATH-1] = 0; //string can be not null-terminated on winXP
		for(int32 i = 0; i < MAX_PATH; ++i)
		{
			if(fileName[i] == L'\\') //symbol \ is not allowed in CreateMutex mutex name
			{
				fileName[i] = ' ';
			}
		}
		hMutex = CreateMutex(NULL, FALSE, fileName);
		if(ERROR_ALREADY_EXISTS == GetLastError())
		{
			return false;
		}

		windowedMode = DisplayMode(800, 600, 16, 0);
		fullscreenMode = DisplayMode(800, 600, 16, 0);
		currentMode = windowedMode;
		isFullscreen = false;

		// create the window, only if we do not use the null device
		LPCWSTR className = L"DavaFrameworkWindowsDevice";

		// Register Class

		WNDCLASSEX wcex;
		wcex.cbSize = sizeof(WNDCLASSEX); 
		wcex.style			= CS_BYTEALIGNCLIENT | CS_HREDRAW | CS_VREDRAW;
		wcex.lpfnWndProc	= (WNDPROC)WndProc;
		wcex.cbClsExtra		= 0;
		wcex.cbWndExtra		= 0;
		wcex.hInstance		= hInstance;
		wcex.hIcon			= 0;
		wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
		wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
		wcex.lpszMenuName	= 0;
		wcex.lpszClassName	= className;
		wcex.hIconSm		= 0;

		RegisterClassEx(&wcex);

		// calculate client size

		RECT clientSize;
		clientSize.top = 0;
		clientSize.left = 0;
		clientSize.right = currentMode.width;
		clientSize.bottom = currentMode.height;

		ULONG style = WINDOWED_STYLE | WS_CLIPCHILDREN;

		// Create the rendering window
		if (isFullscreen)
		{
			style  = WS_VISIBLE | WS_POPUP;
		} // End if Fullscreen


		AdjustWindowRect(&clientSize, style, FALSE);

		int32 realWidth = clientSize.right - clientSize.left;
		int32 realHeight = clientSize.bottom - clientSize.top;

		int32 windowLeft = -10000;//(GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2;
		int32 windowTop = -10000;//(GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2;

		if (isFullscreen)
		{
			windowLeft = 0;
			windowTop = 0;
		}

		// create window
		hWindow = CreateWindow( className, L"", style, windowLeft, windowTop, 
			realWidth, realHeight,	NULL, NULL, hInstance, NULL);

		ShowWindow(hWindow, SW_SHOW);
		UpdateWindow(hWindow);

		// fix ugly ATI driver bugs. Thanks to ariaci (Taken from Irrlight).
		MoveWindow(hWindow, windowLeft, windowTop, realWidth, realHeight, TRUE);
	
#if defined(__DAVAENGINE_DIRECTX9__)
		RenderManager::Create(Core::RENDERER_DIRECTX9);
#elif defined(__DAVAENGINE_OPENGL__)
		RenderManager::Create(Core::RENDERER_OPENGL);
#endif
		RenderManager::Instance()->Create(hInstance, hWindow);

		FrameworkDidLaunched();
		KeyedArchive * options = Core::GetOptions();

		//fullscreenMode = GetCurrentDisplayMode();
		fullscreenMode = GetCurrentDisplayMode();//FindBestMode(fullscreenMode);
		if (options)
		{
			windowedMode.width = options->GetInt32("width");
			windowedMode.height = options->GetInt32("height");
			windowedMode.bpp = options->GetInt32("bpp");
			
			// get values from config in case if they are available
			fullscreenMode.width = options->GetInt32("fullscreen.width", fullscreenMode.width);
			fullscreenMode.height = options->GetInt32("fullscreen.height", fullscreenMode.height);
			fullscreenMode.bpp = windowedMode.bpp;

			fullscreenMode = FindBestMode(fullscreenMode);

			isFullscreen = (0 != options->GetInt32("fullscreen"));	
			String title = options->GetString("title", "[set application title using core options property 'title']");
			WideString titleW = StringToWString(title);
			SetWindowText(hWindow, titleW.c_str());
		}

		Logger::FrameworkDebug("[PlatformWin32] best display fullscreen mode matched: %d x %d x %d refreshRate: %d", fullscreenMode.width, fullscreenMode.height, fullscreenMode.bpp, fullscreenMode.refreshRate);

		currentMode = windowedMode;
		if (isFullscreen)
		{
			currentMode = fullscreenMode;
		}

		clientSize.top = 0;
		clientSize.left = 0;
		clientSize.right = currentMode.width;
		clientSize.bottom = currentMode.height;

		AdjustWindowRect(&clientSize, style, FALSE);

		realWidth = clientSize.right - clientSize.left;
		realHeight = clientSize.bottom - clientSize.top;

		windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2;
		windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2;
		MoveWindow(hWindow, windowLeft, windowTop, realWidth, realHeight, TRUE);
	
        RAWINPUTDEVICE Rid;

        Rid.usUsagePage = 0x01; 
        Rid.usUsage = 0x02; 
        Rid.dwFlags = 0;
        Rid.hwndTarget = 0;

        RegisterRawInputDevices(&Rid, 1, sizeof(Rid));

		RenderManager::Instance()->ChangeDisplayMode(currentMode, isFullscreen);
		RenderManager::Instance()->Init(currentMode.width, currentMode.height);
		UIControlSystem::Instance()->SetInputScreenAreaSize(currentMode.width, currentMode.height);
		Core::Instance()->SetPhysicalScreenSize(currentMode.width, currentMode.height);

		return true;
	}
Exemple #15
0
void TextureConverterCell::SetTexture(const FilePath &texturePath)
{
    textureFormat->SetText(L"");
    textureSize->SetText(L"");
    textureName->SetText(StringToWString(texturePath.GetFilename()));
    
    Texture *texture = Texture::CreateFromFile(texturePath);
    Sprite *s = Sprite::CreateFromTexture(texture, 0, 0, (float32)texture->width, (float32)texture->height);
    preview->SetSprite(s, 0);
    
    if(texturePath.IsEqualToExtension(".png"))
    {
        String pngFormat = Texture::GetPixelFormatString(texture->format);
        
        FilePath pvrPath = FilePath::CreateWithNewExtension(texturePath, ".pvr");
        Texture *pvrTex = Texture::CreateFromFile(pvrPath);
        if(pvrTex)
        {
            PixelFormat format = LibPVRHelper::GetPixelFormat(pvrPath);
            uint32 pvrDataSize = LibPVRHelper::GetDataSize(pvrPath);

            String pvrFormat = Texture::GetPixelFormatString(format);
            textureFormat->SetText(StringToWString(pngFormat + "/" + pvrFormat));
            
            textureSize->SetText(SizeInBytesToWideString(pvrDataSize));
            
            SafeRelease(pvrTex);
        }
        else 
        {
            textureFormat->SetText(StringToWString(pngFormat));
        }
    }
    else if(texturePath.IsEqualToExtension(".pvr"))
    {
        PixelFormat format = LibPVRHelper::GetPixelFormat(texturePath);
        uint32 pvrDataSize = LibPVRHelper::GetDataSize(texturePath);

        String pvrFormat = Texture::GetPixelFormatString(format);
        textureSize->SetText(SizeInBytesToWideString(pvrDataSize));

        FilePath pngPath = FilePath::CreateWithNewExtension(texturePath, ".png");
        Texture *pngTex = Texture::CreateFromFile(pngPath);
        if(pngTex)
        {
            String pngFormat = Texture::GetPixelFormatString(pngTex->format);
            textureFormat->SetText(StringToWString(pngFormat + "/" + pvrFormat));
            
            SafeRelease(pngTex);
        }
        else 
        {
            textureFormat->SetText(StringToWString(pvrFormat));
        }
    }

    textureDimensions->SetText(Format(L"%d x %d", texture->width, texture->height));
    
    SafeRelease(texture);
    SafeRelease(s);
}
Exemple #16
0
OGRDataSource *FGdbDriver::Open( const char* pszFilename, int bUpdate )

{
    // First check if we have to do any work.
    size_t nLen = strlen(pszFilename);
    if(! ((nLen >= 4 && EQUAL(pszFilename + nLen - 4, ".gdb")) ||
          (nLen >= 5 && EQUAL(pszFilename + nLen - 5, ".gdb/"))) )
        return NULL;

    long hr;

    /* Check that the filename is really a directory, to avoid confusion with */
    /* Garmin MapSource - gdb format which can be a problem when the FileGDB */
    /* driver is loaded as a plugin, and loaded before the GPSBabel driver */
    /* (http://trac.osgeo.org/osgeo4w/ticket/245) */
    VSIStatBuf stat;
    if( CPLStat( pszFilename, &stat ) != 0 || !VSI_ISDIR(stat.st_mode) )
    {
        return NULL;
    }

    CPLMutexHolderD(&hMutex);

    FGdbDatabaseConnection* pConnection = oMapConnections[pszFilename];
    if( pConnection != NULL )
    {
        if( pConnection->IsFIDHackInProgress() )
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Cannot open geodatabase at the moment since it is in 'FID hack mode'");
            return NULL;
        }

        pConnection->m_nRefCount ++;
        CPLDebug("FileGDB", "ref_count of %s = %d now", pszFilename,
                 pConnection->m_nRefCount);
    }
    else
    {
        Geodatabase* pGeoDatabase = new Geodatabase;
        hr = ::OpenGeodatabase(StringToWString(pszFilename), *pGeoDatabase);

        if (FAILED(hr))
        {
            delete pGeoDatabase;
            
            if( OGRGetDriverByName("OpenFileGDB") != NULL && bUpdate == FALSE )
            {
                std::wstring fgdb_error_desc_w;
                std::string fgdb_error_desc("Unknown error");
                fgdbError er;
                er = FileGDBAPI::ErrorInfo::GetErrorDescription(static_cast<fgdbError>(hr), fgdb_error_desc_w);
                if ( er == S_OK )
                {
                    fgdb_error_desc = WStringToString(fgdb_error_desc_w);
                }
                CPLDebug("FileGDB", "Cannot open %s with FileGDB driver: %s. Failing silently so OpenFileGDB can be tried",
                         pszFilename,
                         fgdb_error_desc.c_str());
            }
            else
            {
                GDBErr(hr, "Failed to open Geodatabase");
            }
            oMapConnections.erase(pszFilename);
            return NULL;
        }

        CPLDebug("FileGDB", "Really opening %s", pszFilename);
        pConnection = new FGdbDatabaseConnection(pszFilename, pGeoDatabase);
        oMapConnections[pszFilename] = pConnection;
    }

    FGdbDataSource* pDS;

    pDS = new FGdbDataSource(this, pConnection);

    if(!pDS->Open( pszFilename, bUpdate, NULL ) )
    {
        delete pDS;
        return NULL;
    }
    else
    {
        OGRMutexedDataSource* poMutexedDS =
                new OGRMutexedDataSource(pDS, TRUE, hMutex, TRUE);
        if( bUpdate )
            return OGRCreateEmulatedTransactionDataSourceWrapper(poMutexedDS, this, TRUE, FALSE);
        else
            return poMutexedDS;
    }
}
LineConfigDataManager::LineConfigDataManager(void)
{
	mLineConfigData = new vector<LineCategoryItemData*>();

#ifdef _DEMO_DATA
	const int MAX_ITEM = 10;

	for( int i = 0; i < MAX_ITEM; i++)
	{
		CString ID;
		ID.Format(L"%d",i);

		LineCategoryItemData* item = new LineCategoryItemData(wstring(ID.GetBuffer()), 
						L"测试管道",
						GlobalData::KIND_LINE,
						GlobalData::LINE_CATEGORY_SHANGSHUI,
						GlobalData::LINE_SHAPE_CIRCLE,
						L"15",
						L"5",
						GlobalData::LINE_UNIT_CM,
						L"测试数据");

		mLineConfigData->push_back(item);
	}
#else
	CFile archiveFile;

	try
	{
		//read data from file PERSISTENT_FILE
		BOOL result = archiveFile.Open(PERSISTENT_FILE,CFile::modeRead);
		if( !result )
		{
			acutPrintf(L"打开管线类型配置文件失败");
			return;
		}

		//得到文件内容长度
		int length = (ULONGLONG)archiveFile.GetLength()+1;

		//得到文件的窄字符内容
		char* content = new char[length];
		memset(content,0,length);
		archiveFile.Read(content,length);

		//将其转换为宽字符
		string strCnt(content,length);
		wstring wContent = StringToWString( strCnt );

		//查找回车以决定行
		size_t lineFrom = 0;
		size_t linePos = wContent.find_first_of(L"\n",lineFrom);

		while( linePos != wstring::npos )
		{
			//得到一行数据
			wstring& wLine = wContent.substr(lineFrom, linePos-lineFrom);

			//将此行拆分
			size_t columnFrom = 0;
			size_t columnPos = wLine.find_first_of(L"\t",columnFrom);

			LineCategoryItemData* newItem = new LineCategoryItemData();
			newItem->mIndex = 0;

			int indexCol = 0;
			while( columnPos != wstring::npos )
			{
				//得到一个分段
				wstring& rColumn = wLine.substr(columnFrom,columnPos-columnFrom);

				//决定其属性
				if( indexCol == 0 )
					newItem->mID = _wtoi(rColumn.c_str());
				else if( indexCol == 1 )
					newItem->mCategory = rColumn;
				else if( indexCol == 2 )
					newItem->mName = rColumn;
				else if( indexCol == 3 )
					newItem->mKind = rColumn;
				else if( indexCol == 4 )
					newItem->mUnit = rColumn;
				else if( indexCol == 5 )
					newItem->mShape = rColumn;
				else if( indexCol == 6 )
					newItem->mRadius = rColumn;
				else if( indexCol == 7 )
					newItem->mLength = rColumn;
				else if( indexCol == 8 )
					newItem->mWidth = rColumn;
				else if( indexCol == 9 )
					newItem->mWallSize = rColumn;
				else if( indexCol == 10 )
					newItem->mSafeSize = rColumn;
				else if( indexCol == 11 )
					newItem->mCanThrough = rColumn;
				else if( indexCol == 12 )
					newItem->mThroughDirection = rColumn;

				indexCol++;

				//继续下一个column
				columnFrom = columnPos + 1;
				columnPos =  wLine.find_first_of(L'\t',columnFrom);
			}

			if( indexCol == 13 )
			{
				wstring& rColumn = wLine.substr(columnFrom);
				newItem->mComment = rColumn;

				mLineConfigData->push_back(newItem);
			}

			//从下一个字符开始查找另外一行
			lineFrom = linePos + 1;
			linePos = wContent.find_first_of(L"\n",lineFrom + 1);
		}

		//关闭文件
		archiveFile.Close();
	}
	catch(exception& e)
	{
		acutPrintf(L"打开管线类型配置文件异常[%s]",e.what());
	}

#endif
}
Exemple #18
0
OGRErr FGdbDriver::RollbackTransaction(OGRDataSource*& poDSInOut, int& bOutHasReopenedDS)
{
    CPLMutexHolderOptionalLockD(hMutex);

    bOutHasReopenedDS = FALSE;

    OGRMutexedDataSource* poMutexedDS = (OGRMutexedDataSource*)poDSInOut;
    FGdbDataSource* poDS = (FGdbDataSource* )poMutexedDS->GetBaseDataSource();
    FGdbDatabaseConnection* pConnection = poDS->GetConnection();
    if( !pConnection->IsLocked() )
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "No transaction in progress");
        return OGRERR_FAILURE;
    }

    bOutHasReopenedDS = TRUE;

    CPLString osName(poMutexedDS->GetName());
    CPLString osNameOri(osName);
    if( osName[osName.size()-1] == '/' || osName[osName.size()-1] == '\\' )
        osName.resize(osName.size()-1);

    //int bPerLayerCopyingForTransaction = poDS->HasPerLayerCopyingForTransaction();

    pConnection->m_nRefCount ++;
    delete poDSInOut;
    poDSInOut = NULL;
    poMutexedDS = NULL;
    poDS = NULL;

    pConnection->CloseGeodatabase();

    CPLString osEditedName(osName);
    osEditedName += ".ogredited";

    OGRErr eErr = OGRERR_NONE;
    if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE1") || 
        CPLUnlinkTree(osEditedName) != 0 )
    {
        CPLError(CE_Warning, CPLE_AppDefined,
                 "Cannot remove %s. Manual cleanup required", osEditedName.c_str());
        eErr = OGRERR_FAILURE;
    }

    pConnection->m_pGeodatabase = new Geodatabase;
    long hr = ::OpenGeodatabase(StringToWString(osName), *(pConnection->m_pGeodatabase));
    if (EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE2") ||
        FAILED(hr))
    {
        delete pConnection->m_pGeodatabase;
        pConnection->m_pGeodatabase = NULL;
        pConnection->SetLocked(FALSE);
        Release(osName);
        GDBErr(hr, "Failed to re-open Geodatabase. Dataset should be closed");
        return OGRERR_FAILURE;
    }

    FGdbDataSource* pDS = new FGdbDataSource(this, pConnection);
    pDS->Open(osNameOri, TRUE, NULL);
    //pDS->SetPerLayerCopyingForTransaction(bPerLayerCopyingForTransaction);
    poDSInOut = new OGRMutexedDataSource(pDS, TRUE, hMutex, TRUE);

    pConnection->SetLocked(FALSE);

    return eErr;
}
void TextureConverterCell::SetTexture(const String &texturePath)
{
    String textureWorkingPath = texturePath;
    
    String path, filename;
    FileSystem::SplitPath(textureWorkingPath, path, filename);

    textureFormat->SetText(L"");
    textureSize->SetText(L"");
    textureName->SetText(StringToWString(filename));
    
    Texture *texture = Texture::CreateFromFile(textureWorkingPath);
    Sprite *s = Sprite::CreateFromTexture(texture, 0, 0, (float32)texture->width, (float32)texture->height);
    preview->SetSprite(s, 0);
    
    String ext = FileSystem::GetExtension(filename);
    if(".png" == ext)
    {
        String pngFormat = Texture::GetPixelFormatString(texture->format);
        
        String pvrPath = FileSystem::ReplaceExtension(textureWorkingPath, ".pvr");
        Texture *pvrTex = Texture::CreateFromFile(pvrPath);
        if(pvrTex)
        {
            PixelFormat format = LibPVRHelper::GetPixelFormat(pvrPath);
            uint32 pvrDataSize = LibPVRHelper::GetDataLength(pvrPath);

            String pvrFormat = Texture::GetPixelFormatString(format);
            textureFormat->SetText(StringToWString(pngFormat + "/" + pvrFormat));
            
            textureSize->SetText(SizeInBytesToWideString(pvrDataSize));
            
            SafeRelease(pvrTex);
        }
        else 
        {
            textureFormat->SetText(StringToWString(pngFormat));
        }
    }
    else if(".pvr" == ext)
    {
        PixelFormat format = LibPVRHelper::GetPixelFormat(textureWorkingPath);
        uint32 pvrDataSize = LibPVRHelper::GetDataLength(textureWorkingPath);

        String pvrFormat = Texture::GetPixelFormatString(format);
        textureSize->SetText(SizeInBytesToWideString(pvrDataSize));

        String pngPath = FileSystem::ReplaceExtension(textureWorkingPath, ".pvr");
        Texture *pngTex = Texture::CreateFromFile(pngPath);
        if(pngTex)
        {
            String pngFormat = Texture::GetPixelFormatString(pngTex->format);
            textureFormat->SetText(StringToWString(pngFormat + "/" + pvrFormat));
            
            SafeRelease(pngTex);
        }
        else 
        {
            textureFormat->SetText(StringToWString(pvrFormat));
        }
    }

    textureDimensions->SetText(Format(L"%d x %d", texture->width, texture->height));
    
    SafeRelease(texture);
    SafeRelease(s);
}
Exemple #20
0
INT_PTR CALLBACK IVACloudProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_INITDIALOG:
    {
        ConfigIVAInfo *configInfo = (ConfigIVAInfo*)lParam;
        SetWindowLongPtr(hwnd, DWLP_USER, (LONG_PTR)configInfo);
        LocalizeWindow(hwnd);

        HWND hwndPic = GetDlgItem(hwnd, IDC_LISTPIC);
        int i;
        for (i = 0; i < g_pCloudData->m_vIPicDesc.size(); i++)
        {
            std::wstring name;
            StringToWString(g_pCloudData->m_vIPicDesc[i].strTitle, name);

            UINT id = (UINT)SendMessage(hwndPic, LB_ADDSTRING, 0, (LPARAM)name.c_str());
            SendMessage(hwndPic, LB_SETITEMDATA, id, (LPARAM)i);
        }

        CTSTR wszSelPic = configInfo->data->GetString(TEXT("SelCloud"));
        if (wszSelPic != NULL)
        {
            int iNum = SendMessage(hwndPic, LB_FINDSTRINGEXACT, 2, (LPARAM)wszSelPic);
            SendMessage(hwndPic, LB_SETCURSEL, iNum, 0);
            UINT nIndex = (UINT)SendMessage((HWND)hwndPic, LB_GETITEMDATA, iNum, 0);

            std::wstring wstrFilename;
            StringToWString(g_pCloudData->m_vIPicDesc[nIndex].strFileName, wstrFilename);
            DrawImage(hwnd, wstrFilename.c_str(), IDC_PICZONE);
        }

        return 0;
    }

    case WM_COMMAND:
    {
        switch (LOWORD(wParam))
        {
        case IDC_LISTPIC:
        {
            if (HIWORD(wParam) == LBN_SELCHANGE)
            {
                UINT id = (UINT)SendMessage((HWND)lParam, LB_GETCURSEL, 0, 0);
                if (id == LB_ERR)
                    break;
                UINT nIndex = (UINT)SendMessage((HWND)lParam, LB_GETITEMDATA, id, 0);
                std::wstring wstrFilename;
                StringToWString(g_pCloudData->m_vIPicDesc[nIndex].strFileName, wstrFilename);
                DrawImage(hwnd, wstrFilename.c_str(), IDC_PICZONE);
            }
            break;
        }
        case IDTEST:
        {
#if 0
            CImage *img = new CImage;
            HDC dc = GetDC(hwnd);
            img->Load(L"D:\\sss.jpg");
            RECT rect = { 10, 10, 100, 100 };
            img->Draw(GetDC(hwnd), rect);
            delete img;
#endif
            break;
        }
        case IDOK:
        {
            HWND hwndPic = GetDlgItem(hwnd, IDC_LISTPIC);
            UINT id = (UINT)SendMessage((HWND)hwndPic, LB_GETCURSEL, 0, 0);
            if (id == LB_ERR)
            {
                OBSMessageBox(hwnd, L"请选择云图", NULL, 0);
                break;
            }
            UINT nIndex = (UINT)SendMessage((HWND)hwndPic, LB_GETITEMDATA, id, 0);
            ConfigIVAInfo *configInfo = (ConfigIVAInfo*)GetWindowLongPtr(hwnd, DWLP_USER);
            configInfo->data->SetString(TEXT("SelCloud"), g_pCloudData->m_vIPicDesc[nIndex].wstrTitle.c_str());
            configInfo->data->SetInt(TEXT("SelIndex"), nIndex);
        }
        case IDCANCEL:
            EndDialog(hwnd, LOWORD(wParam));
            break;
        }
        break;
    }
    }

    return 0;
}
Exemple #21
0
INT_PTR CALLBACK IVASendiCloudInfoProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_INITDIALOG:
    {
        ConfigIVAInfo *configInfo = (ConfigIVAInfo*)lParam;
        SetWindowLongPtr(hwnd, DWLP_USER, (LONG_PTR)configInfo);
        LocalizeWindow(hwnd);

        ICP_MODE eMode = g_pCloudData->GetICPMode();
        SendMessage(GetDlgItem(hwnd, IDC_MODEIVA), BM_SETCHECK, eMode==ICP_INTERACTIVE_MODE, 0);
        SendMessage(GetDlgItem(hwnd, IDC_MODEEDIT), BM_SETCHECK, eMode == ICP_EDIT_MODE, 0);
        EnableWindow(GetDlgItem(hwnd, IDC_SENDCLOUD), eMode == ICP_INTERACTIVE_MODE);

        return 0;
    }

    case WM_NEWIVACLOUD:
    {
        int nIndex = wParam;
        int nSourceID = lParam;
        HWND hwndLCI = GetDlgItem(hwnd, IDC_LISTCLOUDINFO);

        std::wstring name;
        StringToWString(g_pCloudData->m_vIPicDesc[nIndex].strTitle, name);

        UINT id = (UINT)SendMessage(hwndLCI, LB_ADDSTRING, 0, (LPARAM)name.c_str());
        SendMessage(hwndLCI, LB_SETITEMDATA, id, (LPARAM)nSourceID);
        break;
    }
    case WM_DELETEIVACLOUD:
    {
        int nIndex = wParam;
        int nSourceID = lParam;
        HWND hwndLCI = GetDlgItem(hwnd, IDC_LISTCLOUDINFO);

        std::wstring name;
        StringToWString(g_pCloudData->m_vIPicDesc[nIndex].strTitle, name);
        int iNum = SendMessage(hwndLCI, LB_FINDSTRINGEXACT, -1, (LPARAM)name.c_str());
        SendMessage(hwndLCI, LB_DELETESTRING, iNum, 0);
        break;
    }

    case WM_COMMAND:
    {
        switch (LOWORD(wParam))
        {
        case IDC_SENDCLOUD:
        {
            HWND hwndLCI = GetDlgItem(hwnd, IDC_LISTCLOUDINFO);
            int id = (int)SendMessage((HWND)hwndLCI, LB_GETCURSEL, 0, 0);
            if (id == LB_ERR)
            {
                OBSMessageBox(hwnd, L"请选择一个云信息操作", NULL, 0);
                break;
            }
            int nSourceID = (UINT)SendMessage((HWND)hwndLCI, LB_GETITEMDATA, id, 0);
            if (g_pCloudData->SendCloud(nSourceID) != 0)
                OBSMessageBox(hwnd, L"发送成功", L"成功", 0);
            else
                OBSMessageBox(hwnd, L"发送失败", L"失败", 0);
            break;
        }
        case IDC_MODEIVA:
        case IDC_MODEEDIT:
        {
            int bEditMode = SendMessage(GetDlgItem(hwnd, IDC_MODEEDIT), BM_GETCHECK, 0, 0) == BST_CHECKED;
            int bIVAMode = SendMessage(GetDlgItem(hwnd, IDC_MODEIVA), BM_GETCHECK, 0, 0) == BST_CHECKED;
            ICP_MODE eMode;
            if (bIVAMode != 0)
                eMode = ICP_INTERACTIVE_MODE;
            else
                eMode = ICP_EDIT_MODE;
            EnableWindow(GetDlgItem(hwnd, IDC_SENDCLOUD), bIVAMode);
            g_pCloudData->SetICPMode(eMode);
            break;
        }
        case IDOK:
        {

        }
        case IDCANCEL:
            EndDialog(hwnd, LOWORD(wParam));
            break;
        }
        break;
    }
    }

    return 0;
}
void DeviceInfoTest::DidAppear()
{
    String platform = DeviceInfo::GetPlatformString();
    String version = DeviceInfo::GetVersion();
    String manufacturer = DeviceInfo::GetManufacturer();
    String model = DeviceInfo::GetModel();
    String locale = DeviceInfo::GetLocale();
    String region = DeviceInfo::GetRegion();
    String timezone = DeviceInfo::GetTimeZone();
    String udid = DeviceInfo::GetUDID();
    WideString name = DeviceInfo::GetName();
    List<DeviceInfo::StorageInfo> storages = DeviceInfo::GetStoragesList();
    
    String deviceInfoString;
    deviceInfoString += Format("Platform: %s\n", platform.c_str());
    deviceInfoString += Format("OS version: %s\n", version.c_str());
	deviceInfoString += Format("Manufacturer: %s\n", manufacturer.c_str());
	deviceInfoString += Format("Model: %s\n", model.c_str());
	deviceInfoString += Format("Locale: %s\n", locale.c_str());
	deviceInfoString += Format("Region: %s\n", region.c_str());
	deviceInfoString += Format("Time zone: %s\n", timezone.c_str());
    deviceInfoString += Format("UDID: %s\n", udid.c_str());
    deviceInfoString += Format("Name: %s\n", WStringToString(name).c_str());
    deviceInfoString += Format("ZBufferSize: %d\n", DeviceInfo::GetZBufferSize());
    deviceInfoString += Format("CPU count: %d\n", DeviceInfo::GetCpuCount());
	const eGPUFamily gpu = DeviceInfo::GetGPUFamily();
	if(gpu == GPU_INVALID)
	{
		deviceInfoString += "GPU family: INVALID\n";
	}
	else
	{
		deviceInfoString += Format("GPU family: %s\n", GPUFamilyDescriptor::GetGPUName(gpu).c_str());
	}
    deviceInfoString += Format("Network connection type: %s\n", GetNetworkTypeString().c_str());
    deviceInfoString += Format("Network signal strength: %i%%\n", DeviceInfo::GetNetworkInfo().signalStrength);

    List<DeviceInfo::StorageInfo>::const_iterator iter = storages.begin();
    for (;iter != storages.end(); ++iter)
    {
    	String storageName;

    	switch(iter->type)
    	{
    		case DeviceInfo::STORAGE_TYPE_INTERNAL:
    			storageName = "Internal storage";
    			break;

    		case DeviceInfo::STORAGE_TYPE_PRIMARY_EXTERNAL:
    			storageName = "Primary external storage";
    			break;

    		case DeviceInfo::STORAGE_TYPE_SECONDARY_EXTERNAL:
    			storageName = "Secondary external storage";
    			break;

    		default:
    			storageName = "Unknown storage";
    			break;
    	}

    	String str;
    	if (iter->emulated)
    	{
    		str += "; emulated";
    	}
    	if (iter->readOnly)
    	{
    		str += "; read only";
    	}

    	deviceInfoString += Format("%s: path: %s; capacity: %s; free: %s%s\n", storageName.c_str(),
    			iter->path.GetAbsolutePathname().c_str(), FormatStorageSize(iter->totalSpace).c_str(),
    			FormatStorageSize(iter->freeSpace).c_str(), str.c_str());
    }

    deviceInfoText->SetText(StringToWString(deviceInfoString));
	Logger::Debug("********** Device info **********");
	Logger::Debug(deviceInfoString.c_str());
	Logger::Debug("********** Device info **********");
}
void
ConnectionList::RetrieveProxyCookies( std::string& cookie ) {

	if ( curConnection == NULL ) {
		CosignLog( L"Current connection is not set.  Could not retrieve proxy cookies." );
		return;
	}

	HANDLE	hpf = INVALID_HANDLE_VALUE;
	DWORD	bytesWritten = 0;
	DWORD	err;
   DWORD   success = 0;
   std::string   in;
   std::basic_string <char>::size_type   index;
   std::basic_string <char>::size_type   last;
   std::string crlf = "\r\n";
   std::string line;
   std::string status;

	try { 


	// Create file to hold proxy cookie data
	WCHAR	tempFileName[ 32768 ];
	CosignTrace1( L"proxy Cookies Diretory path = %s", proxyCookiesDirectory.c_str() );
	if ( GetTempFileName( proxyCookiesDirectory.c_str(), L"pck", 0, tempFileName ) == 0 ) {
		err = GetLastError();
		CosignLog( L"GetTempFileName failed with 0x%x", err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	CosignTrace1( L"tempFileName = %s", tempFileName );
	hpf = CreateFile( tempFileName,
		GENERIC_WRITE,
		FILE_SHARE_READ,
		NULL,
		CREATE_ALWAYS,
		FILE_ATTRIBUTE_TEMPORARY,
		NULL );
	if ( hpf == INVALID_HANDLE_VALUE ) {
		err = GetLastError();
		CosignLog( L"CreateFile failed with 0x%x", err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	// Retrieve proxy cookies and store
	Snet*	snet = curConnection;
	std::string out = "RETR " + cookie + " cookies\r\n";
	CosignTrace1( ">> %s", out.c_str() );
	if ( snet->write( out ) == -1 ) {
		CosignLog( "Error writing data to socket \"%s\"\n", out.c_str() );
      goto done;
	}

	while(1) {

		if ( snet->getLine() == -1 ) {
			CosignLog( L"Error reading data from socket" );
         goto done;
		}
		in = snet->data;

		for ( index = 0; index < in.length(); index += 2 ) {
			last = index;
			index = in.find( crlf, index );
			line = in.substr( last, index - last );
			CosignTrace1( "Parsed line << %s", line.c_str() );
			if ( line.length() < 4 ) {
				CosignTrace1( "Error RETR cookies.  Expected more data: %s", in.c_str() );
            goto done;
			}
			status = line.substr( 0, 4 );
			if ( status[ 0 ] != '2' ||
				!isdigit( status[ 1 ] ) ||
				!isdigit( status[ 2 ] ) ) {
				CosignTrace1( "Error RETR cookies.  Server replied: %s", in.c_str() );
            goto done;
			}
			if ( status[ 3 ] == '-' ) {
				// Write cookie to file
				bytesWritten = 0;
				line.replace( 0, 4, "" );
				line += "\r\n";
				const char*	szLine = line.c_str();
				CosignTrace1( "Writing to file: %s", line.c_str() );
				if ( !WriteFile( hpf,
					line.c_str(),
					(DWORD)line.length(),
					&bytesWritten,
					NULL ) ) {

					err = GetLastError();
					CosignLog( L"WriteFile(%s) failed with 0x%x", out.c_str(), err );
					throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
				}
			}
		}
		if ( status.length() >= 4 && status[ 3 ] != '-' ) {
			CosignTrace0( L"Breaking out of RETR loop" );
         success = 1;
			break;
		}
	}

done:
	if ( hpf != INVALID_HANDLE_VALUE ) {
		if ( !CloseHandle( hpf ) ) {
			CosignLog( L"CloseHandle( proxyTmpFile ) failed with 0x%x", GetLastError() );
		}
	}
   if ( !success ) {
      CosignLog( L"Failed to retrieve proxy cookies" );
      return;
   }
	
	std::wstring	wcookie;
	StringToWString( cookie, wcookie );
	index = wcookie.find( L'=' );
	index++;
	if ( index != std::wstring::npos ) {
		wcookie.replace( 0, index, L"" );
	}
	std::wstring	proxyCookiePath = this->proxyCookiesDirectory + wcookie;

	CosignTrace2( L"Copying %s to %s", tempFileName, proxyCookiePath.c_str() );
	if ( !CopyFileEx( tempFileName, proxyCookiePath.c_str(), NULL, NULL, FALSE, 0 ) ) {
		err = GetLastError();
		CosignLog( L"Could not copy file %s to %s: 0x%x", tempFileName, proxyCookiePath.c_str(), err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}
	if ( !DeleteFile( tempFileName ) ) {
		err = GetLastError();
		CosignLog( L"Could not delete temp file %s: 0x%x", tempFileName, err );
		throw( CosignError( err, __LINE__ - 2, __FUNCTION__ ) );
	}

	} catch ( CosignError ce ) {
		if ( hpf != INVALID_HANDLE_VALUE ) {
			if ( !CloseHandle( hpf ) ) {
				CosignLog( L"CloseHandle( proxyTmpFile ) failed with 0x%x", GetLastError() );
			}
		}
		ce.showError();
	}
}
std::wstring ParseXORContents(std::wstring &TempLine)
{
	/*Check if the line has an XOR in it, accounts for multiple
	XORs on the same line*/
	std::size_t StartXOR = 0;
	std::size_t EndQuote = 0;
	std::size_t StartQuote = 0;
	std::size_t EndXOR = 0;
	int StartSearch = 0;
	bool NeedsEnd = false;

	int EraseFixup = 0;
	int InsertFixup = 0;
	std::wstring TotalLine = TempLine;

	if (TempLine.length() <= 0)
		return TempLine;

	//BS Loop SHOULD exit before this
	while (EndQuote<TempLine.length())
	{
		//Do We need beginning of XOR or End
		if (!NeedsEnd)
		{
			//Find Start of XOR Macro
			StartXOR = TempLine.find(L"XOR(", StartSearch);
			if (StartXOR == std::string::npos)
				return TotalLine;

			NeedsEnd = true;

			//Move to End of XOR( character Sequence
			StartXOR += 4;

			//Find Start quote after macro
			StartQuote = TempLine.find(L"\"", StartXOR);
			if (StartQuote == std::string::npos)
				return TempLine;

			StartQuote += 1; //Move to End of Quote
		} else
		{
			EndQuote = TempLine.find(L"\"", StartQuote);
			if (EndQuote == std::string::npos)
				return TempLine;

			bool FoundUnEscapedEnd = false;
			int EscapedFixup = 0;
			while (!FoundUnEscapedEnd)
			{
				if (TempLine.at(EndQuote - 1) != '\\' || (TempLine.at(EndQuote - 2) == '\\' && TempLine.at(EndQuote - 1) == '\\'))
					FoundUnEscapedEnd = true;
				else
				{
					EscapedFixup += 1;
					EndQuote = TempLine.find(L"\"", StartQuote + EscapedFixup);
					if (EndQuote == std::string::npos)
						return TempLine;
				}
			}

			NeedsEnd = false;

			//For Next Iteration ignore previous
			StartSearch = EndQuote;

			std::wstring XORContents = TempLine.substr(StartQuote, EndQuote - StartQuote);

			BOOL Success;
			std::wstring EncryptedSubString = StringToWString(blub(WStringToString(XORContents), Success));
			if (!Success)
				return TempLine;

			EndXOR = TempLine.find(L")", EndQuote);
			if (EndXOR == std::string::npos)
				return TempLine;

			//Move to end of ) and go back to beginning of XOR Macro
			EndXOR += 1;
			StartXOR -= 4;

			//Erase Raw text and replace with encrypted
			TotalLine.erase(StartXOR - EraseFixup + InsertFixup, EndXOR - StartXOR);
			TotalLine.insert(StartXOR - EraseFixup + InsertFixup, EncryptedSubString);

			//Next Time around we need to account for the changed length of the string
			InsertFixup += EncryptedSubString.length();
			EraseFixup += (EndXOR - StartXOR);
		}
	}
	return TempLine;
}
Exemple #25
0
void Logger::ConsoleLog(DAVA::Logger::eLogLevel ll, const char16 *text)
{
    wprintf(L"[%s] %s", StringToWString(GetLogLevelString(ll)).c_str(), text);
}
Exemple #26
0
    /**
     Set the status to "error" and try to retrieve an apropiate error text by evaulating the errno variable.

     NOTE
     Only call this method if you know that there is an error and the "errno" variable
     describes the cause of it.
    */
    void Status::SetToCurrentErrno()
    {
      success=false;
      description=StringToWString(strerror(errno));
    }
Exemple #27
0
template<> LogWrapper& LogWrapper::operator<<(Address Addr)
{
  boost::recursive_mutex::scoped_lock(m_Mutex);
  m_rBuffer += StringToWString(Addr.ToString());
  return *this;
}
UIListCell *MaterialEditor::CellAtIndex(UIList *forList, int32 index)
{
    UIListCell *c = forList->GetReusableCell("Material name cell");
    if (!c) 
    {
        c = new UIListCell(Rect(0, 0, forList->GetRect().dx, 20), "Material name cell");

        float32 boxSize = 16;
        float32 y = (CellHeight(forList, index) - boxSize) / 2;
        float32 x = forList->GetRect().dx - boxSize;
        
        
        //Temporary fix for loading of UI Interface to avoid reloading of texrures to different formates.
        // 1. Reset default format before loading of UI
        // 2. Restore default format after loading of UI from stored settings.
        Texture::SetDefaultFileFormat(NOT_FILE);
        
        Rect r = Rect(x, y, boxSize, boxSize);
        UIControl *sceneFlagBox = new UIControl(r);
        sceneFlagBox->SetName("flagBox");
        sceneFlagBox->GetBackground()->SetDrawType(UIControlBackground::DRAW_SCALE_TO_RECT);
        sceneFlagBox->SetSprite("~res:/Gfx/UI/marker", 1);
        sceneFlagBox->SetInputEnabled(false);
        c->AddControl(sceneFlagBox);
        SafeRelease(sceneFlagBox);
        
        Texture::SetDefaultFileFormat((ImageFileFormat)EditorSettings::Instance()->GetTextureViewFileFormat());
    }

    Material *mat = GetMaterial(index);
    bool found = false;
    if(EDM_ALL == displayMode)
    {
        for (int32 i = 0; i < (int32)workingNodeMaterials.size(); ++i)
        {
            if(workingNodeMaterials[i] == mat)
            {
                found = true;
                break;
            }
        }
    }
    else
    {
        found = true;
    }
    
    ControlsFactory::CustomizeListCell(c, StringToWString(mat->GetName()), false);
    UIControl *sceneFlagBox = c->FindByName("flagBox");
    sceneFlagBox->SetVisible(found, false);
    
    if (index == selectedMaterial) 
    {
        c->SetSelected(true, false);
        lastSelection = c;
    }
    else
    {
        c->SetSelected(false, false);
    }
    
    return c;
}
Exemple #29
0
template<> LogWrapper& LogWrapper::operator<<(std::string Msg)
{
  boost::recursive_mutex::scoped_lock(m_Mutex);
  m_rBuffer += StringToWString(Msg);
  return *this;
}
Exemple #30
0
OGRErr FGdbDriver::CommitTransaction(OGRDataSource*& poDSInOut, int& bOutHasReopenedDS)
{
    CPLMutexHolderOptionalLockD(hMutex);

    bOutHasReopenedDS = FALSE;


    OGRMutexedDataSource* poMutexedDS = (OGRMutexedDataSource*)poDSInOut;
    FGdbDataSource* poDS = (FGdbDataSource* )poMutexedDS->GetBaseDataSource();
    FGdbDatabaseConnection* pConnection = poDS->GetConnection();
    if( !pConnection->IsLocked() )
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "No transaction in progress");
        return OGRERR_FAILURE;
    }

    bOutHasReopenedDS = TRUE;

    CPLString osName(poMutexedDS->GetName());
    CPLString osNameOri(osName);
    if( osName[osName.size()-1] == '/' || osName[osName.size()-1] == '\\' )
        osName.resize(osName.size()-1);

#ifndef WIN32
    int bPerLayerCopyingForTransaction = poDS->HasPerLayerCopyingForTransaction();
#endif

    pConnection->m_nRefCount ++;
    delete poDSInOut;
    poDSInOut = NULL;
    poMutexedDS = NULL;
    poDS = NULL;

    pConnection->CloseGeodatabase();

    CPLString osEditedName(osName);
    osEditedName += ".ogredited";
    
#ifndef WIN32
    if( bPerLayerCopyingForTransaction )
    {
        int bError = FALSE;
        char** papszFiles;
        std::vector<CPLString> aosTmpFilesToClean;
        
        // Check for files present in original copy that are not in edited copy
        // That is to say deleted layers
        papszFiles = VSIReadDir(osName);
        for(char** papszIter = papszFiles; !bError && *papszIter; ++papszIter)
        {
            if( strcmp(*papszIter, ".") == 0 || strcmp(*papszIter, "..") == 0 )
                continue;
            VSIStatBufL sStat;
            if( (*papszIter)[0] == 'a' &&
                VSIStatL( CPLFormFilename(osEditedName, *papszIter, NULL), &sStat ) != 0 )
            {
                if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE1") || 
                    VSIRename( CPLFormFilename(osName, *papszIter, NULL),
                               CPLFormFilename(osName, *papszIter, "tmp") ) != 0 )
                {
                    CPLError(CE_Failure, CPLE_AppDefined, "Cannot rename %s to %s",
                             CPLFormFilename(osName, *papszIter, NULL),
                             CPLFormFilename(osName, *papszIter, "tmp"));
                    bError = TRUE;
                }
                else
                    aosTmpFilesToClean.push_back(CPLFormFilename(osName, *papszIter, "tmp"));
            }
        }
        CSLDestroy(papszFiles);

        // Move modified files from edited directory to main directory
        papszFiles = VSIReadDir(osEditedName);
        for(char** papszIter = papszFiles; !bError && *papszIter; ++papszIter)
        {
            if( strcmp(*papszIter, ".") == 0 || strcmp(*papszIter, "..") == 0 )
                continue;
            struct stat sStat;
            if( lstat( CPLFormFilename(osEditedName, *papszIter, NULL), &sStat ) != 0 )
            {
                CPLError(CE_Failure, CPLE_AppDefined, "Cannot stat %s",
                         CPLFormFilename(osEditedName, *papszIter, NULL));
                bError = TRUE;
            }
            else if( !S_ISLNK(sStat.st_mode) )
            {
                // If there was such a file in original directory, first rename it
                // as a temporary file
                if( lstat( CPLFormFilename(osName, *papszIter, NULL), &sStat ) == 0 )
                {
                    if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE2") || 
                        VSIRename( CPLFormFilename(osName, *papszIter, NULL),
                                   CPLFormFilename(osName, *papszIter, "tmp") ) != 0 )
                    {
                        CPLError(CE_Failure, CPLE_AppDefined, "Cannot rename %s to %s",
                                 CPLFormFilename(osName, *papszIter, NULL),
                                 CPLFormFilename(osName, *papszIter, "tmp"));
                        bError = TRUE;
                    }
                    else
                        aosTmpFilesToClean.push_back(CPLFormFilename(osName, *papszIter, "tmp"));
                }
                if( !bError )
                {
                    if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE3") || 
                        CPLMoveFile( CPLFormFilename(osName, *papszIter, NULL),
                                     CPLFormFilename(osEditedName, *papszIter, NULL) ) != 0 )
                    {
                        CPLError(CE_Failure, CPLE_AppDefined, "Cannot move %s to %s",
                                 CPLFormFilename(osEditedName, *papszIter, NULL),
                                 CPLFormFilename(osName, *papszIter, NULL));
                        bError = TRUE;
                    }
                    else
                        CPLDebug("FileGDB", "Move %s to %s",
                                 CPLFormFilename(osEditedName, *papszIter, NULL),
                                 CPLFormFilename(osName, *papszIter, NULL));
                }
            }
        }
        CSLDestroy(papszFiles);

        if( !bError )
        {
            for(size_t i=0;i<aosTmpFilesToClean.size();i++)
            {
                if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE4") || 
                    VSIUnlink(aosTmpFilesToClean[i]) != 0 )
                {
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "Cannot remove %s. Manual cleanup required", aosTmpFilesToClean[i].c_str());
                }
            }
        }

        if( bError )
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "An error occurred while moving files from %s back to %s. "
                     "Manual cleaning must be done and dataset should be closed",
                     osEditedName.c_str(),
                     osName.c_str());
            pConnection->SetLocked(FALSE);
            Release(osName);
            return OGRERR_FAILURE;
        }
        else if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE5") || 
                 CPLUnlinkTree(osEditedName) != 0 )
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                    "Cannot remove %s. Manual cleanup required", osEditedName.c_str());
        }
    }
    else
#endif
    {
        CPLString osTmpName(osName);
        osTmpName += ".ogrtmp";
        
        /* Install the backup copy as the main database in 3 steps : */
        /* first rename the main directory  in .tmp */
        /* then rename the edited copy under regular name */
        /* and finally dispose the .tmp directory */
        /* That way there's no risk definitely losing data */
        if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE1") || 
            VSIRename(osName, osTmpName) != 0 )
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                    "Cannot rename %s to %s. Edited database during transaction is in %s"
                    "Dataset should be closed",
                    osName.c_str(), osTmpName.c_str(), osEditedName.c_str());
            pConnection->SetLocked(FALSE);
            Release(osName);
            return OGRERR_FAILURE;
        }
        
        if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE2") || 
            VSIRename(osEditedName, osName) != 0 )
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                    "Cannot rename %s to %s. The original geodatabase is in '%s'. "
                    "Dataset should be closed",
                    osEditedName.c_str(), osName.c_str(), osTmpName.c_str());
            pConnection->SetLocked(FALSE);
            Release(osName);
            return OGRERR_FAILURE;
        }

        if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE3") || 
            CPLUnlinkTree(osTmpName) != 0 )
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                    "Cannot remove %s. Manual cleanup required", osTmpName.c_str());
        }
    }

    pConnection->m_pGeodatabase = new Geodatabase;
    long hr = ::OpenGeodatabase(StringToWString(osName), *(pConnection->m_pGeodatabase));
    if( EQUAL(CPLGetConfigOption("FGDB_SIMUL_FAIL", ""), "CASE_REOPEN") || FAILED(hr))
    {
        delete pConnection->m_pGeodatabase;
        pConnection->m_pGeodatabase = NULL;
        pConnection->SetLocked(FALSE);
        Release(osName);
        GDBErr(hr, "Failed to re-open Geodatabase. Dataset should be closed");
        return OGRERR_FAILURE;
    }

    FGdbDataSource* pDS = new FGdbDataSource(this, pConnection);
    pDS->Open(osNameOri, TRUE, NULL);
    //pDS->SetPerLayerCopyingForTransaction(bPerLayerCopyingForTransaction);
    poDSInOut = new OGRMutexedDataSource(pDS, TRUE, hMutex, TRUE);

    pConnection->SetLocked(FALSE);

    return OGRERR_NONE;
}