Ejemplo n.º 1
0
   /// <summary>Get file-type from name</summary>
   /// <exception cref="Logic::ArgumentException">Unrecognised file type</exception>
   UtilExport FileType  ParseFileType(const wstring& type)
   {
      // Case insensitive comparison
      if (StrCmpI(type.c_str(), L"Unknown") == 0)
	      return FileType::Unknown;

      else if (StrCmpI(type.c_str(), L"Universe") == 0)
	      return FileType::Universe;

      else if (StrCmpI(type.c_str(), L"Project") == 0)
	      return FileType::Project;

      else if (StrCmpI(type.c_str(), L"Mission") == 0)
	      return FileType::Mission;

      else if (StrCmpI(type.c_str(), L"Language") == 0)
	      return FileType::Language;

      else if (StrCmpI(type.c_str(), L"Script") == 0)
	      return FileType::Script;
         
      // Unrecognised:
      throw ArgumentException(HERE, L"t", VString(L"Unrecognised fileType '%s'", type.c_str()));
   }
Ejemplo n.º 2
0
void Registry::Write(const wstring keyName, const wstring value)
{
   if (!good) return;
   RegSetValueEx(key, keyName.c_str(), 0, REG_SZ, (LPBYTE)value.c_str(), (DWORD)( (value.length()+1)*2 ));
}
Ejemplo n.º 3
0
double ToDouble(const wstring& str) {
  return _wtof(str.c_str());
}
Ejemplo n.º 4
0
wstring OAuthWebRequestSignedSubmit( 
	const HTTPParameters& oauthParameters, 
	const wstring& url,
	const wstring& httpMethod, 
	const HTTPParameters* postParameters
	) 
{
	_TRACE("OAuthWebRequestSignedSubmit(%s)", url.c_str());

	wstring oauthHeader = L"Authorization: OAuth ";
	oauthHeader += OAuthBuildHeader(oauthParameters);
	oauthHeader += L"\r\n";

	_TRACE("%s", oauthHeader.c_str());

	wchar_t host[1024*4] = {};
	wchar_t path[1024*4] = {};

	URL_COMPONENTS components = { sizeof(URL_COMPONENTS) };

	components.lpszHostName = host;
	components.dwHostNameLength = SIZEOF(host);

	components.lpszUrlPath = path;
	components.dwUrlPathLength = SIZEOF(path);

	wstring normalUrl = url;

	BOOL crackUrlOk = InternetCrackUrl(url.c_str(), url.size(), 0, &components);
	_ASSERTE(crackUrlOk);

	wstring result;

	// TODO you'd probably want to InternetOpen only once at app initialization
	HINTERNET hINet = InternetOpen(L"tc2/1.0", 
		INTERNET_OPEN_TYPE_PRECONFIG, 
		NULL, 
		NULL, 
		0 );
	_ASSERTE( hINet != NULL );
	if ( hINet != NULL )
	{
		// TODO add support for HTTPS requests
		HINTERNET hConnection = InternetConnect( 
			hINet, 
			host, 
			components.nPort, 
			NULL, 
			NULL, 
			INTERNET_SERVICE_HTTP, 
			0, 0 );
		_ASSERTE(hConnection != NULL);
		if ( hConnection != NULL)
		{
			HINTERNET hData = HttpOpenRequest( hConnection, 
				httpMethod.c_str(), 
				path, 
				NULL, 
				NULL, 
				NULL, 
				INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_RELOAD, 
				0 );
			_ASSERTE(hData != NULL);
			if ( hData != NULL )
			{
				BOOL oauthHeaderOk = HttpAddRequestHeaders(hData, 
					oauthHeader.c_str(), 
					oauthHeader.size(), 
					0);
				_ASSERTE(oauthHeaderOk);

				// NOTE POST requests are supported, but the MIME type is hardcoded to application/x-www-form-urlencoded (aka. form data)
				// TODO implement support for posting image, raw or other data types
				string postDataUTF8;
				if(Compare(httpMethod, L"POST", false) && postParameters)
				{
					wstring contentHeader = L"Content-Type: application/x-www-form-urlencoded\r\n";
					BOOL contentHeaderOk = HttpAddRequestHeaders(hData, 
						contentHeader.c_str(), 
						contentHeader.size(), 
						0);
					_ASSERTE(contentHeaderOk);

					postDataUTF8 = WideToUTF8(BuildQueryString(*postParameters));
					_TRACE("POST DATA: %S", postDataUTF8.c_str());
				}

				BOOL sendOk = HttpSendRequest( hData, NULL, 0, (LPVOID)(postDataUTF8.size() > 0 ? postDataUTF8.c_str() : NULL), postDataUTF8.size());
				_ASSERTE(sendOk);

				// TODO dynamically allocate return buffer
				BYTE buffer[1024*32] = {};
				DWORD dwRead = 0;
				while( 
					InternetReadFile( hData, buffer, SIZEOF(buffer) - 1, &dwRead ) &&
					dwRead > 0
					)
				{
					buffer[dwRead] = 0;
					result += UTF8ToWide((char*)buffer);
				}

				_TRACE("%s", result.c_str());

				InternetCloseHandle(hData);
			}
			InternetCloseHandle(hConnection);
		}
		InternetCloseHandle(hINet);
	}

	return result;
}
Ejemplo n.º 5
0
static ID3DBlob* CompileShader(const wchar* path, const char* functionName, const char* profile,
                              const D3D_SHADER_MACRO* defines, bool forceOptimization,
                              vector<wstring>& filePaths)
{
    // Make a hash off the expanded shader code
    string shaderCode = GetExpandedShaderCode(path, filePaths);
    wstring cacheName = MakeShaderCacheName(shaderCode, functionName, profile, defines);

    if(FileExists(cacheName.c_str()))
    {
        File cacheFile(cacheName.c_str(), File::OpenRead);

        const uint64 shaderSize = cacheFile.Size();
        vector<uint8> compressedShader;
        compressedShader.resize(shaderSize);
        cacheFile.Read(shaderSize, compressedShader.data());

        ID3DBlob* decompressedShader[1] = { nullptr };
        uint32 indices[1] = { 0 };
        DXCall(D3DDecompressShaders(compressedShader.data(), shaderSize, 1, 0,
                                    indices, 0, decompressedShader, nullptr));

        return decompressedShader[0];
    }

    std::printf("Compiling shader %s %s %s\n", WStringToAnsi(GetFileName(path).c_str()).c_str(),
                profile, MakeDefinesString(defines).c_str());

    // Loop until we succeed, or an exception is thrown
    while(true)
    {
        UINT flags = D3DCOMPILE_WARNINGS_ARE_ERRORS;
        #ifdef _DEBUG
            flags |= D3DCOMPILE_DEBUG;
            if(forceOptimization == false)
                flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
        #endif

        ID3DBlob* compiledShader;
        ID3DBlobPtr errorMessages;
        HRESULT hr = D3DCompileFromFile(path, defines, D3D_COMPILE_STANDARD_FILE_INCLUDE, functionName,
                                        profile, flags, 0, &compiledShader, &errorMessages);

        if(FAILED(hr))
        {
            if(errorMessages)
            {
                wchar message[1024] = { 0 };
                char* blobdata = reinterpret_cast<char*>(errorMessages->GetBufferPointer());

                MultiByteToWideChar(CP_ACP, 0, blobdata, static_cast<int>(errorMessages->GetBufferSize()), message, 1024);
                std::wstring fullMessage = L"Error compiling shader file \"";
                fullMessage += path;
                fullMessage += L"\" - ";
                fullMessage += message;

                // Pop up a message box allowing user to retry compilation
                int retVal = MessageBoxW(nullptr, fullMessage.c_str(), L"Shader Compilation Error", MB_RETRYCANCEL);
                if(retVal != IDRETRY)
                    throw DXException(hr, fullMessage.c_str());

                #if EnableShaderCaching_
                    shaderCode = GetExpandedShaderCode(path);
                    cacheName = MakeShaderCacheName(shaderCode, functionName, profile, defines);
                #endif
            }
            else
            {
                _ASSERT(false);
                throw DXException(hr);
            }
        }
        else
        {
            // Compress the shader
            D3D_SHADER_DATA shaderData;
            shaderData.pBytecode = compiledShader->GetBufferPointer();
            shaderData.BytecodeLength = compiledShader->GetBufferSize();
            ID3DBlobPtr compressedShader;
            DXCall(D3DCompressShaders(1, &shaderData, D3D_COMPRESS_SHADER_KEEP_ALL_PARTS, &compressedShader));

            // Create the cache directory if it doesn't exist
            if(DirectoryExists(baseCacheDir.c_str()) == false)
                Win32Call(CreateDirectory(baseCacheDir.c_str(), nullptr));

            if(DirectoryExists(cacheDir.c_str()) == false)
                Win32Call(CreateDirectory(cacheDir.c_str(), nullptr));

            File cacheFile(cacheName.c_str(), File::OpenWrite);

            // Write the compiled shader to disk
            uint64 shaderSize = compressedShader->GetBufferSize();
            cacheFile.Write(shaderSize, compressedShader->GetBufferPointer());

            return compiledShader;
        }
    }
}
Ejemplo n.º 6
0
bool install_util::IsFolder(const wstring& path) {
  return PathExists(path) && ((GetFileAttributes(path.c_str()) & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
}
bool AudioQualityIdent::Identify(const wstring& fullPathName, int* sampleRate,
                                 int* bitrate, int* channels, int* cutoff,
                                 int64* duration, wstring* format)
{
    assert(mediaInfo_);
    assert(spectrumSource_);
    assert(sampleRate);
    assert(bitrate);
    assert(channels);
    assert(cutoff);
    assert(duration);
    assert(format);
    if (!mediaInfo_ || !spectrumSource_ || !sampleRate || !bitrate ||
        !channels || !cutoff || !duration || !format)
        return false;

    const wchar_t* unknownFormat = L"[Unknown]";
    *sampleRate = 0;
    *bitrate = 0;
    *channels = 0;
    *cutoff = 0;
    *duration = 0;
    *format = unknownFormat;

    ifstream audioFile(fullPathName.c_str(), std::ios::binary);
    audioFile.seekg(0, std::ios::end);
    int fileSize = static_cast<int>(audioFile.tellg());
    if (fileSize > 0) {
        unique_ptr<int8[]> buf(new int8[fileSize]);
        audioFile.seekg(0);
        audioFile.read(reinterpret_cast<char*>(buf.get()), fileSize);

        // Retrieve all necessary media information.
        PassString ps(format);
        if (!mediaInfo_->GetInstantMediaInfo(buf.get(), fileSize, duration,
                                             bitrate, &ps, NULL, sampleRate,
                                             channels, NULL)) {
            // Return true and mark this file as an unrecognized format.
            return true;
        }

        if (format->empty())
            *format = unknownFormat;

        // Retrieve the average cutoff frequency.
        scoped_refptr<MySpectrumReceiver> receiver(
            new MySpectrumReceiver(*sampleRate, cancelFlag_));
        if (!spectrumSource_->Open(fullPathName.c_str())) {
            // Return true and mark this file as an unrecognized format.
            return true;
        }

        // Exclude the first 10 sec data.
        if (!spectrumSource_->Seek(10.0)) {
            // Return true so that we know it is a short-duration music.
            return true;
        }

        int channel = 0;
        IAudioSpectrumReceiver* r = receiver.get();
        spectrumSource_->ExtractSpectrum(&channel, 1, 1024, &r);
        if (cancelFlag_ && cancelFlag_->IsSet())
            return false;

        *cutoff = receiver->GetAverageFreq();
        return true;
    }

    return false;
}
Ejemplo n.º 8
0
DWORD DownloadCurrency(DWORD dwSendTimeOut, wstring& tUrl, string& info)
{
	CUrlCrack url;
	if (!url.Crack(tUrl.c_str()))
		return 1000;

	HINTERNET		m_hInetSession; // 会话句柄
	HINTERNET		m_hInetConnection; // 连接句柄
	HINTERNET		m_hInetFile; //
	
	m_hInetSession = ::InternetOpen(L"Moneyhub4.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
	{
		return 3000;
	}
	
	DWORD dwTimeOut = 60000;//初始化为5s
	//DWORD dwSendTimeOut = 5000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwSendTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwSendTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	if (m_hInetConnection == NULL)
	{
		InternetCloseHandle(m_hInetSession);

		return 3001;
	}

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;
	
	USES_CONVERSION;
	m_hInetFile = HttpOpenRequestW(m_hInetConnection, _T("GET"), url.GetPath(), NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION, 0);
	if (m_hInetFile == NULL)
	{
		InternetCloseHandle(m_hInetConnection);
		InternetCloseHandle(m_hInetSession);
		return 3002;
	}	

	BOOL bSend = ::HttpSendRequestW(m_hInetFile, NULL, 0, NULL, 0);
	if (!bSend)
	{
		int Error = GetLastError();
		InternetCloseHandle(m_hInetConnection);
		InternetCloseHandle(m_hInetFile);
		InternetCloseHandle(m_hInetSession);
		return Error;
	}
	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		InternetCloseHandle(m_hInetConnection);
		InternetCloseHandle(m_hInetFile);
		InternetCloseHandle(m_hInetSession);
		return 3004;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_PARTIAL_CONTENT && nStatusCode != HTTP_STATUS_OK)
		{
			InternetCloseHandle(m_hInetConnection);
			InternetCloseHandle(m_hInetFile);
			InternetCloseHandle(m_hInetSession);
			return 3005;
		}
	}

	DWORD dwBytesRead = 0;
	char szReadBuf[1024];
	DWORD dwBytesToRead = sizeof(szReadBuf);
	bool sucess = true;

	do
	{
		memset(szReadBuf, 0 , 1024);
		if (!::InternetReadFile(m_hInetFile, szReadBuf, dwBytesToRead, &dwBytesRead))
		{
			sucess = false;
			break;
		}
		else if (dwBytesRead)
		{
			info += szReadBuf;
		}
	}while (dwBytesRead);

	InternetCloseHandle(m_hInetConnection);
	InternetCloseHandle(m_hInetFile);
	InternetCloseHandle(m_hInetSession);
	if(sucess != true)
		return 3007;
	return 0;
}
void ExceptionHelper::HandleNonFatalException(Logger* logger, ErrorHandler* errorHandler, wstring message)
{
    logger->LogFormatted(LogLevels::Error, L"%ls\n%ls", message.c_str(), GetCurrentExceptionMessage().c_str());
    errorHandler->ShowError(message);
}
void ExceptionHelper::HandleNonFatalException(Logger* logger, ErrorHandler* errorHandler, wstring message, const SelectedTextTranslateBaseException& exception)
{
    logger->LogFormatted(LogLevels::Error, L"%ls\n%ls", message.c_str(), exception.GetFullErrorMessage().c_str());
    errorHandler->ShowError(exception.GetDisplayErrorMessage());
}
Ejemplo n.º 11
0
BSTR COMStringUtils::ConvertWString(const wstring &str)
{
	_bstr_t b(str.c_str());
	return b.copy();
}
Ejemplo n.º 12
0
void Font::LoadFontPageSettings( FontPageSettings &cfg, IniFile &ini, const RString &sTexturePath, const RString &sPageName, RString sChars )
{
	cfg.m_sTexturePath = sTexturePath;

	/* If we have any characters to map, add them. */
	for( unsigned n=0; n<sChars.size(); n++ )
	{
		char c = sChars[n];
		cfg.CharToGlyphNo[c] = n;
	}
	int iNumFramesWide, iNumFramesHigh;
	RageTexture::GetFrameDimensionsFromFileName( sTexturePath, &iNumFramesWide, &iNumFramesHigh );
	int iNumFrames = iNumFramesWide * iNumFramesHigh;
	
	ini.RenameKey("Char Widths", "main");

//	LOG->Trace("Loading font page '%s' settings from page name '%s'",
//		TexturePath.c_str(), sPageName.c_str());
	
	ini.GetValue( sPageName, "DrawExtraPixelsLeft", cfg.m_iDrawExtraPixelsLeft );
	ini.GetValue( sPageName, "DrawExtraPixelsRight", cfg.m_iDrawExtraPixelsRight );
	ini.GetValue( sPageName, "AddToAllWidths", cfg.m_iAddToAllWidths );
	ini.GetValue( sPageName, "ScaleAllWidthsBy", cfg.m_fScaleAllWidthsBy );
	ini.GetValue( sPageName, "LineSpacing", cfg.m_iLineSpacing );
	ini.GetValue( sPageName, "Top", cfg.m_iTop );
	ini.GetValue( sPageName, "Baseline", cfg.m_iBaseline );
	ini.GetValue( sPageName, "DefaultWidth", cfg.m_iDefaultWidth );
	ini.GetValue( sPageName, "AdvanceExtraPixels", cfg.m_iAdvanceExtraPixels );
	ini.GetValue( sPageName, "TextureHints", cfg.m_sTextureHints );

	/* Iterate over all keys. */
	const XNode* pNode = ini.GetChild( sPageName );
	if( pNode )
	{
		FOREACH_CONST_Attr( pNode, pAttr )
		{
			RString sName = pAttr->first;
			const XNodeValue *pValue = pAttr->second;

			sName.MakeUpper();

			/* If val is an integer, it's a width, eg. "10=27". */
			if( IsAnInt(sName) )
			{
				cfg.m_mapGlyphWidths[atoi(sName)] = pValue->GetValue<int>();
				continue;
			}

			/* "map codepoint=frame" maps a char to a frame. */
			if( sName.substr(0, 4) == "MAP " )
			{
				/*
				 * map CODEPOINT=frame. CODEPOINT can be
				 * 1. U+hexval
				 * 2. an alias ("oq")
				 * 3. a character in quotes ("X")
				 *
				 * map 1=2 is the same as
				 * range unicode #1-1=2
				 */
				RString sCodepoint = sName.substr(4); /* "CODEPOINT" */

				wchar_t c;
				if( sCodepoint.substr(0, 2) == "U+" && IsHexVal(sCodepoint.substr(2)) )
					sscanf( sCodepoint.substr(2).c_str(), "%x", &c );
				else if( sCodepoint.size() > 0 &&
						utf8_get_char_len(sCodepoint[0]) == int(sCodepoint.size()) )
				{
					c = utf8_get_char( sCodepoint.c_str() );
					if(c == wchar_t(-1))
						LOG->Warn("Font definition '%s' has an invalid value '%s'.",
							ini.GetPath().c_str(), sName.c_str() );
				}
				else if( !FontCharAliases::GetChar(sCodepoint, c) )
				{
					LOG->Warn("Font definition '%s' has an invalid value '%s'.",
						ini.GetPath().c_str(), sName.c_str() );
					continue;
				}

				cfg.CharToGlyphNo[c] = pValue->GetValue<int>();

				continue;
			}

			if( sName.substr(0, 6) == "RANGE " )
			{
				/*
				 * range CODESET=first_frame or
				 * range CODESET #start-end=first_frame
				 * eg
				 * range CP1252=0       (default for 256-frame fonts)
				 * range ASCII=0        (default for 128-frame fonts)
				 *
				 * (Start and end are in hex.)
				 *
				 * Map two high-bit portions of ISO-8859- to one font:
				 * range ISO-8859-2 #80-FF=0
				 * range ISO-8859-3 #80-FF=128
				 *
				 * Map hiragana to 0-84:
				 * range Unicode #3041-3094=0
				 */
				vector<RString> asMatches;
				static Regex parse("^RANGE ([A-Z0-9\\-]+)( ?#([0-9A-F]+)-([0-9A-F]+))?$");
				bool bMatch = parse.Compare( sName, asMatches );
				
				ASSERT( asMatches.size() == 4 ); /* 4 parens */

				if( !bMatch || asMatches[0].empty() )
					RageException::Throw( "Font definition \"%s\" has an invalid range \"%s\": parse error.",
						ini.GetPath().c_str(), sName.c_str() );
				
				/* We must have either 1 match (just the codeset) or 4 (the whole thing). */

				int iCount = -1;
				int iFirst = 0;
				if( !asMatches[2].empty() )
				{
					sscanf( asMatches[2].c_str(), "%x", &iFirst );
					int iLast;
					sscanf( asMatches[3].c_str(), "%x", &iLast );
					if( iLast < iFirst )
						RageException::Throw( "Font definition \"%s\" has an invalid range \"%s\": %i < %i.",
							ini.GetPath().c_str(), sName.c_str(), iLast, iFirst );

					iCount = iLast - iFirst + 1;
				}

				RString sRet = cfg.MapRange( asMatches[0], iFirst, pValue->GetValue<int>(), iCount );
				if( !sRet.empty() )
					RageException::Throw( "Font definition \"%s\" has an invalid range \"%s\": %s.",
						ini.GetPath().c_str(), sName.c_str(), sRet.c_str() );

				continue;
			}

			if( sName.substr(0, 5) == "LINE " )
			{
				/* line ROW=CHAR1CHAR2CHAR3CHAR4
				 * eg.
				 * line 0=ABCDEFGH
				 *
				 * This lets us assign characters very compactly and readably. */

				RString sRowStr = sName.substr(5);
				TrimLeft( sRowStr );

				ASSERT( IsAnInt(sRowStr) );
				const int iRow = atoi( sRowStr.c_str() );
				const int iFirstFrame = iRow * iNumFramesWide;

				if( iRow > iNumFramesHigh )
					RageException::Throw( "The font definition \"%s\" tries to assign line %i, but the font is only %i characters high.",
						ini.GetPath().c_str(), iFirstFrame, iNumFramesHigh );

				/* Decode the string. */
				const wstring wdata( RStringToWstring(pValue->GetValue<RString>()) );

				if( int(wdata.size()) > iNumFramesWide )
					RageException::Throw( "The font definition \"%s\" assigns %i characters to row %i (\"%ls\"), but the font is only %i characters wide.",
						ini.GetPath().c_str(), (int)wdata.size(), iRow, wdata.c_str(), iNumFramesWide );

				for( unsigned i = 0; i < wdata.size(); ++i )
					cfg.CharToGlyphNo[wdata[i]] = iFirstFrame+i;
			}
		}
	}
Ejemplo n.º 13
0
Url::Url(wstring string) 
{
	_extractpath((wchar_t *)string.c_str());
}
Ejemplo n.º 14
0
void write_wstring(byte*& w, wstring v) {
	int l = v.length();
	write_int(w, l);
	memcpy(w, v.c_str(), l << 1);
	w += l << 1;
}
Ejemplo n.º 15
0
void Registry::Write(const wstring keyName, const int value)
{
   if (!good) return;
   RegSetValueEx(key, keyName.c_str(), 0, REG_DWORD, (LPBYTE)&value, sizeof(DWORD));
}
Ejemplo n.º 16
0
//
// Parse a vNote string and fills the propertyMap.
//
int WinNote::parse(const wstring dataString) {

    WCHAR* element = NULL;

    //
    // Parse the vNote and fill the VObject.
    // -----------------------------------------
    //
    VObject* vo = VConverter::parse(dataString.c_str());
    if (!vo) {
        setError(1, ERR_ITEM_VOBJ_PARSE);
        LOG.error("%s", getLastErrorMsg());
        return 1;
    }
    // Check if VObject type and version are the correct ones.
    if (!checkVNoteTypeAndVersion(vo)) {
        if (vo) delete vo;
        return 1;
    }


    //
    // Conversion: vObject -> WinNote.
    // -------------------------------
    // Note: properties found are added to the propertyMap, so that the 
    //       map will contain only parsed properties after this process.
    //
    if (element = getVObjectPropertyValue(vo, L"SUMMARY")) {
        setProperty(L"Subject", element);
    }
    if (element = getVObjectPropertyValue(vo, L"BODY")) {
        setProperty(L"Body", element);
    }
    if (element = getVObjectPropertyValue(vo, L"CATEGORIES")) {
        setProperty(L"Categories", element);
    }
    if (element = getVObjectPropertyValue(vo, L"X-FUNAMBOL-FOLDER")) {
        setProperty(L"Folder", element);
    }


    //
    // ---- Other Funambol defined properties ----
    // Support for other fields that don't have a
    // specific correspondence in vNote.
    if (element = getVObjectPropertyValue(vo, L"X-FUNAMBOL-COLOR")) {
        WCHAR tmp[10];
        int i=0;
        for (i=0; i<NUM_NOTE_COLOR; i++) {
            if (!wcscmp(colorName[i], element)) { break; }
        }
        if (i == NUM_NOTE_COLOR) { 
            i = 1;      // Default = yellow
        }
        wsprintf(tmp, TEXT("%i"), i);
        setProperty(L"Color", tmp);
    }

    if (element = getVObjectPropertyValue(vo, L"X-FUNAMBOL-POSITION")) {
        VProperty* vp = vo->getProperty(TEXT("X-FUNAMBOL-POSITION"));
        element = vp->getPropComponent(1);  
        if (element && wcslen(element)>0)  { setProperty(L"Top", element);    }
        element = vp->getPropComponent(2);  
        if (element && wcslen(element)>0)  { setProperty(L"Left", element);   }
        element = vp->getPropComponent(3);  
        if (element && wcslen(element)>0)  { setProperty(L"Height", element); }
        element = vp->getPropComponent(4);  
        if (element && wcslen(element)>0)  { setProperty(L"Width", element);  }
    }

    return 0;
}
Ejemplo n.º 17
0
void CPicDlgQuery::ChangeText(int IDC, wstring text){
    ::SendMessage(GetDlgItem(IDC)->m_hWnd, WM_SETTEXT, 0, (LPARAM)text.c_str());
}
Ejemplo n.º 18
0
HWND SetWindowTextEx(wstring text) {
	HWND hWnd = GetConsoleWindow();
	SetWindowText(hWnd, text.c_str());
	return hWnd;
}
Ejemplo n.º 19
0
Archivo: CNTK.cpp Proyecto: hahatt/CNTK
static wstring PathToBSStringLiteral(const wstring& path) // quote a pathname for BS
{
    let hasSingleQuote = path.find(path, L'\'') != wstring::npos;
    let hasDoubleQuote = path.find(path, L'"') != wstring::npos;
    if (hasSingleQuote && hasDoubleQuote)
        InvalidArgument("Pathname cannot contain both single (') and double (\") quote at the same time: %ls", path.c_str());
    else if (hasSingleQuote)
        return L"\"" + path + L"\"";
    else
        return L'"' + path + L'"';
}
Ejemplo n.º 20
0
wstring CRegExUtil::Replace(const wstring& a_subject, const wstring& a_pattern, const wstring& a_replacement, int a_flags)
{
	wstring l_result;

	if(a_subject.size() > (uint64_t)std::numeric_limits<int>::max())
	{
		return L"";
	}

	const char *szErrDescr;
	int iErrOffset;
	int ovector[OVECTOR_SIZE];

	pcre16* re = pcre16_compile(reinterpret_cast<PCRE_SPTR16>(a_pattern.c_str()),
		PCRE_UTF16 | PCRE_NEWLINE_ANYCRLF | a_flags,
		&szErrDescr, &iErrOffset, NULL);

	if(re)
	{
		int l_prevEndPos = 0; // the index of the character that follows the last character of the previous match.
		pcre16_extra *pe = pcre16_study(re, 0, &szErrDescr); // this could be NULL but it wouldn't matter.

		while(1)
		{
			int l_execResult = pcre16_exec(re, pe, reinterpret_cast<PCRE_SPTR16>(a_subject.c_str()), (int)a_subject.size(), l_prevEndPos, 0, ovector, OVECTOR_SIZE);

			if(l_execResult == PCRE_ERROR_NOMATCH)
			{
				l_result += a_subject.substr(l_prevEndPos);
				break;
			}
			else if(l_execResult < 1)
			{
				// ovector is too small (= 0) or some other internal error (< 0).
				break;
			}

			_ASSERT(ovector[0] >= l_prevEndPos);

			// append string between end of last match and the start of this one:
			l_result += a_subject.substr(l_prevEndPos, ovector[0] - l_prevEndPos);

			if(!a_replacement.empty())
			{
				// insert back references of form $1 $2 $3 ...
				wstring l_replacement;
				wstring::size_type l_pos = a_replacement.find(L'$'), l_prevPos = 0;

				while(l_pos != wstring::npos)
				{
					l_replacement += a_replacement.substr(l_prevPos, l_pos - l_prevPos);

					wstring l_numBuf;
					while(l_pos + 1 < a_replacement.size() &&
						(a_replacement[l_pos + 1] >= L'0' && a_replacement[l_pos + 1] <= L'9'))
					{
						l_pos++;
						l_numBuf += a_replacement[l_pos];
					}
					// maybe make "$14" insert $1 + "4" here if there is no $14.

					int l_group = _wtoi(l_numBuf.c_str());
					if(l_group >= 0 && l_group < l_execResult)
					{
						int l_len = ovector[l_group * 2 + 1] - ovector[l_group * 2];
						l_replacement.append(a_subject, ovector[l_group * 2], l_len);
					}

					l_prevPos = l_pos + 1;
					l_pos = a_replacement.find(L'$', l_prevPos);
				}

				if(l_prevPos < a_replacement.size() - 1)
				{
					l_replacement += a_replacement.substr(l_prevPos);
				}

				l_result += l_replacement;
			}

			// this is where we will start searching again:
			l_prevEndPos = ovector[1];
		}

		if(pe) pcre16_free(pe);
		pcre16_free(re);
	}
	else
	{
		_ASSERT(false);
	}

	return l_result;
}
Ejemplo n.º 21
0
bool install_util::PathExists(const wstring& path) {
  return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES);
}
Ejemplo n.º 22
0
HRESULT ComReg::RegisterCustomFileType(
    const wchar_t* const* argv,  //array of check-byte strings
    const GUID& filter,
    const GUID& mediatype,
    const GUID& subtype)
{
    assert(argv);
    assert(*argv);
    assert(filter != GUID_NULL);
    assert(mediatype != GUID_NULL);
    assert(subtype != GUID_NULL);

    Registry::Key parent, key1, key2;

    LONG e = parent.open(
                HKEY_CLASSES_ROOT,
                L"Media Type",
                KEY_CREATE_SUB_KEY);

    if (e)
        return HRESULT_FROM_WIN32(e);

    wchar_t buf[guid_buflen];

    int n = StringFromGUID2(mediatype, buf, guid_buflen);
    assert(n == guid_buflen);

    e = key1.create<wchar_t>(parent, buf, 0, 0, KEY_SET_VALUE, 0);

    if (e)
        return HRESULT_FROM_WIN32(e);

    n = StringFromGUID2(subtype, buf, guid_buflen);
    assert(n == guid_buflen);

    e = key2.create<wchar_t>(key1, buf, 0, 0, KEY_SET_VALUE, 0);

    if (e)
        return HRESULT_FROM_WIN32(e);

    const wchar_t* arg = *argv;
    assert(arg);

    int i = 0;

    for (;;)
    {
        wostringstream os;
        os << i;

        const wstring name_ = os.str();
        const wchar_t* const name = name_.c_str();

        e = key2.set(name, arg);

        if (e)
            return HRESULT_FROM_WIN32(e);

        arg = *++argv;

        if (arg == 0)
            break;

        ++i;
    }

    n = StringFromGUID2(filter, buf, guid_buflen);
    assert(n == guid_buflen);

    e = key2.set(L"Source Filter", buf);

    if (e)
        return HRESULT_FROM_WIN32(e);

    return S_OK;
}
Ejemplo n.º 23
0
void CMPTutorial::CreateTextChunks(const wstring& localizedString)
{
	// look for tokens
	const wchar_t token[] = { L"##" };
	const size_t tokenLen = (sizeof(token) / sizeof(token[0])) - 1;

	size_t len = localizedString.length();
	size_t startPos = 0;
	size_t pos = localizedString.find(token, 0);
	m_currentEvent.m_numChunks = 0;
	size_t MAX_CHUNKS = SCurrentlyPlayingEvent::eMAX_TEXT_CHUNKS;

	while (pos != wstring::npos)
	{
		STutorialTextChunk& chunk = m_currentEvent.m_chunks[m_currentEvent.m_numChunks];
		chunk.m_text.assign(localizedString.c_str() + startPos, pos-startPos);		// for simplicity just copy the text to event buffer
		chunk.m_startPos = startPos;
		chunk.m_length = pos-startPos;
		++m_currentEvent.m_numChunks;

		if (m_currentEvent.m_numChunks == MAX_CHUNKS-1)
		{
			GameWarning("CMPTutorial::CreateTextChunks: tutorial event '%S' exceeds max. number of chunks [%d]", localizedString.c_str(), MAX_CHUNKS);
			break;
		}
		startPos = pos+tokenLen;
		pos = localizedString.find(token, startPos);
	}

	// care about the last one, but only if we found at least one
	// otherwise there is no splitter at all, and it's only one chunk
	if (m_currentEvent.m_numChunks > 0)
	{
		STutorialTextChunk& chunk = m_currentEvent.m_chunks[m_currentEvent.m_numChunks];
		chunk.m_startPos = startPos;
		chunk.m_length = len-startPos;
		chunk.m_text.assign(localizedString.c_str() + startPos, len-startPos);		// for simplicity just copy the text to event buffer
 		++m_currentEvent.m_numChunks;

		// now we have the total number of chunks, calc the string length without tokens
		size_t realCharLength = len - (m_currentEvent.m_numChunks-1) * tokenLen;
		for (size_t i=0; i<m_currentEvent.m_numChunks; ++i)
		{
			STutorialTextChunk& chunk = m_currentEvent.m_chunks[i];

			size_t realPos = chunk.m_startPos - i * tokenLen; // calculated with respect to realCharLength
			float pos = (float) realPos / (float) realCharLength; // pos = [0,1]
			chunk.m_startPercent = pos;
		}
	}
	else
	{
		// just one chunk.
		m_currentEvent.m_chunks[0].m_startPercent = 0.0f;
		m_currentEvent.m_chunks[0].m_startPos = 0;
		m_currentEvent.m_chunks[0].m_text = localizedString;
		m_currentEvent.m_chunks[0].m_length = localizedString.length();
		m_currentEvent.m_numChunks = 1;
	}

	// set to invalid so we trigger text next update.
	m_currentEvent.m_currentChunk = -1;
}
Ejemplo n.º 24
0
HRESULT ComReg::RegisterByteStreamHandler(
    const wchar_t* ext,
    const GUID& clsid,
    const wchar_t* friendly_name)
{
    const wchar_t parent_subkey[] =
        L"Software\\Microsoft\\Windows Media Foundation\\ByteStreamHandlers";

#if 0
    const BOOL bProtected = SfcIsKeyProtected(
                                HKEY_LOCAL_MACHINE,
                                parent_subkey,
                                0);

    if (bProtected)
        return E_ACCESSDENIED;

    Registry::Key parent;

    LONG e = parent.open(
                HKEY_LOCAL_MACHINE,
                parent_subkey,
                KEY_WRITE);  //KEY_CREATE_SUB_KEY?

    if (e)
        return HRESULT_FROM_WIN32(e);

    Registry::Key key;

    e = key.create<wchar_t>(parent, ext, 0, 0, KEY_SET_VALUE, 0);

    if (e)
        return HRESULT_FROM_WIN32(e);
#else
    const wstring subkey = wstring(parent_subkey) + L"\\" + ext;

    Registry::Key key;

    LONG e = key.create<wchar_t>(
                HKEY_LOCAL_MACHINE,
                subkey.c_str(),
                0,
                0,
                KEY_WRITE,
                0);

    if (e)
        return HRESULT_FROM_WIN32(e);
#endif

    wchar_t buf[guid_buflen];

    const int n = StringFromGUID2(clsid, buf, guid_buflen);
    n;
    assert(n == guid_buflen);

    e = key.set(buf, friendly_name);

    if (e)
        return HRESULT_FROM_WIN32(e);

    return S_OK;
}
Ejemplo n.º 25
0
int
ListBox::add(const wstring& s)
{
	int index = ListBox_AddString(handle(), s.c_str());
	return index;
}
Ejemplo n.º 26
0
	void Serializer::SerializeWString (const wstring &data)
	{
		uint64 size = (data.size() + 1) * sizeof (wchar_t);
		Serialize (size);
		DataStream->Write (ConstBufferPtr ((byte *) (data.data() ? data.data() : data.c_str()), (size_t) size));
	}
Ejemplo n.º 27
0
int _tmain(int argc, _TCHAR* argv[])
{
	CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
	srand(_time32(NULL));

	string savedAccessTokenString;

	ifstream inFile;
	inFile.open(AuthFileName.c_str());
	inFile >> savedAccessTokenString;
	inFile.close();

	HTTPParameters savedParameters = ParseQueryString(UTF8ToWide(savedAccessTokenString));

	wstring oauthAccessToken = savedParameters[L"oauth_token"];
	wstring oauthAccessTokenSecret = savedParameters[L"oauth_token_secret"];
	wstring screenName = savedParameters[L"screen_name"];

	if( oauthAccessToken.empty() || oauthAccessTokenSecret.empty() )
	{
		// Overall OAuth flow based on 
		// Professional Twitter Development: With Examples in .NET 3.5 by Daniel Crenna

		wstring requestToken = OAuthWebRequestSubmit(RequestUrl, L"GET", NULL, ConsumerKey, ConsumerSecret);

		HTTPParameters response = ParseQueryString(requestToken);
		wstring oauthToken = response[L"oauth_token"];
		wstring oauthTokenSecret = response[L"oauth_token_secret"];
		if(!oauthToken.empty())
		{
			wchar_t buf[1024] = {};
			swprintf_s(buf, SIZEOF(buf), AuthorizeUrl.c_str(), oauthToken.c_str());

			wprintf(L"Launching %s\r\n", buf);
			ShellExecute(NULL, L"open", buf, NULL, NULL, SW_SHOWNORMAL);
		}

		wchar_t pin[1024] = {};
		wprintf(L"\r\n");
		wprintf(L"Enter the PIN you receive after authorizing this program in your web browser: ");
		_getws_s(pin, SIZEOF(pin));

		// exchange the request token for an access token
		wstring accessTokenString = OAuthWebRequestSubmit(AccessUrl, L"GET", NULL, ConsumerKey, ConsumerSecret, 
			oauthToken, oauthTokenSecret, pin);

		HTTPParameters accessTokenParameters = ParseQueryString(accessTokenString);
		oauthAccessToken = accessTokenParameters[L"oauth_token"];
		oauthAccessTokenSecret = accessTokenParameters[L"oauth_token_secret"];
		screenName = accessTokenParameters[L"screen_name"];

		ofstream outFile;
		outFile.open(AuthFileName.c_str(), ios_base::out | ios_base::trunc);
		outFile << WideToUTF8(accessTokenString);
		outFile.close();
	}

	wprintf(L"\r\n");
	wprintf(L"Authorized screen_name: %s\r\n", screenName.c_str());
	wprintf(L"Your oauth_token is: %s\r\n", oauthAccessToken.c_str());
	wprintf(L"Your oauth_token_secret is: %s\r\n", oauthAccessTokenSecret.c_str());
	wprintf(L"\r\n");

	wprintf(L"Press enter to request your time line...\r\n");
	getchar();

	// access a protected API call on Twitter using our access token
	wstring userTimeline = OAuthWebRequestSubmit(UserTimelineUrl, L"GET", NULL, ConsumerKey, ConsumerSecret, 
		oauthAccessToken, oauthAccessTokenSecret);

	wprintf(L"\r\nYour timeline:\r\n%s\r\n", userTimeline.c_str());

	wprintf(L"Enter your status update (Enter to skip): ");

	wchar_t buf[500] = {L""};
	_getws_s(buf, SIZEOF(buf));

	wstring input = buf;
	if(input.size() > 0)
	{
		wprintf(L"\r\nUpdating status: %s\r\n", input.c_str());

		HTTPParameters postParams;
		postParams[L"status"] = UrlEncode(input);

		wstring submitResult = OAuthWebRequestSubmit(UserStatusUpdateUrl, L"POST", &postParams, ConsumerKey, ConsumerSecret, 
			oauthAccessToken, oauthAccessTokenSecret);

		wprintf(L"\r\nUpdate Result:\r\n%s\r\n", submitResult.c_str());
	}


	wprintf(L"Press enter to exit...\r\n");
	getchar();

	return 0;
}
Ejemplo n.º 28
0
// Uguale alla GetCurrentPath() ma prende come argomento una wstring
wstring GetCurrentPathStr(const wstring &strInFile) {
	return GetCurrentPath((const PWCHAR)strInFile.c_str());
}
Ejemplo n.º 29
0
int ToInt(const wstring& str) {
  return _wtoi(str.c_str());
}
Ejemplo n.º 30
0
string ws2s(wstring& inputws){ return WChar2Ansi(inputws.c_str()); }