static ErrNo StringToNumbericArr(PCTSTR szBuffer,PCTSTR seps,int *n_arr,const int n)
{
	TCHAR *pstr_t;
	int nLength,nCount;
	TCHAR *pstr,*pnext_token = NULL;

	nLength = _tcslen(szBuffer);
	if(!(pstr_t = new TCHAR [nLength+1]))
		return ALLOCATE_MEMORY_FAIL;

	for(int i=0;i<=nLength;i++)
		pstr_t[i] = szBuffer[i];		//复制字符串

	nCount = 0;
	pstr = wcstok_s(pstr_t,seps,&pnext_token);
	while(pstr != NULL)
	{
		if(!CharacterJudgement(pstr))
			return INCORRECT_DATA;
		if(nCount > n)
			return NOT_MATCH;
		//n_arr[nCount] = wcstod(pstr,&ptemp);
		n_arr[nCount] = _wtoi(pstr);
		pstr = wcstok_s(NULL,seps,&pnext_token);
		nCount++;
	}
	if(nCount != n)
		return NOT_MATCH;

	delete [] pstr_t;
	return 0;
}
Exemple #2
0
// Should be robust enough to catch most edge cases.
bool DNS::IsIPv4(LPWSTR s)
{
	DWORD i;
	DWORD places = 0;
	DWORD octets = 0;
	LPWSTR parts[4];
	WCHAR *token = NULL;
	WCHAR *tmpString = new WCHAR[lstrlen(s)+1];
	WCHAR *context = NULL;

	ZeroMemory(tmpString, lstrlen(s)+1);

	for(i = 0; i < (DWORD)lstrlen(s); i++)
	{
		if((s[i] < 0x30 && s[i] != 0x2E) || (s[i] > 0x39 && s[i] != 0x2E))
		{
			return false;
		}
		if(s[i] >= 0x30 && s[i] <= 0x39)
		{
			places++;
		}
		if(s[i] == 0x2E)
		{
			octets++;
			places = 0;
		}
		if(places > 3 || octets > 4)
		{
			return false;
		}
	}

	lstrcpy(tmpString, s);

	token = wcstok_s(tmpString, L".", &context);

	while(token != NULL)
	{
		DWORD num = 0;

		num = _wtoi(token);

		if(num < 0 || num > 255)
		{
			return false;
		}

		token = wcstok_s(NULL, L".", &context);
	}
	delete(tmpString);
	return true;
}
Exemple #3
0
STDMETHODIMP Profile::get_Languages(SAFEARRAY ** pVal)
{
	try {
		WCHAR * pResult = gSkypeQueue.RetrieveProperty(L"PROFILE", L"", L"LANGUAGES");

		long lTotal=0, lCtr=0;
		HRESULT hr;
		BSTR * pItems;

		for(int i = 0; i < 2; i++) {
			WCHAR *next_token = NULL;
			WCHAR * pItem = wcstok_s(pResult, L" ", &next_token);
			while(pItem != NULL) {
				if(wcslen(pItem) > 0) {
					if(i == 0) {
						lTotal++;
					} else {
						pItems[lCtr++] = SysAllocString(pItem);
					}
				}
				pItem = wcstok_s(NULL, L" ", &next_token);
			}

			if(i == 0) {
				SAFEARRAYBOUND sba;
				sba.cElements = lTotal;
				sba.lLbound = 0;
				*pVal = SafeArrayCreateEx(VT_BSTR, 1, & sba, NULL);
				if((*pVal) == NULL) {
					return AtlReportError(GetObjectCLSID(), L"Unable to create array", GUID_NULL, E_FAIL);
				}
				hr = SafeArrayLock(*pVal);
				if(FAILED(hr)) {
					return AtlReportError(GetObjectCLSID(), L"Unable to lock array", GUID_NULL, E_FAIL);
				}

				pItems = (BSTR *) (*pVal)->pvData;
			} else {
				hr = SafeArrayUnlock(*pVal);
				if(FAILED(hr)) {
					return AtlReportError(GetObjectCLSID(), L"Unable to unlock array", GUID_NULL, E_FAIL);
				}
			}
		}

		free(pResult);
		return S_OK;
	} catch (const WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}
}
// Need String, String (char), Integer
extern "C" long _declspec(dllexport) _stdcall Split(int nNumArgs, FormulaAddInData *pArgs, FormulaAddInData *pReturnValue)
{
	pReturnValue->nVarType = 2;

	// Check Input Parameters
	if (nNumArgs != 3 ||
		pArgs[0].nVarType != 2 ||
		pArgs[1].nVarType != 2 ||
		pArgs[2].nVarType != 1) {
		const wchar_t* errorMessage = L"Syntax: Syntax, Delimiter, Token Number.";
		SetString(pReturnValue, errorMessage);
		pReturnValue->isNull = 1;
		return 0;
	}

	// Check for Nulls
	if (pArgs[0].isNull || pArgs[2].isNull || pArgs[2].dVal < 0 || pArgs[1].isNull || wcslen(pArgs[1].pVal) == 0) {
		SetString(pReturnValue, pArgs[0].pVal);
		ResetIsNull(nNumArgs, pArgs);
		return 1;
	}

	// Copy the string
	size_t nLen = wcslen(pArgs[0].pVal);
	if (nLen == 0) {
		pReturnValue->isNull = true;
		return 1;
	}

	wchar_t *input = new wchar_t[nLen + 1];
	wcscpy(input, pArgs[0].pVal);

	// Split the String
	wchar_t* buffer = NULL;
	wchar_t *token = NULL;
	token = wcstok_s(input, pArgs[1].pVal, &buffer);
	int count = 1;
	while (token != NULL && count < pArgs[2].dVal) {
		token = wcstok_s(NULL, pArgs[1].pVal, &buffer);
		count++;
	}

	if (token == NULL) {
		pReturnValue->isNull = true;
	} else {
		SetString(pReturnValue, token);
	}

	delete input;
	return 1;
}
Exemple #5
0
// 設定をロードする
std::map<std::wstring, std::wstring> loadSettings(LPCWSTR fileName, LPCWSTR sectionName)
{
	std::map<std::wstring, std::wstring> settings;
	TCHAR wcFilePath[MAX_PATH];
	TCHAR wcSettings[32767];
	TCHAR *lpwcCurrent;
	TCHAR *lpwcString;
	TCHAR *lpwcContext;
	size_t len;
	std::wstring key;
	std::wstring value;

	GetFullPathName(fileName, MAX_PATH, wcFilePath, NULL);
	GetPrivateProfileSection(sectionName, wcSettings, 32767, wcFilePath);

	lpwcCurrent = wcSettings;
	while (*lpwcCurrent) {
		len = wcslen(lpwcCurrent);
		lpwcString = wcstok_s(lpwcCurrent, _T("="), &lpwcContext);
		key = std::wstring(lpwcString);
		value = std::wstring(lpwcString + wcslen(lpwcString) + 1);
		settings[key] = value;
		lpwcCurrent += len + 1;
	}

	return settings;
}
Exemple #6
0
static int
find_env_config_value(FILE * env_file, const wchar_t * key, wchar_t * value)
{
    int result = 0; /* meaning not found */
    char buffer[MAXPATHLEN*2+1];  /* allow extra for key, '=', etc. */

    fseek(env_file, 0, SEEK_SET);
    while (!feof(env_file)) {
        char * p = fgets(buffer, MAXPATHLEN*2, env_file);
        wchar_t tmpbuffer[MAXPATHLEN*2+1];
        PyObject * decoded;
        size_t n;

        if (p == NULL)
            break;
        n = strlen(p);
        if (p[n - 1] != '\n') {
            /* line has overflowed - bail */
            break;
        }
        if (p[0] == '#')    /* Comment - skip */
            continue;
        decoded = PyUnicode_DecodeUTF8(buffer, n, "surrogateescape");
        if (decoded != NULL) {
            Py_ssize_t k;
            k = PyUnicode_AsWideChar(decoded,
                                     tmpbuffer, MAXPATHLEN * 2);
            Py_DECREF(decoded);
            if (k >= 0) {
                wchar_t * context = NULL;
                wchar_t * tok = wcstok_s(tmpbuffer, L" \t\r\n", &context);
                if ((tok != NULL) && !wcscmp(tok, key)) {
                    tok = wcstok_s(NULL, L" \t", &context);
                    if ((tok != NULL) && !wcscmp(tok, L"=")) {
                        tok = wcstok_s(NULL, L"\r\n", &context);
                        if (tok != NULL) {
                            wcsncpy(value, tok, MAXPATHLEN);
                            result = 1;
                            break;
                        }
                    }
                }
            }
        }
    }
    return result;
}
Exemple #7
0
void DNS::IPToHostname(LPWSTR ip, std::wstring *hostname)
{
	PDNS_RECORD dnsInfo;
	DWORD ret;
	WCHAR *token;
	WCHAR *context;
	std::wstring address;
	std::vector<LPWSTR> octets;

	LPWSTR tmpString = new WCHAR[lstrlen(ip)+1];
	ZeroMemory(tmpString, lstrlen(ip)+1);
	lstrcpy(tmpString, ip);

	hostname->clear();
	// Gotta flip the IP around for reverse DNS lookups.
	token = wcstok_s(tmpString, L".", &context);

	while(token != NULL)
	{
		octets.push_back(token);
		token = wcstok_s(NULL, L".", &context);
	}

	address.append(octets[3]);
	address.append(L".");
	address.append(octets[2]);
	address.append(L".");
	address.append(octets[1]);
	address.append(L".");
	address.append(octets[0]);
	address.append(L".in-addr.arpa");

	if((ret = DnsQuery((PWCHAR)address.c_str(), DNS_TYPE_PTR, DNS_QUERY_STANDARD, NULL, &dnsInfo, NULL)) != 0)
	{
		Util::Error(ret, L"DnsQuery()");
		wprintf(L"ret = %x\n", ret);
	}
	else
	{
		hostname->append(dnsInfo->Data.PTR.pNameHost);
		DnsRecordListFree(dnsInfo);
	}
	delete(tmpString);
}
void ChatMessageCollection::SetItemList(LPCWSTR ItemList)
{
	try {
		m_itemList.clear();

		WCHAR * list = _wcsdup(ItemList);
		WCHAR *next_token = NULL;
		WCHAR * pItem = wcstok_s(list, L", ", &next_token);
		while(pItem) {
			long lID = _wtol(pItem);
			if(lID > 0) {
				m_itemList.push_back(lID);
			}
			pItem = wcstok_s(NULL, L", ", &next_token);
		}
	free(list);
	} catch(...) {
	}
}
Exemple #9
0
void parse_headers_string(_Inout_z_ utf16char* headersStr, http_headers& headers)
{
    utf16char* context = nullptr;
    utf16char* line = wcstok_s(headersStr, CRLF, &context);
    while (line != nullptr)
    {
        const utility::string_t header_line(line);
        const size_t colonIndex = header_line.find_first_of(_XPLATSTR(":"));
        if (colonIndex != utility::string_t::npos)
        {
            utility::string_t key = header_line.substr(0, colonIndex);
            utility::string_t value = header_line.substr(colonIndex + 1, header_line.length() - colonIndex - 1);
            http::details::trim_whitespace(key);
            http::details::trim_whitespace(value);
            headers.add(key, value);
        }
        line = wcstok_s(nullptr, CRLF, &context);
    }
}
void CSkypeMessageQueue::InternalRebuildUserList()
{
	m_bNeedRebuildUserList = false;
	m_listUsers.clear();

	try {
		WCHAR * pStrUsers = gSkypeQueue.ExecuteBlockingCommand(L"SEARCH FRIENDS", L"USERS");
		WCHAR *next_token = NULL;
		WCHAR * pItem = wcstok_s(pStrUsers, L", ", &next_token);
		while(pItem) {
			if(wcslen(pItem) > 0) {
				m_listUsers[std::wstring(pItem)] = olsUnknown;
			}
			pItem = wcstok_s(NULL, L", ", &next_token);
		}
		free(pStrUsers);
	} catch(const WCHAR * err) {
	}
}
Exemple #11
0
wchar_t *find_on_path(wchar_t *name)
{
    wchar_t *pathext;
    size_t   varsize;
    wchar_t *context = NULL;
    wchar_t *extension;
    wchar_t *result = NULL;
    DWORD    len;
    errno_t  rc;
    /* Return value storage - we don't need to be re-entrant */
    static wchar_t path_buf[MAX_PATH];

    if (wcschr(name, L'.') != NULL) {
        /* assume it has an extension. */
        len = SearchPathW(NULL, name, NULL, MAX_PATH, path_buf, NULL);
        if (len) {
            result = path_buf;
        }
    }
    else {
        /* No extension - search using registered extensions. */
        rc = _wdupenv_s(&pathext, &varsize, L"PATHEXT");
        if (rc == 0) {
            extension = wcstok_s(pathext, L";", &context);
            while (extension) {
                len = SearchPathW(NULL, name, extension, MAX_PATH, path_buf, NULL);
                if (len) {
                    result = path_buf;
                    break;
                }
                extension = wcstok_s(NULL, L";", &context);
            }
            free(pathext);
        }
    }
    if (result) {
        /* We just want the directory */
        wchar_t *end = wcsrchr(result, L'\\');
        *end = L'\0';
    }
    return result;
}
//----------------------------------------------------------------
void CPUTConfigEntry::ValueAsFloatArray(float *pFloats, int count)
{
    cString valueCopy = szValue;
    TCHAR *szOrigValue = (TCHAR*)valueCopy.c_str();

    TCHAR *szNewValue = NULL;
    TCHAR *szCurrValue = wcstok_s(szOrigValue, _L(" "), &szNewValue);
	for(int clear = 0; clear < count; clear++)
	{
		pFloats[clear] = 0.0f;
	}
    for(int ii=0;ii<count;++ii)
    {
		if(szCurrValue == NULL)
            return;
        swscanf_s(szCurrValue, _L("%f"), pFloats+ii);
        szCurrValue = wcstok_s(NULL, _L(" "), &szNewValue);

    }
}
BOOL IsDeleteFile(LPCTSTR lpszFilePath, LPCTSTR lpszExtList)
{
	DWORD dwSize = lstrlen(lpszExtList);
	LPTSTR lpszExtList2 = (LPTSTR)GlobalAlloc(0, (dwSize + 1) * sizeof(TCHAR));
	lstrcpy(lpszExtList2, lpszExtList);
	LPCTSTR seps = TEXT(";");
	TCHAR *next;
	LPTSTR token = wcstok_s(lpszExtList2, seps, &next);
	while (token != NULL)
	{
		if (PathMatchSpec(lpszFilePath, token))
		{
			GlobalFree(lpszExtList2);
			return TRUE;
		}
		token = wcstok_s(0, seps, &next);
	}
	GlobalFree(lpszExtList2);
	return FALSE;
}
Exemple #14
0
PWSTR XmlParseToken(
    _In_ PWSTR XmlString,
    _In_ PWSTR XmlTokenName
    )
{
    PWSTR xmlTokenNext = NULL;
    PWSTR xmlStringData;
    PWSTR xmlTokenString;

    xmlStringData = PhDuplicateStringZ(XmlString);

    xmlTokenString = wcstok_s(
        xmlStringData,
        L"<>",
        &xmlTokenNext
        );

    while (xmlTokenString)
    {
        if (PhEqualStringZ(xmlTokenString, XmlTokenName, TRUE))
        {
            // We found the value.
            xmlTokenString = wcstok_s(NULL, L"<>", &xmlTokenNext);
            break;
        }

        xmlTokenString = wcstok_s(NULL, L"<>", &xmlTokenNext);
    }

    if (xmlTokenString)
    {
        PWSTR xmlStringDup = PhDuplicateStringZ(xmlTokenString);

        PhFree(xmlStringData);

        return xmlStringDup;
    }

    PhFree(xmlStringData);
    return NULL;
}
void CSkypeMessageQueue::InternalRebuildCallList()
{
	m_bNeedRebuildCallList = false;
	m_listCalls.clear();

	try {
		WCHAR * pStrCalls = gSkypeQueue.ExecuteBlockingCommand(L"SEARCH CALLS", L"CALLS");
		WCHAR * list = pStrCalls;
		WCHAR *next_token = NULL;
		WCHAR * pItem = wcstok_s(list, L", ", &next_token);
		while(pItem) {
			long lID = _wtol(pItem);
			if(lID > 0) {
				m_listCalls[lID] = prgUnknown;
			}
			pItem = wcstok_s(NULL, L", ", &next_token);
		}
		free(pStrCalls);
	} catch(const WCHAR * err) {
	}
}
ContentType WBPassthruSink::GetContentTypeFromURL(const std::wstring& src)
{
  std::wstring schemeAndHierarchicalPart = GetSchemeAndHierarchicalPart(src);
  auto contentType = GetContentTypeFromString(schemeAndHierarchicalPart);
  if (contentType == ContentType::CONTENT_TYPE_OTHER &&
    AdblockPlus::IE::InstalledMajorVersion() == 8)
  {
    std::wstring queryString = GetQueryString(src);
    wchar_t* nextToken = nullptr;
    const wchar_t* token = wcstok_s(&queryString[0], L"&=", &nextToken);
    while (token != nullptr)
    {
      contentType = GetContentTypeFromString(token);
      if (contentType != ContentType::CONTENT_TYPE_OTHER)
      {
         return contentType;
      }
      token = wcstok_s(nullptr, L"&=", &nextToken);
    }
  }
  return contentType;
}
Exemple #17
0
void ConfigParser::ParseRegistryKey(HKEY hk, CmdLineArgsParser &parser)
{
#ifdef _WIN32
    DWORD dwSize;
    DWORD dwValue;

#if ENABLE_DEBUG_CONFIG_OPTIONS
    char16 regBuffer[MaxRegSize];
    dwSize = sizeof(regBuffer);
    if (NOERROR == RegGetValueW(hk, nullptr, _u("JScript9"), RRF_RT_REG_SZ, nullptr, (LPBYTE)regBuffer, &dwSize))
    {
        LPWSTR regValue = regBuffer, nextValue = nullptr;
        regValue = wcstok_s(regBuffer, _u(" "), &nextValue);
        while (regValue != nullptr)
        {
            int err = 0;
            if ((err = parser.Parse(regValue)) != 0)
            {
                break;
            }
            regValue = wcstok_s(nullptr, _u(" "), &nextValue);
        }
    }
#endif

    // MemSpect - This setting controls whether MemSpect instrumentation is enabled.
    // The value is treated as a bit field with the following bits:
    //   0x01 - Track Arena memory
    //   0x02 - Track Recycler memory
    //   0x04 - Track Page allocations
    dwValue = 0;
    dwSize = sizeof(dwValue);
    if (NOERROR == ::RegGetValueW(hk, nullptr, _u("MemSpect"), RRF_RT_DWORD, nullptr, (LPBYTE)&dwValue, &dwSize))
    {
        if (dwValue & 0x01)
        {
            ArenaMemoryTracking::Activate();
        }
        if (dwValue & 0x02)
        {
            RecyclerMemoryTracking::Activate();
        }
        if (dwValue & 0x04)
        {
            PageTracking::Activate();
        }
    }

    // JScriptJIT - This setting controls the JIT/interpretation of Jscript code.
    // The legal values are as follows:
    //      1- Force JIT code to be generated for everything.
    //      2- Force interpretation without profiling (turn off JIT)
    //      3- Default
    //      4- Interpreter, simple JIT, and full JIT run a predetermined number of times. Requires >= 3 calls to functions.
    //      5- Interpreter, simple JIT, and full JIT run a predetermined number of times. Requires >= 4 calls to functions.
    //      6- Force interpretation with profiling
    //
    // This reg key is present in released builds.  The QA team's tests use these switches to
    // get reliable JIT coverage in servicing runs done by IE/Windows.  Because this reg key is
    // released, the number of possible values is limited to reduce surface area.
    dwValue = 0;
    dwSize = sizeof(dwValue);
    if (NOERROR == RegGetValueW(hk, nullptr, _u("JScriptJIT"), RRF_RT_DWORD, nullptr, (LPBYTE)&dwValue, &dwSize))
    {
        Js::ConfigFlagsTable &configFlags = Js::Configuration::Global.flags;
        switch (dwValue)
        {
        case 1:
            configFlags.Enable(Js::ForceNativeFlag);
            configFlags.ForceNative = true;
            break;

        case 6:
            configFlags.Enable(Js::ForceDynamicProfileFlag);
            configFlags.ForceDynamicProfile = true;
            // fall through

        case 2:
            configFlags.Enable(Js::NoNativeFlag);
            configFlags.NoNative = true;
            break;

        case 3:
            break;

        case 4:
            configFlags.Enable(Js::AutoProfilingInterpreter0LimitFlag);
            configFlags.Enable(Js::ProfilingInterpreter0LimitFlag);
            configFlags.Enable(Js::AutoProfilingInterpreter1LimitFlag);
            configFlags.Enable(Js::SimpleJitLimitFlag);
            configFlags.Enable(Js::ProfilingInterpreter1LimitFlag);
            configFlags.Enable(Js::EnforceExecutionModeLimitsFlag);

            configFlags.AutoProfilingInterpreter0Limit = 0;
            configFlags.AutoProfilingInterpreter1Limit = 0;
            if (
#if ENABLE_DEBUG_CONFIG_OPTIONS
                configFlags.NewSimpleJit
#else
                DEFAULT_CONFIG_NewSimpleJit
#endif
                )
            {
                configFlags.ProfilingInterpreter0Limit = 0;
                configFlags.SimpleJitLimit = 0;
                configFlags.ProfilingInterpreter1Limit = 2;
            }
            else
            {
                configFlags.ProfilingInterpreter0Limit = 1;
                configFlags.SimpleJitLimit = 1;
                configFlags.ProfilingInterpreter1Limit = 0;
            }
            configFlags.EnforceExecutionModeLimits = true;
            break;

        case 5:
            configFlags.Enable(Js::AutoProfilingInterpreter0LimitFlag);
            configFlags.Enable(Js::ProfilingInterpreter0LimitFlag);
            configFlags.Enable(Js::AutoProfilingInterpreter1LimitFlag);
            configFlags.Enable(Js::SimpleJitLimitFlag);
            configFlags.Enable(Js::ProfilingInterpreter1LimitFlag);
            configFlags.Enable(Js::EnforceExecutionModeLimitsFlag);

            configFlags.AutoProfilingInterpreter0Limit = 0;
            configFlags.ProfilingInterpreter0Limit = 0;
            configFlags.AutoProfilingInterpreter1Limit = 1;
            if (
#if ENABLE_DEBUG_CONFIG_OPTIONS
                configFlags.NewSimpleJit
#else
                DEFAULT_CONFIG_NewSimpleJit
#endif
                )
            {
                configFlags.SimpleJitLimit = 0;
                configFlags.ProfilingInterpreter1Limit = 2;
            }
            else
            {
                configFlags.SimpleJitLimit = 2;
                configFlags.ProfilingInterpreter1Limit = 0;
            }
            configFlags.EnforceExecutionModeLimits = true;
            break;
        }
    }

    // EnumerationCompat
    // This setting allows disabling a couple of changes to enumeration:
    //     - A change that causes deleted property indexes to be reused for new properties, thereby changing the order in which
    //       properties are enumerated
    //     - A change that creates a true snapshot of the type just before enumeration, and enumerating only those properties. A
    //       property that was deleted before enumeration and is added back during enumeration will not be enumerated.
    // Values:
    //     0 - Default
    //     1 - Compatibility mode for enumeration order (disable changes described above)
    // This FCK does not apply to WWAs. WWAs should use the RC compat mode to disable these changes.
    dwValue = 0;
    dwSize = sizeof(dwValue);
    if (NOERROR == RegGetValueW(hk, nullptr, _u("EnumerationCompat"), RRF_RT_DWORD, nullptr, (LPBYTE)&dwValue, &dwSize))
    {
        if(dwValue == 1)
        {
            Js::Configuration::Global.flags.EnumerationCompat = true;
        }
    }

#ifdef ENABLE_PROJECTION
    // FailFastIfDisconnectedDelegate
    // This setting allows enabling fail fast if the delegate invoked is disconnected
    //     0 - Default return the error RPC_E_DISCONNECTED if disconnected delegate is invoked
    //     1 - Fail fast if disconnected delegate
    dwValue = 0;
    dwSize = sizeof(dwValue);
    if (NOERROR == RegGetValueW(hk, nullptr, _u("FailFastIfDisconnectedDelegate"), RRF_RT_DWORD, nullptr, (LPBYTE)&dwValue, &dwSize))
    {
        if(dwValue == 1)
        {
            Js::Configuration::Global.flags.FailFastIfDisconnectedDelegate = true;
        }
    }
#endif

    // ES6 feature control
    // This setting allows enabling\disabling es6 features
    //     0 - Enable ES6 flag - Also default behavior
    //     1 - Disable ES6 flag
    dwValue = 0;
    dwSize = sizeof(dwValue);
    if (NOERROR == RegGetValueW(hk, nullptr, _u("DisableES6"), RRF_RT_DWORD, nullptr, (LPBYTE)&dwValue, &dwSize))
    {
        Js::ConfigFlagsTable &configFlags = Js::Configuration::Global.flags;
        if (dwValue == 1)
        {
            configFlags.Enable(Js::ES6Flag);
            configFlags.SetAsBoolean(Js::ES6Flag, false);
        }
    }

    // Asmjs feature control
    // This setting allows enabling\disabling asmjs compilation
    //     0 - Disable Asmjs phase - Also default behavior
    //     1 - Enable Asmjs phase
    dwValue = 0;
    dwSize = sizeof(dwValue);
    if (NOERROR == RegGetValueW(hk, nullptr, _u("EnableAsmjs"), RRF_RT_DWORD, nullptr, (LPBYTE)&dwValue, &dwSize))
    {
        if (dwValue == 1)
        {
            Js::Configuration::Global.flags.Asmjs = true;
        }
    }
#endif // _WIN32
}
Exemple #18
0
void TestMove_s( void )
{

    wchar_t    buf[128];
    wchar_t    s2[] = L"VALUE";
    wchar_t    str[] = L"VALUE";

    wchar_t    src1[100] = L"hello";
    wchar_t    src2[7] = L"goodbye";
    wchar_t    dst1[6], dst2[5], dst3[5];

    wchar_t    sc1[100] = L"good";
    wchar_t    sc2[6] = L"hello";
    wchar_t    sc3[6] = L"hello";
    wchar_t    sc4[7] = L"abc";
    wchar_t    sc5[1000] = L"bye";

    int     violations = NumViolations;

    /*   wcstok_s */
    static wchar_t     str1[] = L"?a???b,,,#c";
    static wchar_t     str2[] = L"\t \t";
    static wchar_t     str3[] = L"?a???b,,,#c";
    wchar_t            *t, *ptr1, *ptr2, *ptr3;
    rsize_t         max1 = ARRAYCOUNT( str1 );
    rsize_t         max2 = ARRAYCOUNT( str2 );
    rsize_t         max3 = ARRAYCOUNT( str3 );


    /***********************************************************************/
    /*  set constraint-handler                                             */
    /***********************************************************************/

    set_constraint_handler_s( my_constraint_handler );

    /***********************************************************************/
    /*  memcpy_s                                                           */
    /***********************************************************************/
//  printf( "Test memcpys      (%s).\n", ProgramName );

    /* Test the "good" case */
    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), s2, 0 ) == 0 );
    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), s2, 1 + wcslen( s2 ) ) == 0 );
    VERIFY( wmemcpy_s( buf, wcslen( s2 ) + 2, s2, 1 + wcslen( s2 ) ) == 0 );

    VERIFY( wcslen( buf ) == wcslen( L"VALUE" ) );
    VERIFY( wcscmp( buf, L"VALUE" ) == 0 );
    VERIFY( NumViolations == violations );

    /* Test various failing cases */
    /* Test runtime-constraint violations */
    VERIFY( wmemcpy_s( buf, 3, s2, wcslen( s2 ) ) != 0 );
    VERIFY( buf[0] == L'\0' );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemcpy_s( NULL, ARRAYCOUNT( buf ), s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), NULL, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), s2, sizeof( buf ) / sizeof( buf[0] )+ 1 ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), buf + 1, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

#if RSIZE_MAX != SIZE_MAX
    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), s2, ~0 ) != 0 );
    VERIFY( NumViolations == ++violations );
#endif

    /***********************************************************************/
    /*  memmove_s                                                          */
    /***********************************************************************/
//  printf( "Test memmove      (%s).\n", ProgramName );

    /* Test the "good" cases */
    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), s2, 0 ) == 0 );
    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), s2, 1 + wcslen( s2 ) ) == 0 );

    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), buf + 1, 1 + wcslen( s2 ) ) == 0 );

    VERIFY( wmemmove_s( buf, 1 + wcslen( s2 ), s2, 1 + wcslen( s2 ) ) == 0 );

    VERIFY( wcslen( buf ) == wcslen( L"VALUE" ) );
    VERIFY( wcscmp( buf, L"VALUE" ) == 0 );
    VERIFY( NumViolations == violations );

    /* Test various failing cases */
    /* Test runtime-constraint violations */
    VERIFY( wmemmove_s( buf, 3, s2, wcslen( s2 ) ) != 0 );
    VERIFY( buf[0] == L'\0' );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemmove_s( NULL, ARRAYCOUNT( buf ), s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), NULL, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), s2, ARRAYCOUNT( buf ) + 1 ) != 0 );
    VERIFY( NumViolations == ++violations );

#if RSIZE_MAX != SIZE_MAX
    VERIFY( wmemmove_s( buf, ~0, s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), s2, ~0 ) != 0 );
    VERIFY( NumViolations == ++violations );
#endif

    /***********************************************************************/
    /*  wcscpy_s                                                           */
    /***********************************************************************/
//  printf( "Test memcpy       (%s).\n", ProgramName );

    /* Test the "good" cases */
    VERIFY( wcscpy_s( buf, ARRAYCOUNT( buf ), s2 ) == 0 );
    VERIFY( wcscpy_s( buf, ARRAYCOUNT( buf ), s2 ) == 0 );
    VERIFY( wcscpy_s( buf, wcslen( s2 ) + 1, s2 ) == 0 );


    VERIFY( wcslen( buf ) == wcslen( L"VALUE" ) );
    VERIFY( wcscmp( buf, L"VALUE" ) == 0 );
    VERIFY( NumViolations == violations );

    /* Test various failing cases */
    /* Test runtime-constraint violations */
    VERIFY( wcscpy_s( buf, 3, s2 ) != 0 );
    VERIFY( NumViolations == ++violations );
    VERIFY( buf[0] == L'\0' );

    VERIFY( wcscpy_s( NULL, ARRAYCOUNT( buf ), s2 ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcscpy_s( buf, ARRAYCOUNT( buf ), NULL ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcscpy_s( buf, 5, s2 ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcscpy_s( buf, ARRAYCOUNT( buf ), buf + 1 ) != 0 );
    VERIFY( NumViolations == ++violations );

#if RSIZE_MAX != SIZE_MAX
    VERIFY( wcscpy_s( buf, ~0, s2 ) != 0 );
    VERIFY( NumViolations == ++violations );
#endif

    /***********************************************************************/
    /*  wcscat_s                                                           */
    /***********************************************************************/
//  printf( "Test wcscat       (%s).\n", ProgramName );
    wcscpy( sc1,src1 );
    VERIFY( wcscmp( sc1,src1 ) == 0 );
    VERIFY( wcscat_s( sc1, 100, sc5 ) == 0 );
    VERIFY( wcscmp( sc1, L"hellobye") == 0 );

    VERIFY( wcscat_s( sc2, 6, L"" ) == 0 );

    VERIFY( wcscat_s( sc3, 6, L"X" ) != 0 );
    VERIFY( NumViolations == ++violations );
    VERIFY( sc3[0] == L'\0');

    VERIFY( wcscat_s(sc4, 7, L"defghijklmn") != 0);
    VERIFY( NumViolations == ++violations );

    VERIFY( wcscmp(sc4, L"" ) == 0);


    /***********************************************************************/
    /*  wcsnlen_s                                                          */
    /***********************************************************************/

//  printf( "Test wcsnlen      (%s).\n", ProgramName );
    /* Test the "good" case */
    VERIFY( wcsnlen_s( str, ARRAYCOUNT( str ) ) == wcslen( str ) );
    VERIFY( wcsnlen_s( str, 4 ) == 4 );
    VERIFY( wcsnlen_s( str, 0 ) == 0 );
    VERIFY( wcsnlen_s( NULL, 1000 ) == 0 );

    /* Test various failing cases */

    /* No runtime-constraint violations to test */

    VERIFY( NumViolations == violations );

    /***********************************************************************/
    /*  wcsncpy_s                                                          */
    /***********************************************************************/

//  printf( "Test wcsncpy      (%s).\n", ProgramName );
    /* Test the "good" case */
    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), s2, 0 ) == 0 );
    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), s2, wcslen( s2 ) ) == 0 );
    VERIFY( wcsncpy_s( buf, wcslen( s2 ) + 1, s2, wcslen( s2 ) ) == 0 );

    VERIFY( wcslen( buf ) == wcslen( L"VALUE" ) );
    VERIFY( wcscmp( buf, L"VALUE" ) == 0 );
    VERIFY( NumViolations == violations );

    VERIFY( wcsncpy_s( dst1, 6, src1, 100 ) == 0 );
    VERIFY( wcscmp( dst1, src1 ) == 0 );

    VERIFY( wcsncpy_s( dst3, 5, src2, 4 ) == 0 );

    /* Test various failing cases */
    /* Test runtime-constraint violations */
    VERIFY( wcsncpy_s( buf, 3, s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );
    VERIFY( buf[0] == '\0' );

    VERIFY( wcsncpy_s( NULL, ARRAYCOUNT( buf ), s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), NULL, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), buf + 1, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcsncpy_s( dst2, 5, src2, 7 ) != 0 );
    VERIFY( NumViolations == ++violations );


#if RSIZE_MAX != SIZE_MAX
    VERIFY( wcsncpy_s( buf, ~0, s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), s2, ~0 ) != 0 );
    VERIFY( NumViolations == ++violations );
#endif


    /***********************************************************************/
    /*  wcsncat_s                                                          */
    /***********************************************************************/

//  printf( "Test wcsncat      (%s).\n", ProgramName );
    wcscpy( sc1, L"good" );
    wcscpy( sc2, L"hello" );
    wcscpy( sc3, L"hello" );
    wcscpy( sc4, L"abc" );
    VERIFY( wcsncat_s( sc1, 100, sc5, 1000 ) == 0);
    VERIFY( wcscmp( sc1, L"goodbye" ) == 0 );

    VERIFY( wcsncat_s( sc2, 6, L"", 1 ) == 0 );

    VERIFY( wcsncat_s( sc4, 7, L"defghijklmn", 3 ) == 0 );
    VERIFY( wcscmp( sc4, L"abcdef" ) == 0 );

    /* Test runtime-constraint violations */
    VERIFY( wcsncat_s( sc3, 6, L"XXX", 3 ) != 0 );
    VERIFY( NumViolations == ++violations );
    VERIFY( sc3[0] == L'\0');

    /***********************************************************************/
    /*  wcstok_s                                                           */
    /***********************************************************************/

//  printf( "Test wcstok       (%s).\n", ProgramName );
    VERIFY( (t = wcstok_s( str1, &max1, L"?", &ptr1 )) != NULL );    /* points to the token "a" */
    VERIFY( wcscmp( t, L"a" ) == 0 );

    VERIFY( (t = wcstok_s( NULL, &max1, L",", &ptr1 )) != NULL );    /* points to the token "??b" */
    VERIFY( wcscmp( t, L"??b" ) == 0 );

    VERIFY( NULL == wcstok_s( str2, &max2, L" \t", &ptr2 ) );        /* null pointer */
    VERIFY( NumViolations == violations );

    VERIFY( (t = wcstok_s( NULL, &max1, L"#,", &ptr1 )) != NULL  );  /* points to the token "c" */
    VERIFY( wcscmp( t, L"c" ) == 0 );
    VERIFY( ptr1 != NULL );
    VERIFY( NumViolations == violations );

    VERIFY( NULL == wcstok_s( NULL, &max1, L"#,", &ptr1 ) );  /* at the end */

    wcscpy( str1, str3 );
    max1 = ARRAYCOUNT( str1 );
    VERIFY( NULL == wcstok_s( str1, &max1, str3, &ptr3 ) );         /* only delimiter chars */

//  printf( "Test wcstok rtc   (%s).\n", ProgramName );
    /* Test runtime-constraint violations */
    ptr1 = NULL;
    VERIFY( NULL == wcstok_s( NULL, &max1, L"?", &ptr1 ) );          /* null pointer */
    VERIFY( NumViolations == ++violations );

    VERIFY( NULL == wcstok_s( str3, NULL, L"?", &ptr1 ) );
    VERIFY( NumViolations == ++violations );

    VERIFY( NULL == wcstok_s( str3, &max3, NULL, &ptr1 ) );
    VERIFY( NumViolations == ++violations );

    VERIFY( NULL == wcstok_s( str3, &max3, L"?", NULL ) );
    VERIFY( NumViolations == ++violations );

    ptr3 = NULL;
    VERIFY( NULL == wcstok_s( NULL, &max3, L"?", &ptr3 ) );
    VERIFY( NumViolations == ++violations );

#if RSIZE_MAX != SIZE_MAX
    max1 = ~0;
    VERIFY( NULL == wcstok_s( str3, &max1, L"?", &ptr1 ) );
    VERIFY( NumViolations == ++violations );
#endif
}
BOOL CViewReport::OnInitDialog()
{
  std::vector<UINT> vibottombtns;
  vibottombtns.push_back(IDOK);
  vibottombtns.push_back(IDC_REPORT2CLIPBOARD);
  vibottombtns.push_back(IDCANCEL);

  AddMainCtrlID(IDC_EDITREPORT);
  AddBtnsCtrlIDs(vibottombtns, 2);

  UINT statustext[1] = {IDS_BLANK};
  SetStatusBar(&statustext[0], 1, false);

  CPWResizeDialog::OnInitDialog();

  if (GetParent() == NULL)
    GetDlgItem(IDC_REPORT2CLIPBOARD)->EnableWindow(FALSE);

  // Get new edit string (as per MS doc.)
  HLOCAL h = ::LocalAlloc(LHND, m_dwDatasize + sizeof(wchar_t));
  if (h == NULL) {
    pws_os::Trace(L"ViewReport: Unable to allocate memory.  Can't do this properly!\n");
    m_editreport.SetWindowText(m_pString.c_str());
    return FALSE;
  }
  m_bMemoryAllocOK = true;

  LPCWSTR lpszText = (LPCWSTR)::LocalLock(h);
  memcpy((void *)lpszText, m_pString.c_str(), m_dwDatasize);

  // Now work out maximum size of dialog
  CClientDC dc(GetDlgItem(IDC_EDITREPORT));

  //get the size of the text
  CRect textRect(0, 0, 32767, 32767);
  CFont *pOldFont = dc.SelectObject(m_editreport.GetFont());

  // Get Height
  dc.DrawText(lpszText, (int)m_pString.length(), &textRect, DT_CALCRECT | DT_NOCLIP);

  // Get width of longest line - ignores tabs - but no issue as edit control has
  // horizontal scroll bars
  wchar_t pSeps[] = L"\r\n";
  int iMaxWidth(-1);
  // Capture individual lines:
  wchar_t *next_token;
  wchar_t *token = wcstok_s((LPWSTR)lpszText, pSeps, &next_token);
  while(token) {
    CSize sz = dc.GetTextExtent(token, (int)wcslen(token));
    if (sz.cx > iMaxWidth)
      iMaxWidth = sz.cx;
    token = wcstok_s(NULL, pSeps, &next_token);
  }

  dc.SelectObject(pOldFont);

  //get the size of the edit control and the dialog
  CRect editRect, dlgRect;
  m_editreport.GetClientRect(&editRect);
  GetClientRect(&dlgRect);

  // Get height and width of characters
  TEXTMETRIC tm;
  dc.GetTextMetrics(&tm);

  // Set size based on current size (add spare in case)
  int iAdditionalHeight(0), iAdditionalWidth(0);
  if (iMaxWidth > editRect.Width())
    iAdditionalWidth = (iMaxWidth - editRect.Width()) + 2 * tm.tmMaxCharWidth;
  if (textRect.Height() > editRect.Height())
    iAdditionalHeight = (textRect.Height() - editRect.Height()) + 2 * tm.tmHeight;

  // Set it
  SetMaxHeightWidth(dlgRect.Height() + iAdditionalHeight, 
                    dlgRect.Width()  + iAdditionalWidth);

  // Refresh data as _wcstok trashes it!
  memcpy((void *)lpszText, m_pString.c_str(), m_dwDatasize);
  ::LocalUnlock(h);

  // Free original handle
  ::LocalFree(m_editreport.GetHandle());
  // Set ours
  m_editreport.SetHandle(h);

  return FALSE;
}
bool CPluginFilter::IsElementHidden(const std::wstring& tag, IHTMLElement* pEl, const std::wstring& domain, const std::wstring& indent) const
{
  std::wstring id;
  CComBSTR idBstr;
  if (SUCCEEDED(pEl->get_id(&idBstr)) && idBstr)
  {
    id = ToWstring(idBstr);
  }
  std::wstring classNames;
  CComBSTR classNamesBstr;
  if (SUCCEEDED(pEl->get_className(&classNamesBstr)) && classNamesBstr)
  {
    classNames = ToWstring(classNamesBstr);
  }

  CriticalSection::Lock filterEngineLock(s_criticalSectionFilterMap);
  {
    // Search tag/id filters
    if (!id.empty())
    {
      auto idItEnum = m_elementHideTagsId.equal_range(std::make_pair(tag, id));
      for (auto idIt = idItEnum.first; idIt != idItEnum.second; ++idIt)
      {
        if (idIt->second.IsMatchFilterElementHide(pEl))
        {
#ifdef ENABLE_DEBUG_RESULT
          DEBUG_HIDE_EL(indent + L"HideEl::Found (tag/id) filter:" + idIt->second.m_filterText);
          CPluginDebug::DebugResultHiding(tag, L"id:" + id, idIt->second.m_filterText);
#endif
          return true;
        }
      }

      // Search general id
      idItEnum = m_elementHideTagsId.equal_range(std::make_pair(L"", id));
      for (auto idIt = idItEnum.first; idIt != idItEnum.second; ++idIt)
      {
        if (idIt->second.IsMatchFilterElementHide(pEl))
        {
#ifdef ENABLE_DEBUG_RESULT
          DEBUG_HIDE_EL(indent + L"HideEl::Found (?/id) filter:" + idIt->second.m_filterText);
          CPluginDebug::DebugResultHiding(tag, L"id:" + id, idIt->second.m_filterText);
#endif
          return true;
        }
      }
    }

    // Search tag/className filters
    if (!classNames.empty())
    {
      wchar_t* nextToken = nullptr;
      const wchar_t* token = wcstok_s(&classNames[0], L" \t\n\r", &nextToken);
      while (token != nullptr)
      {
        std::wstring className(token);
        auto classItEnum = m_elementHideTagsClass.equal_range(std::make_pair(tag, className));
        for (auto classIt = classItEnum.first; classIt != classItEnum.second; ++classIt)
        {
          if (classIt->second.IsMatchFilterElementHide(pEl))
          {
#ifdef ENABLE_DEBUG_RESULT
            DEBUG_HIDE_EL(indent + L"HideEl::Found (tag/class) filter:" + classIt->second.m_filterText);
            CPluginDebug::DebugResultHiding(tag, L"class:" + className, classIt->second.m_filterText);
#endif
            return true;
          }
        }

        // Search general class name
        classItEnum = m_elementHideTagsClass.equal_range(std::make_pair(L"", className));
        for (auto classIt = classItEnum.first; classIt != classItEnum.second; ++ classIt)
        {
          if (classIt->second.IsMatchFilterElementHide(pEl))
          {
#ifdef ENABLE_DEBUG_RESULT
            DEBUG_HIDE_EL(indent + L"HideEl::Found (?/class) filter:" + classIt->second.m_filterText);
            CPluginDebug::DebugResultHiding(tag, L"class:" + className, classIt->second.m_filterText);
#endif
            return true;
          }
        }
        token = wcstok_s(nullptr, L" \t\n\r", &nextToken);
      }
    }

    // Search tag filters
    auto tagItEnum = m_elementHideTags.equal_range(tag);
    for (auto tagIt = tagItEnum.first; tagIt != tagItEnum.second; ++tagIt)
    {
      if (tagIt->second.IsMatchFilterElementHide(pEl))
      {
#ifdef ENABLE_DEBUG_RESULT
        DEBUG_HIDE_EL(indent + L"HideEl::Found (tag) filter:" + tagIt->second.m_filterText);
        CPluginDebug::DebugResultHiding(tag, L"-", tagIt->second.m_filterText);
#endif
        return true;
      }
    }
  }

  return false;
}
static ErrNo GetMatrix(const HWND hwndEdit,double **pMatrix,const int nRows,const int nColumns)
{
	TCHAR	szBuffer_t[MAXSIZE];
	bool	data = false;
	TCHAR	seps[] = TEXT(" \t");
	TCHAR	*ptemp,*pstr,*pnext_token = NULL,*szBuffer = NULL;
	int		iLine,iLength,iStart,iCount;
	int		iMax = nColumns*20;							//缺憾 获取数据还是有限定的 每行字符个数不能超过iMax个

	szBuffer = new TCHAR[iMax];		//存储每一行获得的字符

	iLine = Edit_GetLineCount(hwndEdit);
	if(iLine == 1)											 //判断是否没有输入数据
	{
		if(!(iLength = Edit_GetText(hwndEdit,szBuffer,iMax)))
		{
			return NO_DATA_INPUT;
		}
	}
	else if(iLine<nRows)
	{
		return WRONG_MATRIX;
	}

	data = false;
	for(int i=0;i<iLine;i++)
	{
		iLength = Edit_GetLine(hwndEdit,i,szBuffer_t,MAXSIZE);
		if(iLength)				//找出第一个有数据的行
		{
			for(int j=0;j<iLength;j++)
			{
				if((szBuffer_t[j] >= TEXT('0') && szBuffer_t[j] <= TEXT('9')) || szBuffer_t[j] == TEXT('.'))
				{
					iStart = i;
					data = true;
					break;
				}
			}
			if(data)
				break;
		}
	}

	for(int i=iStart,k=0;i<iStart+nRows;i++,k++)			//获取每行数据
	{
		iCount = 0;
		iLength = Edit_GetLine(hwndEdit,i,szBuffer,iMax-1);
		szBuffer[iLength]=TEXT('\0');
		//字符串分割
		pstr = wcstok_s(szBuffer,seps,&pnext_token);
		while(pstr!=NULL)
		{
			if(*pstr == TEXT('+'))								//判断是否有分割行							
				return WRONG_MATRIX;	
			else if(!CharacterJudgement(pstr))					//判断是否非法字符输入
				return INCORRECT_DATA;
			if(iCount >= nColumns)								//判断每行输入数据个数是否超出限定矩阵维数
				return WRONG_MATRIX;
			pMatrix[k][iCount] = wcstod(pstr,&ptemp);
			pstr = wcstok_s(NULL,seps,&pnext_token);
			iCount++;
		}
		if(iCount != nColumns)
			return WRONG_MATRIX;
	}

	delete szBuffer;
	szBuffer = NULL;
	return 0;
}
Exemple #22
0
// Parse the command line for the parameters
// Only parameters that are specified on the command line are updated, if there
// are no parameters for a value, the previous WindowParams settings passed in
// are preserved
//-----------------------------------------------------------------------------
CPUTResult CPUT_DX11::CPUTParseCommandLine(cString commandLine, CPUTWindowCreationParams *pWindowParams, cString *pFilename)
{
    ASSERT( (NULL!=pWindowParams), _L("Required command line parsing parameter is NULL"));
    ASSERT( (NULL!=pFilename), _L("Required command line parsing parameter is NULL"));
   
    // there are no command line parameters, just return
    if(0==commandLine.size())
    {
        return CPUT_SUCCESS;
    }

    // we do have parameters, so parse them.
#if defined (UNICODE) || defined(_UNICODE)
    // convert command line to lowercase version
    cString CommandLineParams(commandLine);        
    std::transform(CommandLineParams.begin(), CommandLineParams.end(), CommandLineParams.begin(), ::tolower);

    // special case - double-clicked on a file
    // In the case someone has associated .set files with CPUT, then the target set file comes in surrounded
    // by quote marks (i.e. "c:\SoftwareOcclusionCulling\Asset\City.set").  If the first char is a quote mark, we're in this
    // special case
    if('"' == CommandLineParams[0])
    {
        pFilename->assign(&CommandLineParams[1]);   // remove the leading " char
        (*pFilename)[pFilename->size()-1] = '\0';   // remove the trailing " char
        return CPUT_SUCCESS;
    }

    wchar_t separators[]   = L" \t\n";
    wchar_t* nextToken = NULL;
    wchar_t* token = wcstok_s((wchar_t*)CommandLineParams.c_str(), separators, &nextToken);
    while(token) 
    {
        if('-' == token[0])
        {
            // parameter - get next token for which one
            cString ParameterName(&token[1]);
            if(0!=ParameterName.size())
            {
                if(0==ParameterName.compare(_L("width")))
                {
                    // get the next value
                    token = wcstok_s(NULL, separators, &nextToken); 
                    ASSERT(token, _L("-width command line parameter missing required numerical value"));
                    pWindowParams->windowWidth = _wtoi(token);
                }
                else if(0==ParameterName.compare(_L("height")))
                {
                    // get the next value
                    token = wcstok_s(NULL, separators, &nextToken); 
                    ASSERT(token, _L("-height command line parameter missing required numerical value"));
                    pWindowParams->windowHeight = _wtoi(token);
                }
                else if(0==ParameterName.compare(_L("fullscreen")))
                {
                    // get the bool 
                    token = wcstok_s(NULL, separators, &nextToken); 
                    cString boolString(token);
                    if(0==boolString.compare(_L("true")))
                    {
                        pWindowParams->startFullscreen = true;
                    }
                }
                else if(0==ParameterName.compare(_L("vsync")))
                {
                    // get the bool 
                    token = wcstok_s(NULL, separators, &nextToken); 
                    cString boolString(token);
                    if( (0==boolString.compare(_L("on"))) || (0==boolString.compare(_L("true"))) )
                    {
                        // vsync set to 30 FPS
                        pWindowParams->deviceParams.refreshRate = 30;
                    }
                    if( (0==boolString.compare(_L("off"))) || (0==boolString.compare(_L("false"))) )
                    {
                        pWindowParams->deviceParams.refreshRate = 0;
                    }
                }
                else if(0==ParameterName.compare(_L("xpos")))
                {
                    // get the next value
                    token = wcstok_s(NULL, separators, &nextToken); 
                    ASSERT(token, _L("-xpos command line parameter missing required numerical value"));
                    pWindowParams->windowPositionX = _wtoi(token);
                }
                else if(0==ParameterName.compare(_L("ypos")))
                {
                    // get the next value
                    token = wcstok_s(NULL, separators, &nextToken); 
                    ASSERT(token, _L("-ypos command line parameter missing required numerical value"));
                    pWindowParams->windowPositionY = _wtoi(token);
                }
                else if(0==ParameterName.compare(_L("file")))
                {
                    // get the filename 
                    token = wcstok_s(NULL, separators, &nextToken);
                    pFilename->assign(token);
                }
                else
                {
                    // we don't know what the string was, but all specified ones should be of the form
                    // '-<keyword> <value>' 
                    // so skip over the <value> part
                    token = wcstok_s(NULL, separators, &nextToken); 
                }
                
                // we don't know what this parameter is, let user parse it
            }
        }
        
        // advance to next token
        token = wcstok_s(NULL, separators, &nextToken);
    }
#else
    ASSERT(false, _L("CPUT_DX11::CPUTParseCommandLine non-UNICODE version not written yet - need to write if we want to support multi-byte"));
#endif     
    
    return CPUT_SUCCESS;
}
Exemple #23
0
BOOL freerdp_client_parse_rdp_file_buffer_unicode(rdpFile* file, BYTE* buffer, size_t size)
{
    int length;
    WCHAR* line;
    WCHAR* type;
    WCHAR* context;
    WCHAR *d1, *d2;
    WCHAR *beg, *end;
    WCHAR *name, *value;

    line = wcstok_s((WCHAR*) buffer, CR_LF_STR_W, &context);

    while (line != NULL)
    {
        length = _wcslen(line);

        if (length > 1)
        {
            beg = line;
            end = &line[length - 1];

            if (beg[0] == '/')
            {
                /* FreeRDP option */
                freerdp_client_parse_rdp_file_option_unicode(file, line);
                goto next_line;
            }

            d1 = _wcschr(line, ':');

            if (!d1)
                goto next_line; /* not first delimiter */

            type = &d1[1];
            d2 = _wcschr(type, ':');

            if (!d2)
                goto next_line; /* no second delimiter */

            if ((d2 - d1) != 2)
                goto next_line; /* improper type length */

            if (d2 == end)
                goto next_line; /* no value */

            *d1 = 0;
            *d2 = 0;
            name = beg;
            value = &d2[1];

            if (*type == 'i')
            {
                /* integer type */
                freerdp_client_parse_rdp_file_integer_unicode(file, name, value);
            }
            else if (*type == 's')
            {
                /* string type */
                freerdp_client_parse_rdp_file_string_unicode(file, name, value);
            }
            else if (*type == 'b')
            {
                /* binary type */
            }
        }

next_line:
        line = wcstok_s(NULL, CR_LF_STR_W, &context);
    }

    return TRUE;
}
Exemple #24
0
STDMETHODIMP Profile::get_ForwardingRules(SAFEARRAY ** pVal)
{
	try {
		WCHAR * pResult = gSkypeQueue.RetrieveProperty(L"PROFILE", L"", L"CALL_FORWARD_RULES");
		size_t sz = wcslen(pResult) + 1;
		WCHAR * pCopy = new WCHAR[sz];

		long lTotal=0, lCtr=0;
		HRESULT hr;
		ForwardingRule * pItems;

		for(int i = 0; i < 2; i++) {
			wcscpy_s(pCopy, sz, pResult);
			WCHAR *next_token = NULL;
			WCHAR * pItem = wcstok_s(pCopy, L" ", &next_token);
			while(pItem != NULL) {
				size_t iLen = wcslen(pItem);
				if(iLen > 0) {
					LONG start;
					LONG end;
					WCHAR * name = new WCHAR[iLen];

					bool bValid = 
						swscanf_s(pItem, L"%d,%d,%s", & start, & end, name, iLen) == 3;

					if(bValid) {
						if(i == 0) {
							lTotal++;
						} else {
							pItems[lCtr].StartTime = start;
							pItems[lCtr].EndTime = end;
							pItems[lCtr].Handle = SysAllocString(name);
							lCtr++;
						}
					}

					delete(name);
				}
				pItem = wcstok_s(NULL, L" ", &next_token);
			}

			if(i == 0) {
				SAFEARRAYBOUND sba;
				sba.cElements = lTotal;
				sba.lLbound = 0;

				CComPtr<IRecordInfo> *ptrRecInfo;

				hr = GetRecordInfoFromGuids(CAtlModule::m_libid, 1, 0, 0x409,
					__uuidof(ForwardingRule), (IRecordInfo**) & ptrRecInfo);

				if(FAILED(hr)) {
					return AtlReportError(GetObjectCLSID(), L"Unable to retrieve structure info", GUID_NULL, E_FAIL);				
				}
					
				*pVal = SafeArrayCreateEx(VT_RECORD, 1, & sba, ptrRecInfo);
				if((*pVal) == NULL) {
					return AtlReportError(GetObjectCLSID(), L"Unable to create array", GUID_NULL, E_FAIL);
				}

				hr = SafeArrayLock(*pVal);
				if(FAILED(hr)) {
					return AtlReportError(GetObjectCLSID(), L"Unable to lock array", GUID_NULL, E_FAIL);
				}

				pItems = (ForwardingRule *) (*pVal)->pvData;

			} else {
				hr = SafeArrayUnlock(*pVal);
				if(FAILED(hr)) {
					return AtlReportError(GetObjectCLSID(), L"Unable to unlock array", GUID_NULL, E_FAIL);
				}
			}
		}

		free(pResult);
		return S_OK;
	} catch (const WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}

	return S_OK;
}
void GraphicsInterface::DisplayStatus(wstring wstrText, int display_time)
{
	GraphicsEngineOptions geo;
	RECT rcScreen;
	CMonitors cm;
	POINT pt = { 0, 0 };
	Color cNull = Color(0, 0, 0, 0);
	Color cTemp;
	Color cOutline;
	Color cDropShadow;
	REAL rTemp;

	if (!m_ssSettings.bVisualFeedback)
		return;

	if (m_ssSettings.bNoDisplayWhenActive && m_ITCom->IsActiveWindow())
		return;

	EnterCriticalSection(&_csCreateDisplay);
	_nDisplayType = 1;

	// Configure
	geo.nDisplayAlpha = m_ssSettings.nOSDAlpha;
	geo.bDisplayTopMost = m_ssSettings.bOSDTopMost;
	geo.nMaxWidth = m_ssSettings.nOSDMaxWidth;
	geo.nArtScaleMode = m_ssSettings.nArtMode == 3 ? ART_SCALEMODEHEIGHT : ART_SCALEMODESIZE;
	geo.saAlign = (Gdiplus::StringAlignment)m_ssSettings.nOSDTextJustify;
	geo.bForceToWidth = m_ssSettings.bOSDForceWidth;
	for (const auto& ge : _ges)
	{
		ge->SetOptions(geo);
		// Begin render process
		ge->BeginRender(5);
	}

		// Set background and borders
		rTemp = (REAL)m_ssSettings.nOSDBorderSize;
	cOutline = Color(GetRValue(m_ssSettings.lOSDBorderColor), GetGValue(m_ssSettings.lOSDBorderColor), GetBValue(m_ssSettings.lOSDBorderColor));
	cTemp = Color(GetRValue(m_ssSettings.lOSDBkColorRef), GetGValue(m_ssSettings.lOSDBkColorRef), GetBValue(m_ssSettings.lOSDBkColorRef));
	cDropShadow = Color(GetRValue(m_ssSettings.lDropShadowColor), GetGValue(m_ssSettings.lDropShadowColor), GetBValue(m_ssSettings.lDropShadowColor));
	for (const auto& ge : _ges)
	{
		ge->SetDisplayBorder(m_ssSettings.bOSDOutlineMode ? cNull : cOutline, rTemp);
		ge->SetDisplayBackground(m_ssSettings.bOSDOutlineMode ? cNull : cTemp);
	}

		// Cache text height for shapes
		REAL text_height = _ges.at(0)->GetTextHeight(m_ssSettings.wcFontFace, (float)m_ssSettings.nOSDFontPoint, m_ssSettings.nOSDFontStyle);

	// Break string into lines, add to display
	wchar_t *lpToken = NULL;
	wchar_t *lpContext = NULL;
	wchar_t *lpRating = NULL;
	wchar_t *lpVolume = NULL;
	wchar_t *lpBeforeRating = NULL;
	cTemp = Color(GetRValue(m_ssSettings.lOSDColorRef), GetGValue(m_ssSettings.lOSDColorRef), GetBValue(m_ssSettings.lOSDColorRef));
	Color cShapeFill = Color(GetRValue(m_ssSettings.lRatingShapeFill), GetGValue(m_ssSettings.lRatingShapeFill), GetBValue(m_ssSettings.lRatingShapeFill));
	Color cShapeOutline = Color(GetRValue(m_ssSettings.lRatingShapeOutline), GetGValue(m_ssSettings.lRatingShapeOutline), GetBValue(m_ssSettings.lRatingShapeOutline));
	lpToken = wcstok_s(const_cast<wchar_t*>(wstrText.c_str()), L"\n", &lpContext);
	while (NULL != lpToken && m_ssSettings.nDisplayLayout != 4)
	{
		for (const auto& ge : _ges)
		{
			ge->BeginLine();
		}
			// check for %rating% in string, replace with img rating
			lpRating = wcsstr(lpToken, L"%rating%");
		lpVolume = wcsstr(lpToken, L"%volume%");
		if (NULL != lpVolume)
		{
			// Break up line
			lpBeforeRating = new wchar_t[lpVolume - lpToken + 1];
			wcsncpy_s(lpBeforeRating, lpVolume - lpToken + 1, lpToken, lpVolume - lpToken);

			// Add text before rating
			for (const auto& ge : _ges)
			{
				ge->AddString(lpBeforeRating, false, m_ssSettings.nOSDFontStyle, (float)m_ssSettings.nOSDFontPoint,
					cTemp, m_ssSettings.wcFontFace, m_ssSettings.bOSDOutlineMode ? cOutline : cNull, 1.5f,
					m_ssSettings.bUseDropShadow ? m_ssSettings.fDropShadowOffset : 0.0f, cDropShadow);
			}

				// Add rating
				unsigned int lVolume = m_ITCom->GetVolumeLevel();

			RectF rfShape = RectF(0, 0, text_height*10.0f, text_height*1.5f);
			for (const auto& ge : _ges)
			{
				ge->AddShape(ShapeVolume, FillCustom, rfShape, false, cShapeOutline, 3.0, cShapeFill, lVolume);
				// Add text after rating
				ge->AddString(lpVolume + 8, false, m_ssSettings.nOSDFontStyle, (float)m_ssSettings.nOSDFontPoint,
					cTemp, m_ssSettings.wcFontFace, m_ssSettings.bOSDOutlineMode ? cOutline : cNull, 1.5f,
					m_ssSettings.bUseDropShadow ? m_ssSettings.fDropShadowOffset : 0.0f, cDropShadow);
			}

				delete[] lpBeforeRating;
		}
		else if (NULL != lpRating)
		{
			// Break up line
			lpBeforeRating = new wchar_t[lpRating - lpToken + 1];
			wcsncpy_s(lpBeforeRating, lpRating - lpToken + 1, lpToken, lpRating - lpToken);

			// Add text before rating
			for (const auto& ge : _ges)
			{
				ge->AddString(lpBeforeRating, false, m_ssSettings.nOSDFontStyle, (float)m_ssSettings.nOSDFontPoint,
					cTemp, m_ssSettings.wcFontFace, m_ssSettings.bOSDOutlineMode ? cOutline : cNull, 1.5f,
					m_ssSettings.bUseDropShadow ? m_ssSettings.fDropShadowOffset : 0.0f, cDropShadow);
			}

				// Add rating
				long lRating = m_ITCom->GetTrackRating();
			long lWhole = (lRating - (lRating % 20)) / 20;
			lRating = lRating - lWhole * 20;
			long lHalf = (lRating - (lRating % 10)) / 10;
			long lEmpty = 5 - lWhole - lHalf;

			RectF rfShape = RectF(0, 0, text_height, text_height);
			for (int i = 0; i < lWhole; i++)
			{
				for (const auto& ge : _ges)
				{
					if (m_ssSettings.nRatingType == 1)
						ge->AddImage(m_ssSettings.wcRatingFullPath);
					else
						ge->AddShape((ShapeType)m_ssSettings.nRatingShapeType, FillAll, rfShape, false, cShapeOutline, 3.0, cShapeFill);
				}
			}
			for (int i = 0; i < lHalf; i++)
			{
				for (const auto& ge : _ges)
				{
					if (m_ssSettings.nRatingType == 1)
						ge->AddImage(m_ssSettings.wcRatingHalfPath);
					else
						ge->AddShape((ShapeType)m_ssSettings.nRatingShapeType, (ShapeStyle)(m_ssSettings.nRatingShapeStyle + 2), rfShape, false, cShapeOutline, 3.0, cShapeFill);
				}
			}
			for (int i = 0; i < lEmpty; i++)
			{
				for (const auto& ge : _ges)
				{
					if (m_ssSettings.nRatingType == 1)
						ge->AddImage(m_ssSettings.wcRatingEmptyPath);
					else
						ge->AddShape((ShapeType)m_ssSettings.nRatingShapeType, FillNone, rfShape, false, cShapeOutline, 3.0, cShapeFill);
				}
			}

			// Add text after rating
			for (const auto& ge : _ges)
			{
				ge->AddString(lpRating + 8, false, m_ssSettings.nOSDFontStyle, (float)m_ssSettings.nOSDFontPoint,
					cTemp, m_ssSettings.wcFontFace, m_ssSettings.bOSDOutlineMode ? cOutline : cNull, 1.5f,
					m_ssSettings.bUseDropShadow ? m_ssSettings.fDropShadowOffset : 0.0f, cDropShadow);
			}

				delete[] lpBeforeRating;
		}
		else
		{
			for (const auto& ge : _ges)
			{
				ge->AddString(lpToken, false, m_ssSettings.nOSDFontStyle, (float)m_ssSettings.nOSDFontPoint,
					cTemp, m_ssSettings.wcFontFace, m_ssSettings.bOSDOutlineMode ? cOutline : cNull, 1.5f,
					m_ssSettings.bUseDropShadow ? m_ssSettings.fDropShadowOffset : 0.0f, cDropShadow);
			}
		}

		for (const auto& ge : _ges)
		{
			ge->EndLine();
		}

			lpToken = wcstok_s(NULL, L"\n", &lpContext);
	}

	// Position display
	if (!cm.GetMonitorRect(m_ssSettings.nOSDMonitor, rcScreen))
		SystemParametersInfo(SPI_GETWORKAREA, 0, &rcScreen, 0);

	pt.x = rcScreen.left + (LONG)ceilf((m_ssSettings.nOSDHoriz / 100.0f) * (rcScreen.right - rcScreen.left));
	pt.y = rcScreen.top + (LONG)ceilf((m_ssSettings.nOSDVert / 100.0f) * (rcScreen.bottom - rcScreen.top));

	// Show display, start timer
	if (m_ssSettings.bOSDAllMonitors)
	{
		int monitor = 1;

		for (const auto& ge : _ges)
		{
			// Position display
			cm.GetMonitorRect(monitor, rcScreen);

			pt.x = rcScreen.left + (LONG)ceilf((m_ssSettings.nOSDHoriz / 100.0f) * (rcScreen.right - rcScreen.left));
			pt.y = rcScreen.top + (LONG)ceilf((m_ssSettings.nOSDVert / 100.0f) * (rcScreen.bottom - rcScreen.top));

			ge->EndRender(pt, rcScreen);

			++monitor;
		}
	}
	else
	{
		for (const auto& ge : _ges)
		{
			ge->EndRender(pt, rcScreen);
		}
	}

	// Display should be shown for xx seconds, then hidden
	if (NULL != _hDisplayTimer)
		DeleteTimerQueueTimer(_hTimerQueue, _hDisplayTimer, INVALID_HANDLE_VALUE);
	_hDisplayTimer = NULL;
	CreateTimerQueueTimer(&_hDisplayTimer, _hTimerQueue, DisplayTimerCallback, (PVOID)this, display_time, 0, WT_EXECUTEDEFAULT | WT_EXECUTEONLYONCE);

	DisplayShow();

	LeaveCriticalSection(&_csCreateDisplay);

	return;
}
HTTPAPI_RESULT HTTPAPI_ExecuteRequest(HTTP_HANDLE handle, HTTPAPI_REQUEST_TYPE requestType, const char* relativePath,
    HTTP_HEADERS_HANDLE httpHeadersHandle, const unsigned char* content,
    size_t contentLength, unsigned int* statusCode,
    HTTP_HEADERS_HANDLE responseHeadersHandle, BUFFER_HANDLE responseContent)
{
    HTTPAPI_RESULT result;
    HTTP_HANDLE_DATA* handleData = (HTTP_HANDLE_DATA*)handle;

    if ((handleData == NULL) ||
        (relativePath == NULL) ||
        (httpHeadersHandle == NULL))
    {
        result = HTTPAPI_INVALID_ARG;
        LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
    }
    else
    {
        wchar_t* requestTypeString = NULL;

        switch (requestType)
        {
        default:
            break;

        case HTTPAPI_REQUEST_GET:
            requestTypeString = L"GET";
            break;

        case HTTPAPI_REQUEST_POST:
            requestTypeString = L"POST";
            break;

        case HTTPAPI_REQUEST_PUT:
            requestTypeString = L"PUT";
            break;

        case HTTPAPI_REQUEST_DELETE:
            requestTypeString = L"DELETE";
            break;

        case HTTPAPI_REQUEST_PATCH:
            requestTypeString = L"PATCH";
            break;
        }

        if (requestTypeString == NULL)
        {
            result = HTTPAPI_INVALID_ARG;
            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
        }
        else
        {
            wchar_t relativePathTemp[1024];
            char headers[1024];
            wchar_t headersTemp[1024];

            result = ConstructHeadersString(httpHeadersHandle, headers, sizeof(headers));
            if (result == HTTPAPI_OK)
            {
                if (MultiByteToWideChar(CP_ACP, 0, relativePath, -1, relativePathTemp, sizeof(relativePathTemp) / sizeof(relativePathTemp[0])) == 0)
                {
                    result = HTTPAPI_STRING_PROCESSING_ERROR;
                    LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                }
                else
                {
                    if (MultiByteToWideChar(CP_ACP, 0, headers, -1, headersTemp, sizeof(headersTemp) / sizeof(headersTemp[0])) == 0)
                    {
                        result = HTTPAPI_STRING_PROCESSING_ERROR;
                        LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                    }
                    else
                    {
                        PCWSTR rgpszAcceptTypes[] = { L"text/*", NULL };
                        HINTERNET requestHandle = HttpOpenRequestW(
                            handleData->ConnectionHandle,
                            requestTypeString,
                            relativePathTemp,
                            NULL,
                            NULL,
                            rgpszAcceptTypes,
                            INTERNET_FLAG_SECURE,
                            0);
                        if (requestHandle == NULL)
                        {
                            result = HTTPAPI_OPEN_REQUEST_FAILED;
                            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                        }
                        else
                        {
                            unsigned long int timeout = 55000;
                            if (!InternetSetOption(
                                requestHandle,
                                INTERNET_OPTION_RECEIVE_TIMEOUT, /*Sets or retrieves an unsigned long integer value that contains the time-out value, in milliseconds, to receive a response to a request.*/
                                &timeout,
                                sizeof(timeout)))
                            {
                                result = HTTPAPI_SET_TIMEOUTS_FAILED;
                                LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                            }
                            else
                            {
                                DWORD dwSecurityFlags = 0;
                                if (!InternetSetOption(
                                    requestHandle,
                                    INTERNET_OPTION_SECURITY_FLAGS,
                                    &dwSecurityFlags,
                                    sizeof(dwSecurityFlags)))
                                {
                                    result = HTTPAPI_SET_OPTION_FAILED;
                                    LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                }
                                else
                                {
                                    if (!HttpSendRequestW(
                                        requestHandle,
                                        headersTemp,
                                        -1,
                                        (void*)content,
                                        contentLength))
                                    {
                                        result = HTTPAPI_SEND_REQUEST_FAILED;
LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                    }
                                    else
                                    {
                                        DWORD dwStatusCode = 0;
                                        DWORD dwBufferLength = sizeof(DWORD);
                                        DWORD responseBytesAvailable;

                                        if (responseHeadersHandle != NULL)
                                        {
                                            wchar_t responseHeadersTemp[16384];
                                            DWORD responseHeadersTempLength = sizeof(responseHeadersTemp);

                                            if (HttpQueryInfo(
                                                requestHandle,
                                                HTTP_QUERY_RAW_HEADERS_CRLF,
                                                responseHeadersTemp,
                                                &responseHeadersTempLength,
                                                0))
                                            {
                                                wchar_t *next_token;
                                                wchar_t* token = wcstok_s(responseHeadersTemp, L"\r\n", &next_token);
                                                while ((token != NULL) &&
                                                    (token[0] != L'\0'))
                                                {
                                                    char tokenTemp[1024];

                                                    if (WideCharToMultiByte(CP_ACP, 0, token, -1, tokenTemp, sizeof(tokenTemp), NULL, NULL) > 0)
                                                    {
                                                        /*breaking the token in 2 parts: everything before the first ":" and everything after the first ":"*/
                                                        /* if there is no such character, then skip it*/
                                                        /*if there is a : then replace is by a '\0' and so it breaks the original string in name and value*/

                                                        char* whereIsColon = strchr(tokenTemp, ':');
                                                        if (whereIsColon != NULL)
                                                        {
                                                            *whereIsColon = '\0';
                                                            HTTPHeaders_AddHeaderNameValuePair(responseHeadersHandle, tokenTemp, whereIsColon + 1);
                                                        }
                                                    }
                                                    token = wcstok_s(NULL, L"\r\n", &next_token);
                                                }
                                            }
                                        }

                                        if (!HttpQueryInfo(
                                            requestHandle,
                                            HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
                                            &dwStatusCode,
                                            &dwBufferLength,
                                            0))
                                        {
                                            result = HTTPAPI_QUERY_HEADERS_FAILED;
                                            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                        }
                                        else
                                        {
                                            BUFFER_HANDLE useToReadAllResponse = (responseContent != NULL) ? responseContent : BUFFER_new();
                                            /*HTTP status code (dwStatusCode) can be either ok (<HTTP_STATUS_AMBIGUOUS) or "not ok (>=HTTP_STATUS_AMBIGUOUS)*/
                                            if (useToReadAllResponse == NULL)
                                            {
                                                result = HTTPAPI_ERROR;
                                                LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                            }
                                            else
                                            {
                                                int goOnAndReadEverything = 1;
                                                /*set the response code*/
                                                if (statusCode != NULL)
                                                {
                                                    *statusCode = dwStatusCode;
                                                }

                                                do
                                                {
                                                    /*from MSDN:  If there is currently no data available and the end of the file has not been reached, the request waits until data becomes available*/
                                                    if (!InternetQueryDataAvailable(requestHandle, &responseBytesAvailable, 0, 0))
                                                    {
                                                        result = HTTPAPI_QUERY_DATA_AVAILABLE_FAILED;
                                                        LogError("InternetQueryDataAvailable failed (result = %s) GetLastError = %d\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result), GetLastError());
                                                        goOnAndReadEverything = 0;
                                                    }
                                                    else if (responseBytesAvailable == 0)
                                                    {
                                                        /*end of the stream, go out*/
                                                        if (dwStatusCode >= HTTP_STATUS_AMBIGUOUS)
                                                        {
                                                            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                        }

                                                        result = HTTPAPI_OK;
                                                        goOnAndReadEverything = 0;
                                                    }
                                                    else
                                                    {
                                                        /*add the needed space to the buffer*/
                                                        if (BUFFER_enlarge(useToReadAllResponse, responseBytesAvailable) != 0)
                                                        {
                                                            result = HTTPAPI_ERROR;
                                                            LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                            goOnAndReadEverything = 0;
                                                        }
                                                        else
                                                        {
                                                            unsigned char* bufferContent;
                                                            size_t bufferSize;
                                                            /*add the data to the buffer*/
                                                            if (BUFFER_content(useToReadAllResponse, &bufferContent) != 0)
                                                            {
                                                                result = HTTPAPI_ERROR;
                                                                LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                goOnAndReadEverything = 0;
                                                            }
                                                            else if (BUFFER_size(useToReadAllResponse, &bufferSize) != 0)
                                                            {
                                                                result = HTTPAPI_ERROR;
                                                                LogError("(result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                goOnAndReadEverything = 0;
                                                            }
                                                            else
                                                            {
                                                                DWORD bytesReceived;
                                                                if (!InternetReadFile(requestHandle, bufferContent + bufferSize - responseBytesAvailable, responseBytesAvailable, &bytesReceived))
                                                                {
                                                                    result = HTTPAPI_READ_DATA_FAILED;
                                                                    LogError("InternetReadFile failed (result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                    goOnAndReadEverything = 0;
                                                                }
                                                                else
                                                                {
                                                                    /*if for some reason bytesReceived is zero, MSDN says To ensure all data is retrieved, an application must continue to call the InternetReadFile function until the function returns TRUE and the lpdwNumberOfBytesRead parameter equals zero*/
                                                                    if (bytesReceived == 0)
                                                                    {
                                                                        /*end of everything, but this looks like an error still, or a non-conformance between InternetQueryDataAvailable and InternetReadFile*/
                                                                        result = HTTPAPI_READ_DATA_FAILED;
                                                                        LogError("InternetReadFile failed (result = %s)\r\n", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                        goOnAndReadEverything = 0;
                                                                    }
                                                                    else
                                                                    {
                                                                        /*all is fine, keep going*/
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                } while (goOnAndReadEverything != 0);

                                                if (responseContent == NULL)
                                                {
                                                    BUFFER_delete(useToReadAllResponse);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            (void)InternetCloseHandle(requestHandle);
                        }
                    }
                }
            }
        }
    }

    return result;
}
void MultiFace::ParseCmdString(PWSTR lpCmdLine)
{
    const WCHAR KEY_USERS[]                                 = L"-Users";
    const WCHAR KEY_DEPTH[]                                 = L"-Depth";
    const WCHAR KEY_COLOR[]                                 = L"-Color";
    const WCHAR KEY_NEAR_MODE[]                             = L"-NearMode";
    const WCHAR KEY_SEATED_SKELETON_MODE[]                  = L"-SeatedSkeleton";

    const WCHAR STR_NUI_IMAGE_TYPE_DEPTH[]                  = L"DEPTH";
    const WCHAR STR_NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX[] = L"PLAYERID";
    const WCHAR STR_NUI_IMAGE_TYPE_COLOR[]                  = L"RGB";
    const WCHAR STR_NUI_IMAGE_TYPE_COLOR_YUV[]              = L"YUV";

    const WCHAR STR_NUI_IMAGE_RESOLUTION_80x60[]            = L"80x60";
    const WCHAR STR_NUI_IMAGE_RESOLUTION_320x240[]          = L"320x240";
    const WCHAR STR_NUI_IMAGE_RESOLUTION_640x480[]          = L"640x480";
    const WCHAR STR_NUI_IMAGE_RESOLUTION_1280x960[]         = L"1280x960";

    enum TOKEN_ENUM
    {
        TOKEN_ERROR,
        TOKEN_USERS,
        TOKEN_DEPTH,
        TOKEN_COLOR,
        TOKEN_NEARMODE,
		TOKEN_SEATEDSKELETON
    }; 

    int argc = 0;
    LPWSTR *argv = CommandLineToArgvW(lpCmdLine, &argc);

    for(int i = 0; i < argc; i++)
    {
        NUI_IMAGE_TYPE* pType = NULL;
        NUI_IMAGE_RESOLUTION* pRes = NULL;

        TOKEN_ENUM tokenType = TOKEN_ERROR; 
        PWCHAR context = NULL;
        PWCHAR token = wcstok_s(argv[i], L":", &context);
        if(0 == wcsncmp(token, KEY_DEPTH, ARRAYSIZE(KEY_DEPTH)))
        {
            tokenType = TOKEN_DEPTH;
            pType = &m_depthType;
            pRes = &m_depthRes;
        }
        else if(0 == wcsncmp(token, KEY_USERS, ARRAYSIZE(KEY_USERS)))
        {
            tokenType = TOKEN_USERS;
        }
        else if(0 == wcsncmp(token, KEY_COLOR, ARRAYSIZE(KEY_COLOR)))
        {
            tokenType = TOKEN_COLOR;
            pType = &m_colorType;
            pRes = &m_colorRes;
        }
        else if(0 == wcsncmp(token, KEY_NEAR_MODE, ARRAYSIZE(KEY_NEAR_MODE)))
        {
            tokenType = TOKEN_NEARMODE;
            m_bNearMode = TRUE;
        }
        else if(0 == wcsncmp(token, KEY_SEATED_SKELETON_MODE, ARRAYSIZE(KEY_NEAR_MODE)))
        {
            tokenType = TOKEN_SEATEDSKELETON;
            m_bSeatedSkeletonMode = TRUE;
        }

        if(tokenType == TOKEN_USERS)
        {
            while((token = wcstok_s(NULL, L":", &context)) != NULL)
            {
                UINT users = _wtoi(token);
                if(users > m_nbUsers)
                {
                    m_nbUsers = users;
                    break;
                }
            }
        }
        else if(tokenType == TOKEN_DEPTH || tokenType == TOKEN_COLOR)
        {
            _ASSERT(pType != NULL && pRes != NULL);

            while((token = wcstok_s(NULL, L":", &context)) != NULL)
            {
                if(0 == wcsncmp(token, STR_NUI_IMAGE_TYPE_DEPTH, ARRAYSIZE(STR_NUI_IMAGE_TYPE_DEPTH)))
                {
                    *pType = NUI_IMAGE_TYPE_DEPTH;
                }
                else if(0 == wcsncmp(token, STR_NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX, ARRAYSIZE(STR_NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX)))
                {
                    *pType = NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX;
                }
                else if(0 == wcsncmp(token, STR_NUI_IMAGE_TYPE_COLOR, ARRAYSIZE(STR_NUI_IMAGE_TYPE_COLOR)))
                {
                    *pType = NUI_IMAGE_TYPE_COLOR;
                }
                else if(0 == wcsncmp(token, STR_NUI_IMAGE_TYPE_COLOR_YUV, ARRAYSIZE(STR_NUI_IMAGE_TYPE_COLOR_YUV)))
                {
                    *pType = NUI_IMAGE_TYPE_COLOR_YUV;
                }
                else if(0 == wcsncmp(token, STR_NUI_IMAGE_RESOLUTION_80x60, ARRAYSIZE(STR_NUI_IMAGE_RESOLUTION_80x60)))
                {
                    *pRes = NUI_IMAGE_RESOLUTION_80x60;
                }
                else if(0 == wcsncmp(token, STR_NUI_IMAGE_RESOLUTION_320x240, ARRAYSIZE(STR_NUI_IMAGE_RESOLUTION_320x240)))
                {
                    *pRes = NUI_IMAGE_RESOLUTION_320x240;
                }
                else if(0 == wcsncmp(token, STR_NUI_IMAGE_RESOLUTION_640x480, ARRAYSIZE(STR_NUI_IMAGE_RESOLUTION_640x480)))
                {
                    *pRes = NUI_IMAGE_RESOLUTION_640x480;
                }
                else if(0 == wcsncmp(token, STR_NUI_IMAGE_RESOLUTION_1280x960, ARRAYSIZE(STR_NUI_IMAGE_RESOLUTION_1280x960)))
                {
                    *pRes = NUI_IMAGE_RESOLUTION_1280x960;
                }
            }
        }
    }

    if(argv) LocalFree(argv);
}
void GraphicsInterface::DisplayInfo(wstring wstrText, bool bArtwork, wchar_t *wcArt, int display_time, bool bUpdateOnly)
{
	GraphicsEngineOptions geo;
	RECT rcScreen;
	CMonitors cm;
	POINT pt = { 0, 0 };
	Color cNull = Color(0, 0, 0, 0);
	Color cTemp;
	Color cOutline;
	Color cArtOutline;
	Color cDropShadow;
	REAL rTemp;

	if (!m_ssSettings.bVisualFeedback)
		return;

	if (m_ssSettings.bNoDisplayWhenActive && m_ITCom->IsActiveWindow())
		return;

	if (bUpdateOnly && (_nDisplayType == 1 || !IsDisplayVisible()))
		return;

	EnterCriticalSection(&_csCreateDisplay);
	_nDisplayType = 0;

	// Configure
	geo.nDisplayAlpha = m_ssSettings.nOSDAlpha;
	geo.bDisplayTopMost = m_ssSettings.bOSDTopMost;
	geo.nMaxWidth = m_ssSettings.nOSDMaxWidth;
	geo.nArtScaleMode = m_ssSettings.nArtMode == 3 ? ART_SCALEMODEHEIGHT : ART_SCALEMODESIZE;
	geo.saAlign = (Gdiplus::StringAlignment)m_ssSettings.nOSDTextJustify;
	geo.bForceToWidth = m_ssSettings.bOSDForceWidth;

	if (!bArtwork || NULL == wcArt || 0 == wcscmp(wcArt, L""))
	{
		for (const auto& ge : _ges)
		{
			ge->SetOptions(geo);
			ge->BeginRender(5);
		}
	}
	else
	{
		for (const auto& ge : _ges)
		{
			ge->SetOptions(geo);
			ge->BeginRender(m_ssSettings.nDisplayLayout);
		}
	}

	// Set background and borders
	rTemp = (REAL)m_ssSettings.nOSDBorderSize;
	cOutline = Color(GetRValue(m_ssSettings.lOSDBorderColor), GetGValue(m_ssSettings.lOSDBorderColor), GetBValue(m_ssSettings.lOSDBorderColor));
	cTemp = Color(GetRValue(m_ssSettings.lOSDBkColorRef), GetGValue(m_ssSettings.lOSDBkColorRef), GetBValue(m_ssSettings.lOSDBkColorRef));
	cDropShadow = Color(GetRValue(m_ssSettings.lDropShadowColor), GetGValue(m_ssSettings.lDropShadowColor), GetBValue(m_ssSettings.lDropShadowColor));
	cArtOutline = Color(GetRValue(m_ssSettings.lArtBorderColor), GetGValue(m_ssSettings.lArtBorderColor), GetBValue(m_ssSettings.lArtBorderColor));
	for (const auto& ge : _ges)
	{
		ge->SetDisplayBorder(m_ssSettings.bOSDOutlineMode ? cNull : cOutline, rTemp);
		ge->SetDisplayBackground(m_ssSettings.bOSDOutlineMode ? cNull : cTemp);
	}

		// Add album art if needed
		if (bArtwork && m_ssSettings.bShowArtwork)
		{
			for (const auto& ge : _ges)
			{
				ge->AddArt(wcArt, false, cArtOutline, 1.5f, (float)m_ssSettings.nArtConstSize, m_ssSettings.nArtMode == 3 ? IMG_SCALENONE : IMG_SCALEALL);
			}
		}

	// Cache text height for shapes
	static REAL text_height;
	if (!bUpdateOnly)
		text_height = _ges.at(0)->GetTextHeight(m_ssSettings.wcFontFace, (float)m_ssSettings.nOSDFontPoint, m_ssSettings.nOSDFontStyle);

	// Break string into lines, add to display
	wchar_t *lpToken = NULL;
	wchar_t *lpContext = NULL;
	std::wstring line;
	size_t current_position = 0;
	size_t next_rating = 0;
	size_t next_format = 0;
	int old_font_style = m_ssSettings.nOSDFontStyle;
	cTemp = Color(GetRValue(m_ssSettings.lOSDColorRef), GetGValue(m_ssSettings.lOSDColorRef), GetBValue(m_ssSettings.lOSDColorRef));
	Color cShapeFill = Color(GetRValue(m_ssSettings.lRatingShapeFill), GetGValue(m_ssSettings.lRatingShapeFill), GetBValue(m_ssSettings.lRatingShapeFill));
	Color cShapeOutline = Color(GetRValue(m_ssSettings.lRatingShapeOutline), GetGValue(m_ssSettings.lRatingShapeOutline), GetBValue(m_ssSettings.lRatingShapeOutline));
	lpToken = wcstok_s(const_cast<wchar_t*>(wstrText.c_str()), L"\n", &lpContext);

	while (NULL != lpToken && m_ssSettings.nDisplayLayout != 4)
	{
		for (const auto& ge : _ges)
		{
			ge->BeginLine();
		}

			line = lpToken;
		current_position = 0;
		do
		{
			next_rating = line.find(L"%rating%", current_position);
			next_format = line.find(L"<", current_position);

			if ((next_rating == std::wstring::npos && next_format != std::wstring::npos) ||
				(next_format != std::wstring::npos && next_rating != std::wstring::npos &&
					next_format < next_rating))
			{
				// format
				if ((next_format - current_position) > 0)
				{
					for (const auto& ge : _ges)
					{
						ge->AddString(line.substr(current_position, next_format - current_position).c_str(), false,
							m_ssSettings.nOSDFontStyle, (float)m_ssSettings.nOSDFontPoint, cTemp, m_ssSettings.wcFontFace,
							m_ssSettings.bOSDOutlineMode ? cOutline : cNull, 1.5f, m_ssSettings.bUseDropShadow ? m_ssSettings.fDropShadowOffset : 0.0f,
							cDropShadow);
					}
				}
				if (line.compare(next_format, 3, L"<b>") == 0)
				{
					m_ssSettings.nOSDFontStyle |= FontStyleBold;
					current_position = next_format + 3;
				}
				else if (line.compare(next_format, 3, L"<i>") == 0)
				{
					m_ssSettings.nOSDFontStyle |= FontStyleItalic;
					current_position = next_format + 3;
				}
				else if (line.compare(next_format, 4, L"</b>") == 0)
				{
					m_ssSettings.nOSDFontStyle &= ~FontStyleBold;
					current_position = next_format + 4;
				}
				else if (line.compare(next_format, 4, L"</i>") == 0)
				{
					m_ssSettings.nOSDFontStyle &= ~FontStyleItalic;
					current_position = next_format + 4;
				}
				else
				{
					for (const auto& ge : _ges)
					{
						ge->AddString(line.substr(next_format, 1).c_str(), false,
							m_ssSettings.nOSDFontStyle, (float)m_ssSettings.nOSDFontPoint, cTemp, m_ssSettings.wcFontFace,
							m_ssSettings.bOSDOutlineMode ? cOutline : cNull, 1.5f, m_ssSettings.bUseDropShadow ? m_ssSettings.fDropShadowOffset : 0.0f,
							cDropShadow);
					}
					current_position = next_format + 1;
				}
			}
			else if ((next_format == std::wstring::npos && next_rating != std::wstring::npos) ||
				(next_format != std::wstring::npos && next_rating != std::wstring::npos &&
					next_rating < next_format))
			{
				// rating
				if ((next_rating - current_position) > 0)
				{
					for (const auto& ge : _ges)
					{
						ge->AddString(line.substr(current_position, next_rating - current_position).c_str(), false,
							m_ssSettings.nOSDFontStyle, (float)m_ssSettings.nOSDFontPoint, cTemp, m_ssSettings.wcFontFace,
							m_ssSettings.bOSDOutlineMode ? cOutline : cNull, 1.5f, m_ssSettings.bUseDropShadow ? m_ssSettings.fDropShadowOffset : 0.0f,
							cDropShadow);
					}
				}

				// Add rating
				long lRating = m_ITCom->GetTrackRating();
				long lWhole = (lRating - (lRating % 20)) / 20;
				lRating = lRating - lWhole * 20;
				long lHalf = (lRating - (lRating % 10)) / 10;
				long lEmpty = 5 - lWhole - lHalf;

				RectF rfShape = RectF(0, 0, text_height, text_height);
				for (int i = 0; i < lWhole; i++)
				{
					for (const auto& ge : _ges)
					{
						if (m_ssSettings.nRatingType == 1)
							ge->AddImage(m_ssSettings.wcRatingFullPath);
						else
							ge->AddShape((ShapeType)m_ssSettings.nRatingShapeType, FillAll, rfShape, false, cShapeOutline, 3.0, cShapeFill);
					}
				}
				for (int i = 0; i < lHalf; i++)
				{
					for (const auto& ge : _ges)
					{
						if (m_ssSettings.nRatingType == 1)
							ge->AddImage(m_ssSettings.wcRatingHalfPath);
						else
							ge->AddShape((ShapeType)m_ssSettings.nRatingShapeType, (ShapeStyle)(m_ssSettings.nRatingShapeStyle + 2), rfShape, false, cShapeOutline, 3.0, cShapeFill);
					}
				}
				for (int i = 0; i < lEmpty; i++)
				{
					for (const auto& ge : _ges)
					{
						if (m_ssSettings.nRatingType == 1)
							ge->AddImage(m_ssSettings.wcRatingEmptyPath);
						else
							ge->AddShape((ShapeType)m_ssSettings.nRatingShapeType, FillNone, rfShape, false, cShapeOutline, 3.0, cShapeFill);
					}
				}

				current_position = next_rating + 8;
			}
			else
			{
				// no special processing needed
				if (line.substr(current_position, std::wstring::npos).length() > 0)
				{
					for (const auto& ge : _ges)
					{
						ge->AddString(line.substr(current_position, std::wstring::npos).c_str(), false,
							m_ssSettings.nOSDFontStyle, (float)m_ssSettings.nOSDFontPoint, cTemp, m_ssSettings.wcFontFace,
							m_ssSettings.bOSDOutlineMode ? cOutline : cNull, 1.5f, m_ssSettings.bUseDropShadow ? m_ssSettings.fDropShadowOffset : 0.0f,
							cDropShadow);
					}
				}
			}
		} while (next_format != std::wstring::npos || next_rating != std::wstring::npos);

		for (const auto& ge : _ges)
		{
			ge->EndLine();
		}

		lpToken = wcstok_s(NULL, L"\n", &lpContext);
	}

	// Restore font style
	m_ssSettings.nOSDFontStyle = old_font_style;

	// Show display, start timer
	if (_bmInfo)
	{
		delete _bmInfo;
		_bmInfo = NULL;
	}

	if (m_ssSettings.bOSDAllMonitors)
	{
		bool has_track_pos = (NULL != wcsstr(m_ssSettings.wcOSDFormat, L"%track_position%"));
		int monitor = 1;

		for (const auto& ge : _ges)
		{
			// Position display
			cm.GetMonitorRect(monitor, rcScreen);

			pt.x = rcScreen.left + (LONG)ceilf((m_ssSettings.nOSDHoriz / 100.0f) * (rcScreen.right - rcScreen.left));
			pt.y = rcScreen.top + (LONG)ceilf((m_ssSettings.nOSDVert / 100.0f) * (rcScreen.bottom - rcScreen.top));

			if (has_track_pos)
				ge->EndRender(pt, rcScreen);
			else
				ge->EndRender(pt, rcScreen, m_ssSettings.bOSDAlwaysUp, &_bmInfo);

			++monitor;
		}
	}
	else
	{
		// Position display
		if (!cm.GetMonitorRect(m_ssSettings.nOSDMonitor, rcScreen))
			SystemParametersInfo(SPI_GETWORKAREA, 0, &rcScreen, 0);

		pt.x = rcScreen.left + (LONG)ceilf((m_ssSettings.nOSDHoriz / 100.0f) * (rcScreen.right - rcScreen.left));
		pt.y = rcScreen.top + (LONG)ceilf((m_ssSettings.nOSDVert / 100.0f) * (rcScreen.bottom - rcScreen.top));

		if (NULL != wcsstr(m_ssSettings.wcOSDFormat, L"%track_position%"))
		{
			for (const auto& ge : _ges)
			{
				ge->EndRender(pt, rcScreen);
			}
		}
		else
		{
			for (const auto& ge : _ges)
			{
				ge->EndRender(pt, rcScreen, m_ssSettings.bOSDAlwaysUp, &_bmInfo);
			}
		}
	}

	// Display should be shown for xx seconds, then hidden
	if (!bUpdateOnly)
	{
		if (!m_ssSettings.bOSDAlwaysUp)
		{
			if (NULL != _hDisplayTimer)
				DeleteTimerQueueTimer(_hTimerQueue, _hDisplayTimer, INVALID_HANDLE_VALUE);
			_hDisplayTimer = NULL;
			CreateTimerQueueTimer(&_hDisplayTimer, _hTimerQueue, DisplayTimerCallback, (PVOID)this, display_time, 0, WT_EXECUTEDEFAULT | WT_EXECUTEONLYONCE);
		}


		DisplayShow();
	}

	LeaveCriticalSection(&_csCreateDisplay);

	return;
}
HRESULT TFunctionInstanceInfo::CreateInstance(
        __in GUID* pDeviceId,
        __in_opt TDeviceInfo* pDeviceInfo,
        __in SOCKADDR_STORAGE* pFromAddr,
        INT FromAddrLen,
        ULONG InterfaceIndex,
        __deref_out TFunctionInstanceInfo** ppFunctionInstanceInfo)
{
    HRESULT hr = S_OK;
    TFunctionInstanceInfo* pFunctionInstanceInfo = NULL;
    MIB_IPNET_ROW2 IpNetRow2 = {0};
    int err = 0;
    static const WCHAR szDelimeters[] = L" ,;";
    PWSTR pszToken = NULL;
    PWSTR pszNextToken = NULL;
    ULONG iCategoryIndex = 0;

    *ppFunctionInstanceInfo = NULL;

    // Create new Function Instance info
    if (S_OK == hr)
    {
        pFunctionInstanceInfo = new(std::nothrow) TFunctionInstanceInfo();
        if (!pFunctionInstanceInfo)
        {
            hr = E_OUTOFMEMORY;
        }
    }

    // Get the MAC address for the From address
    if (S_OK == hr)
    {
        memcpy(
            &IpNetRow2.Address, 
            pFromAddr, 
            (FromAddrLen <= sizeof(IpNetRow2.Address)) ? FromAddrLen : sizeof(IpNetRow2.Address));
        IpNetRow2.InterfaceIndex = InterfaceIndex;
        err = GetIpNetEntry2(&IpNetRow2);
        if (NO_ERROR != err)
        {
            // Could not find the MAC address in the cache, lets hit the wire.
             err = ResolveIpNetEntry2(&IpNetRow2, NULL);
        }

        if (NO_ERROR == err)
        {
            memcpy(pFunctionInstanceInfo->m_PhysicalAddress, IpNetRow2.PhysicalAddress, IpNetRow2.PhysicalAddressLength);
            pFunctionInstanceInfo->m_PhysicalAddressLength = IpNetRow2.PhysicalAddressLength;
        }
        else
        {
            hr = HRESULT_FROM_WIN32(err);
        }
    }

    // Convert the From Address to String form.
    if (S_OK == hr)
    {
        err = GetNameInfo(
            (PSOCKADDR) pFromAddr,
            FromAddrLen,
            pFunctionInstanceInfo->m_szIPAddress,
            ARRAYSIZE(pFunctionInstanceInfo->m_szIPAddress),
            NULL, 
            0,
            NI_NUMERICHOST | NI_NOFQDN);
        if (err != 0)
        {
            hr = HRESULT_FROM_WIN32(WSAGetLastError());
        }
    }

    // Convert the GUID into String Form
    if (S_OK == hr)
    {
        err = UuidToString(
            pDeviceId,
            (RPC_WSTR*) &pFunctionInstanceInfo->m_pszDeviceId);
        if (RPC_S_OK != err)
        {
            hr = E_OUTOFMEMORY;
        }
    }

    // Copy device info
    if (S_OK == hr)
    {
        if (pDeviceInfo)
        {
            pFunctionInstanceInfo->m_DeviceInfo = *pDeviceInfo;
        }
    }

    // Create an array of device categories
    if (   (S_OK == hr)
        && *pFunctionInstanceInfo->m_DeviceInfo.szDeviceCategory)
    {
        // Count the number of delimeters in the string
        pFunctionInstanceInfo->m_cDeviceCategoriesCount = 1;
        pszToken = pFunctionInstanceInfo->m_DeviceInfo.szDeviceCategory;
        while (*pszToken)
        {
            if (wcschr(szDelimeters, *pszToken))
            {
                ++pFunctionInstanceInfo->m_cDeviceCategoriesCount;
            }
            ++pszToken;
        }

        // Allocate an array to hold the string pointers
        pFunctionInstanceInfo->m_ppszDeviceCategories = (PWSTR*) malloc(pFunctionInstanceInfo->m_cDeviceCategoriesCount * sizeof(PWSTR));

        if (pFunctionInstanceInfo->m_ppszDeviceCategories)
        {
            // Tokenize the device categories and save the pointers

            pszToken = wcstok_s(pFunctionInstanceInfo->m_DeviceInfo.szDeviceCategory,
                szDelimeters,
                &pszNextToken);

            while (   pszToken
                   && (iCategoryIndex < pFunctionInstanceInfo->m_cDeviceCategoriesCount))
            {
                pFunctionInstanceInfo->m_ppszDeviceCategories[iCategoryIndex] = pszToken;
                ++iCategoryIndex;
                  
                pszToken = wcstok_s(
                    NULL,
                    szDelimeters,
                    &pszNextToken);
            }
        }
        else
        {
            hr = E_OUTOFMEMORY;
        }

    }

    // Cleanup
    if (S_OK == hr)
    {
        *ppFunctionInstanceInfo = pFunctionInstanceInfo;
    }
    else
    {
        delete pFunctionInstanceInfo;
    }

    return hr;
}  // TFunctionInstanceInfo::CreateInstance
void CSkypeMessageQueue::ProcessQueue()
{
	std::wstring strFull;
	std::wstring str;
	std::wstring strID;

	// Retrieve the next change in status
	if(! m_queueStatus.empty()) {
		SkypeAPIAttachmentStatus status = m_queueStatus.front();
		m_queueStatus.pop();

		for(CSkypeMessageSinkList::iterator it = m_MessageSinks.begin(); it != m_MessageSinks.end(); it++) {
			(*it)->ProcessAPIStatusChange(status);
		}
	}
	
	// Retrieve the next response, if there is one
	if(! m_queueIncoming.empty()) {
		strFull = m_queueIncoming.front();
		str = strFull;
		strID = L"";
		m_queueIncoming.pop();

		if(str[0] == L'#') {
			size_t iSpace = str.find(L" ");
			if(iSpace != -1) {
				strID = str.substr(0, iSpace + 1);
				str = str.substr(iSpace + 1, str.length() - iSpace);
			}
		}

		if(_wcsicmp(str.c_str(), L"CONNSTATUS LOGGEDOUT") == 0) {
			// When connection status is logged out, start rechecking for skype
			gSkypeQueue.DeleteAllBinaryTransfers();
			RestartTimer();
		}

		if(_wcsnicmp(str.c_str(), L"PROTOCOL ", 9) == 0) {
 			if(str.length() > 8) {
				bool bSendProtocol = (m_lSupportedProtocol == -1);
				m_lSupportedProtocol = _wtol(& str.c_str()[9]);
				if(bSendProtocol) {
					WCHAR strMsg[16];
					swprintf_s(strMsg, 16, L"PROTOCOL %d", SUPPORTED_PROTOCOL);
					InternalProcessCommand(strMsg);
				}
			}
		}

#ifndef _NO_USE_LIST
		if(! m_bNeedRebuildCallList) {
			if(_wcsnicmp(str.c_str(), L"CALL", 4) == 0) {
				WCHAR * ptrStatus;
				WCHAR * ptrStatusInd = wcsstr(str.c_str(), L" STATUS ");
				if(ptrStatusInd != NULL) {
					ptrStatus = & ptrStatusInd[8];
					if(ptrStatus != NULL) { 
						long lCallID = 0;
						if(swscanf_s(str.c_str(), L"CALL %d STATUS", & lCallID) == 1) {
							if(lCallID > 0) {
								SkypeCallProgress progress = TextToSkypeCallProgress(ptrStatus);
								UpdateCallProgress(lCallID, progress);
							}
						}
					}
				}
			}
		}
		if(! m_bNeedRebuildUserList) {
			if(_wcsnicmp(str.c_str(), L"USER", 4) == 0) {
				WCHAR * ptrOnlineStatus;
				WCHAR * ptrOnlineStatusInd = wcsstr(str.c_str(), L" ONLINESTATUS ");
				if(ptrOnlineStatusInd != NULL) {
					ptrOnlineStatus = & ptrOnlineStatusInd[14];
					if(ptrOnlineStatus != NULL) {
						WCHAR userID[_MAX_LINE];
						if(swscanf_s(str.c_str(), L"USER %s ONLINESTATUS", userID, _MAX_LINE) == 1) {
							if(wcslen(userID) > 0) {
								SkypeOnlineStatus status = TextToSkypeOnlineStatus(ptrOnlineStatus);
								UpdateUserOnlineStatus(userID, status);
							}
						}
					}
				}
			}
		}
#endif
		
		bool bProcessCallbacks = ! m_bBlocking;
		bool bMatch = false;
	
		// If we are waiting on a blocking call, set up the response
		if(m_bBlocking) {
			if((m_strDesiredResult.empty()) && (! m_blockingCommandID)) {
				m_strCommandResult = str;
			} else {
				if(m_blockingCommandID) {
					if(_wcsicmp(strID.c_str(), m_strCommandID) == 0) {
						m_strCommandResult = str;
						ATLTRACE(L"Response received: %s\n", strID.c_str());
						bMatch = true;	// イベントのブロックを解除
						
						if(_wcsnicmp(str.c_str(), L"ERROR", 5) == 0) {
							ATLTRACE(L"Error for %s detected: %s\n", strID.c_str(),
								str.c_str());
							m_bBlockingError = true;
						}
					}
				} else {
					WCHAR * pCopy = _wcsdup(m_strDesiredResult.c_str());
					WCHAR *next_token = NULL;
					WCHAR * pSearch = wcstok_s(pCopy, L"|", &next_token);
					while(pSearch && (! bMatch)) {
						if(wcsstr(str.c_str(), pSearch) != NULL) {
							m_strCommandResult = str;
							bMatch = true;
							break;
						}
						pSearch = wcstok_s(NULL, L"|", &next_token);
					}
					try {
						free(pCopy);
					} catch(...) {
					}

					if(! bMatch) {
						if(_wcsnicmp(str.c_str(), L"ERROR", 5) == 0) {
							m_strCommandResult = str;
							m_bBlockingError = true;
							bMatch = true;
						}
					}
				}
			}
		}	

		// Let the blocking routine know if a match was found
		if(m_bBlocking) {
			m_bBlocking = ! bMatch;
		}

// paak
// ブロックコマンド実行中のイベントの抑制は行わない。
// イベントは常に発生させ、コールバック内で有効性をチェックすべき。
bProcessCallbacks = true;

		// Trigger the response event sinks
		for(CSkypeMessageSinkList::iterator it = m_MessageSinks.begin(); it != m_MessageSinks.end(); it++) {
			(*it)->ProcessResponse(strFull.c_str(), bProcessCallbacks);
		}
	}

	if((! m_queueOutgoing.empty()) && (m_hWndSkype != NULL)) {

		str = m_queueOutgoing.front();
		m_queueOutgoing.pop();
		
		InternalProcessCommand(str.c_str());
	}

}