void SourceEdit::TokenizeLine(const CStringW& line, CArray<CStringW>& tokens) { int i = 0; while (true) { // We are either at the start of the line, or the end of the previous token, // so scan forward to find the start of the next token. while (true) { if (i == line.GetLength()) return; WCHAR c = line.GetAt(i); if ((c != L' ') && (c != L'\t')) break; i++; } // Find the end of this token int j = line.Find(L" ",i); if (j == -1) { // No final delimiter, so this must be the last token if (i < line.GetLength()) tokens.Add(line.Mid(i)); return; } else { // Store this token and move to the end of it tokens.Add(line.Mid(i,j-i)); i = j; } } }
bool CStringUtils::WriteAsciiStringToClipboard(const CStringW& sClipdata, HWND hOwningWnd) { CClipboardHelper clipboardHelper; if (clipboardHelper.Open(hOwningWnd)) { EmptyClipboard(); HGLOBAL hClipboardData = CClipboardHelper::GlobalAlloc((sClipdata.GetLength()+1)*sizeof(WCHAR)); if (hClipboardData) { WCHAR* pchData = (WCHAR*)GlobalLock(hClipboardData); if (pchData) { _tcscpy_s(pchData, sClipdata.GetLength()+1, (LPCWSTR)sClipdata); GlobalUnlock(hClipboardData); if (SetClipboardData(CF_UNICODETEXT, hClipboardData)) { // no need to also set CF_TEXT : the OS does this // automatically. return true; } } } } return false; }
CString TextFormat::UnicodeToUTF8(const CStringW& in) { CString utfText; int utfLen = ::AtlUnicodeToUTF8(in,in.GetLength(),NULL,0); LPSTR utfPtr = utfText.GetBufferSetLength(utfLen); ::AtlUnicodeToUTF8(in,in.GetLength(),utfPtr,utfLen); utfText.ReleaseBuffer(utfLen); return utfText; }
CStringW CHistoryManager::Redirect(CStringW strFileName) { bool bRedirect = false; CStringW strRedirect; strFileName.Replace(L'/', L'\\'); bool bLeadSlash = false; if (strFileName.GetLength() >= 4 && _wcsnicmp(strFileName, L"\\\\?\\", 4) == 0) bLeadSlash = true; std::vector<std::wstring> vecParts; std::wstring strPath = strFileName; transform(strPath.begin(), strPath.end(), strPath.begin(), tolower); SplitPath(strPath, vecParts); for (int i = 0; i < TEMP_KEY_COUNT; i++) { int nPartCount = g_TempPaths[i].vecShortParts.size(); if (nPartCount == 0 || (int)vecParts.size() < nPartCount) continue; bool bSame = true; for (int j = 0; j < nPartCount; j++) { if (g_TempPaths[i].vecShortParts[j] != vecParts[j] && g_TempPaths[i].vecLongParts[j] != vecParts[j]) { bSame = false; break; } } if (bSame) { bRedirect = true; if (bLeadSlash) strRedirect = L"\\\\?\\"; strRedirect += m_strRedirectPath; strRedirect += g_TempPaths[i].strRegKey.c_str(); for (std::vector<std::wstring>::size_type j = nPartCount; j < vecParts.size(); j++) // gao { strRedirect += L"\\"; strRedirect += vecParts[j].c_str(); } if (strFileName[strFileName.GetLength() - 1] == L'\\') strRedirect += L'\\'; break; } } return bRedirect ? strRedirect : strFileName; }
char* CStringToNPStringCharacters(const CString &str) { CStringW wstr = CT2W(str); int nUTF8 = WideCharToMultiByte(CP_UTF8, 0, wstr, wstr.GetLength() + 1, NULL, 0, NULL, NULL); if (nUTF8 == 0) return NULL; char* utf8str = (char *)NPN_MemAlloc(nUTF8); WideCharToMultiByte(CP_UTF8, 0, wstr, wstr.GetLength() + 1, utf8str, nUTF8, NULL, NULL); return utf8str; }
CStringA Util::String::UnicodeToGBK( CStringW unicode ) { CStringA strGBK = ""; DWORD dwMinSize = 0; dwMinSize = WideCharToMultiByte(936, NULL, unicode, unicode.GetLength(),NULL, 0, NULL, FALSE); strGBK.GetBufferSetLength(dwMinSize); LPSTR lpszStr = strGBK.GetBuffer(); INT ok = WideCharToMultiByte(936, NULL, unicode, unicode.GetLength(), lpszStr, dwMinSize, NULL, FALSE); strGBK.ReleaseBuffer(); return strGBK; }
BOOL CStdioFileEx::ReadWideString(CStringW& rString) { _ASSERTE(m_pStream); rString = L"";// empty string without deallocating if(m_bIsUnicodeText) { // If at position 0, discard byte-order mark before reading if(GetPosition() == 0) { wchar_t bom; Read(&bom, sizeof(wchar_t)); } const int nMaxSize = 128; LPWSTR lpsz = rString.GetBuffer(nMaxSize); LPWSTR lpszResult; int nLen = 0; for (;;) { lpszResult = fgetws(lpsz, nMaxSize+1, m_pStream); rString.ReleaseBuffer(); // handle error/eof case if (lpszResult == NULL && !feof(m_pStream)) { Afx_clearerr_s(m_pStream); AfxThrowFileException(CFileException::genericException, _doserrno, m_strFileName); } // if string is read completely or EOF if (lpszResult == NULL || (nLen = (int)lstrlenW(lpsz)) < nMaxSize || lpsz[nLen-1] == '\n') break; nLen = rString.GetLength(); lpsz = rString.GetBuffer(nMaxSize + nLen) + nLen; } //remove crlf if exist. nLen = rString.GetLength(); if (nLen > 1 && rString.Mid(nLen-2) == L"\r\n") { rString.GetBufferSetLength(nLen-2); } return rString.GetLength() > 0; } else { CStringA ansiString; BOOL bRetval = ReadAnsiString(ansiString); //setlocale(LC_ALL, "chs_chn.936");//no need rString = ansiString; return bRetval; } }
CStringA wc2utf8(const CStringW& rwstr) { CStringA strUTF8; int iChars = AtlUnicodeToUTF8(rwstr, rwstr.GetLength(), NULL, 0); if (iChars > 0) { LPSTR pszUTF8 = strUTF8.GetBuffer(iChars); AtlUnicodeToUTF8(rwstr, rwstr.GetLength(), pszUTF8, iChars); strUTF8.ReleaseBuffer(iChars); } return strUTF8; }
STDMETHODIMP IDSMPropertyBagImpl::GetPropertyInfo(ULONG iProperty, ULONG cProperties, PROPBAG2* pPropBag, ULONG* pcProperties) { CheckPointer(pPropBag, E_POINTER); CheckPointer(pcProperties, E_POINTER); for(ULONG i = 0; i < cProperties; i++, iProperty++, (*pcProperties)++) { CStringW key = GetKeyAt(iProperty); pPropBag[i].pstrName = (BSTR)CoTaskMemAlloc((key.GetLength()+1)*sizeof(WCHAR)); if(!pPropBag[i].pstrName) return E_FAIL; wcscpy_s(pPropBag[i].pstrName, key.GetLength()+1, key); } return S_OK; }
AVSINLINE const CStringA Encoding::wstring2string(const CStringW &sLine, const unsigned int unCodePage) { const int nSize = WideCharToMultiByte( unCodePage, 0, sLine.GetString(), sLine.GetLength(), NULL, 0, NULL, NULL ); char *sTemp = new char[nSize]; if ( !sTemp ) return ""; WideCharToMultiByte( unCodePage, 0, sLine.GetString(), sLine.GetLength(), sTemp, nSize, NULL, NULL ); CStringA sResult( sTemp ); delete []sTemp; return sResult; }
BOOL SearchEdit::PreTranslateMessage(MSG* pMsg) { if (pMsg->message == WM_KEYDOWN) { bool ctrl = ((::GetKeyState(VK_CONTROL) & 0x8000) != 0); switch (pMsg->wParam) { case VK_RETURN: { CStringW text; GetWindowText(text); if (text.GetLength() > 0) GetParentFrame()->SendMessage(m_msg,(WPARAM)(LPCWSTR)text); } break; case VK_ESCAPE: GetParentFrame()->PostMessage(WM_SELECTSIDE,0); break; case 'A': if (ctrl) PostMessage(WM_COMMAND,ID_EDIT_SELECT_ALL); break; } } return UnicodeEdit::PreTranslateMessage(pMsg); }
void IniFile::Parse(LPCVOID data, size_t size) { LPCWSTR begin = (LPCWSTR)data; LPCWSTR end = begin + size / sizeof(*begin); if (*begin == 0xFEFF) ++begin; Section* currentSection = nullptr; CString* varToAppend = nullptr; while (1) { const wchar_t* eol = GetEol(begin, end); if (begin >= eol) break; CStringW line(begin, int(eol - begin)); begin = eol + 1; line.Trim(L" \t\r\n"); if (varToAppend) { bool appendNext = line.Right(1) == L"\\"; if (appendNext) line.Delete(line.GetLength() - 1); *varToAppend += line; if (!appendNext) varToAppend = nullptr; continue; } if (line.IsEmpty() || line[0] == L';') continue; if (line[0] == L'[' && line[line.GetLength() - 1] == L']') { currentSection = &m_sections[line.Trim(L"[]")]; continue; } if (!currentSection) continue; int equalPos = line.Find(L'='); if (equalPos == -1 || equalPos == 0) continue; CStringW var = line.Left(equalPos); CStringW text = line.Mid(equalPos + 1); if (text.Right(1) == L"\\") { text.Delete(text.GetLength() - 1); varToAppend = &(*currentSection)[var]; } (*currentSection)[var] = text; } }
CString TextFormat::ToXML_UTF8(const CStringW& in) { // First escape any characters that will cause problems in the XML CStringW escText; int escLen = ::EscapeXML(in,in.GetLength(),NULL,0); LPWSTR escPtr = escText.GetBufferSetLength(escLen); ::EscapeXML(in,in.GetLength(),escPtr,escLen); escText.ReleaseBuffer(escLen); // Convert the escaped text to UTF-8 CString utfText; int utfLen = ::AtlUnicodeToUTF8(escText,escText.GetLength(),NULL,0); LPSTR utfPtr = utfText.GetBufferSetLength(utfLen); ::AtlUnicodeToUTF8(escText,escText.GetLength(),utfPtr,utfLen); utfText.ReleaseBuffer(utfLen); return utfText; }
int CStringUtils::FastCompareNoCase (const CStringW& lhs, const CStringW& rhs) { // attempt latin-only comparison INT_PTR count = min (lhs.GetLength(), rhs.GetLength()+1); const wchar_t* left = lhs; const wchar_t* right = rhs; for (const wchar_t* last = left + count+1; left < last; ++left, ++right) { int leftChar = *left; int rightChar = *right; int diff = leftChar - rightChar; if (diff != 0) { // case-sensitive comparison found a difference if ((leftChar | rightChar) >= 0x80) { // non-latin char -> fall back to CRT code // (full comparison required as we might have // skipped special chars / UTF plane selectors) return _wcsicmp (lhs, rhs); } // normalize to lower case if ((leftChar >= 'A') && (leftChar <= 'Z')) leftChar += 'a' - 'A'; if ((rightChar >= 'A') && (rightChar <= 'Z')) rightChar += 'a' - 'A'; // compare again diff = leftChar - rightChar; if (diff != 0) return diff; } } // must be equal (both ended with a 0) return 0; }
STDMETHODIMP CSubPicAllocatorPresenterImpl::GetString(LPCSTR field, LPWSTR* value, int* chars) { CheckPointer(value, E_POINTER); CheckPointer(chars, E_POINTER); CStringW ret = nullptr; if (!strcmp(field, "name")) { ret = L"MPC-HC"; } else if (!strcmp(field, "version")) { ret = VersionInfo::GetVersionString(); } else if (!strcmp(field, "yuvMatrix")) { ret = L"None"; if (m_inputMediaType.IsValid() && m_inputMediaType.formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2* pVIH2 = (VIDEOINFOHEADER2*)m_inputMediaType.pbFormat; if (pVIH2->dwControlFlags & AMCONTROL_COLORINFO_PRESENT) { DXVA2_ExtendedFormat& flags = (DXVA2_ExtendedFormat&)pVIH2->dwControlFlags; ret = (flags.NominalRange == DXVA2_NominalRange_Normal) ? L"PC." : L"TV."; switch (flags.VideoTransferMatrix) { case DXVA2_VideoTransferMatrix_BT601: ret.Append(L"601"); break; case DXVA2_VideoTransferMatrix_BT709: ret.Append(L"709"); break; case DXVA2_VideoTransferMatrix_SMPTE240M: ret.Append(L"240M"); break; default: ret = L"None"; break; } } } } if (!ret.IsEmpty()) { int len = ret.GetLength(); size_t sz = (len + 1) * sizeof(WCHAR); LPWSTR buf = (LPWSTR)LocalAlloc(LPTR, sz); if (!buf) { return E_OUTOFMEMORY; } wcscpy_s(buf, len + 1, ret); *chars = len; *value = buf; return S_OK; } return E_INVALIDARG; }
bool SourceEdit::GetNextLine(const CStringW& text, CStringW& line, int& i) { if (i == text.GetLength()) { // If at the very end, the final line must be blank line = ""; i++; return true; } else if (i > text.GetLength()) { // Past the end of the text, so stop reading lines return false; } line.Empty(); while (i < text.GetLength()) { WCHAR c = text.GetAt(i); i++; switch (c) { case L'\r': // Check for a "\r\n" sequence if (i < text.GetLength()) { if (text.GetAt(i) == L'\n') i++; } return true; case L'\n': return true; default: line.AppendChar(c); break; } } // Having got here a line must have ended without a trailing carriage return, // so move beyond the end of text to make sure this is the last line. i++; return true; }
CStringW CSecRunAsUser::CreateRandomPW(){ CStringW strResult; while (strResult.GetLength() < 10){ char chRnd = (char)(48 + (rand() % 74)); if( (chRnd > 97 && chRnd < 122) || (chRnd > 65 && chRnd < 90) || (chRnd >48 && chRnd < 57) ||(chRnd==95) ){ strResult.AppendChar(chRnd); } } return strResult; }
void SourceEdit::Search(LPCWSTR text, std::vector<SearchWindow::Result>& results) { CWaitCursor wc; int len = (int)CallEdit(SCI_GETLENGTH); TextToFind find; find.chrg.cpMin = 0; find.chrg.cpMax = len; CString textUtf = TextFormat::UnicodeToUTF8(text); find.lpstrText = (char*)(LPCSTR)textUtf; while (true) { // Search for the text if (CallEdit(SCI_FINDTEXT,0,(sptr_t)&find) == -1) return; // Get the surrounding text as context CStringW leading = GetTextRange(find.chrgText.cpMin-4,find.chrgText.cpMin,len); CStringW match = GetTextRange(find.chrgText.cpMin,find.chrgText.cpMax,len); CStringW trailing = GetTextRange(find.chrgText.cpMax,find.chrgText.cpMax+32,len); CStringW context = leading + match + trailing; context.Replace(L'\n',L' '); context.Replace(L'\r',L' '); context.Replace(L'\t',L' '); // Store the found result SearchWindow::Result result; result.context = context; result.inContext.cpMin = leading.GetLength(); result.inContext.cpMax = leading.GetLength() + match.GetLength(); result.sourceLocation = SOURCE_FILE; result.inSource.cpMin = find.chrgText.cpMin; result.inSource.cpMax = find.chrgText.cpMax; results.push_back(result); // Look for the next match find.chrg.cpMin = find.chrgText.cpMax; theApp.RunMessagePump(); } }
// **************************************************************** // ReadShapefileIndex() // **************************************************************** // Fast reading for drawing procedure without bounds, file code, etc bool CShapefileReader::ReadShapefileIndex(CStringW filename, FILE* shpFile, CCriticalSection* readLock) { if (filename.GetLength() < 4) { return false; } // reading shape index (SHX) CStringW sFilename = filename; sFilename.SetAt(sFilename.GetLength() - 1, L'x'); FILE* shxfile = _wfopen(sFilename, L"rb"); if (!shxfile ) { _shpfile = NULL; _indexData = NULL; USES_CONVERSION; CallbackHelper::ErrorMsg(Debug::Format("Failed to open SHX file: %s", OLE2A(sFilename))); return false; } fseek (shxfile, 0, SEEK_END); int indexFileSize = ftell(shxfile); rewind(shxfile); // 100 is for header fseek(shxfile, 100, SEEK_SET); _indexData = new char[indexFileSize - 100]; long result = fread(_indexData, sizeof(char), indexFileSize - 100, shxfile); fclose(shxfile); //_shpHeader.numShapes = (indexFileSize - 100)/8; // 2 int on record _readLock = readLock; _shpfile = shpFile; rewind(shpFile); return true; }
BOOL CHistoryManager::PrepareTempDirs() { for (int i = 0; i < TEMP_KEY_COUNT; i++) { HKEY key; if (RegOpenKeyExA(HKEY_CURRENT_USER, REG_TEMP_FOLDER, 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) continue; g_TempPaths[i].strRegKey = g_TempKey[i]; WCHAR szPath[1024]; DWORD Size = 1024; if (RegQueryValueExW(key, g_TempPaths[i].strRegKey.c_str(), NULL, NULL, (LPBYTE)szPath, &Size) != ERROR_SUCCESS) { RegCloseKey(key); continue; } CStringW strPath = szPath; strPath.Replace(L'/', L'\\'); if (strPath[strPath.GetLength() - 1] != L'\\') strPath += L'\\'; ////////////////////////////////////////////////////////////////////////// // Create Redirect Directory CStringW strTemp = m_strRedirectPath + CStringW(g_TempPaths[i].strRegKey.c_str()); if (!CreateDirectoryW(strTemp, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) continue; SetFileAttributesW(strTemp, FILE_ATTRIBUTE_HIDDEN); ////////////////////////////////////////////////////////////////////////// // WCHAR szDir[1024], szShort[1024], szLong[1024]; ExpandEnvironmentStringsW((LPWSTR)(LPCWSTR)strPath, (LPWSTR)szDir, _countof(szDir)); GetShortPathNameW(szDir, szShort, _countof(szShort)); GetLongPathNameW(szDir, szLong, _countof(szLong)); _wcslwr_s(szShort); _wcslwr_s(szLong); g_TempPaths[i].strShortTempDir = szShort; g_TempPaths[i].strLongTempDir = szLong; SplitPath(g_TempPaths[i].strShortTempDir, g_TempPaths[i].vecShortParts); SplitPath(g_TempPaths[i].strLongTempDir, g_TempPaths[i].vecLongParts); RegCloseKey(key); } return true; }
CStringA CUnicodeUtils::GetMulti(const CStringW& string,int acp) { char * buf; CStringA retVal; int len = string.GetLength(); if (len==0) return retVal; buf = retVal.GetBuffer(len*4 + 1); int lengthIncTerminator = WideCharToMultiByte(acp, 0, string, -1, buf, len * 4, nullptr, nullptr); retVal.ReleaseBuffer(lengthIncTerminator-1); return retVal; }
STDMETHODIMP XyOptionsImpl::XyGetString(unsigned field, LPWSTR *value, int *chars) { if (!TestOption(field, OPTION_TYPE_STRING, OPTION_MODE_READ)) return E_INVALIDARG; if (!value && !chars) return S_FALSE; CStringW tmp; HRESULT hr = DoGetField(field, &tmp); if (SUCCEEDED(hr)) { if (value) { *value = static_cast<LPWSTR>(LocalAlloc(LPTR, sizeof(WCHAR)*(tmp.GetLength()+1))); ASSERT(*value); memcpy(*value, tmp.GetString(), (tmp.GetLength()+1)*sizeof(WCHAR)); } if (chars) { *chars = tmp.GetLength(); } } return hr; }
CString TextFormat::UnicodeToLatin1(const CStringW& in) { CString text; int len = in.GetLength(); LPSTR textPtr = text.GetBufferSetLength(len); for (int i = 0; i < len; i++) { wchar_t c = in[i]; textPtr[i] = (c < 256) ? (char)c : '?'; } text.ReleaseBuffer(len); return text; }
BOOL CFileBasedProjectTemplateItem::CreateMainFile(LPCTSTR lpszTargetPath, LPCTSTR lpszCrLf) { CStringW text; TextDocument doc; bool result = doc.Read(m_strPath,text); if (result) { const CStringW lineendings(L"\r\n"); int index = text.FindOneOf(lineendings); if (index != -1) { CStringW line = text.Left(index); const CStringW strKey(L"%DESCRIPTION: "); CStringW strStartOfLine = line.Left(strKey.GetLength()); strStartOfLine.MakeUpper(); if (strKey == strStartOfLine) { text.Delete(0,index); text.TrimLeft(lineendings + L' '); } } LPCWSTR le = GetLineEnding(static_cast<LPCWSTR>(text),text.GetLength()); USES_CONVERSION; if (std::wcscmp(le,T2CW(lpszCrLf)) != 0) // Line endings not equal text.Replace(le,lpszCrLf); result = doc.Write(lpszTargetPath,text); } return result; }
CStringA CUnicodeUtils::GetUTF8(const CStringW& string) { char * buf; CStringA retVal; int len = string.GetLength(); if (len==0) return retVal; buf = retVal.GetBuffer(len*4 + 1); // SecureZeroMemory(buf, (string.GetLength()*4 + 1)*sizeof(char)); int lengthIncTerminator = WideCharToMultiByte(CP_UTF8, 0, string, -1, buf, len*4, NULL, NULL); retVal.ReleaseBuffer(lengthIncTerminator-1); return retVal; }
// ************************************************************* // SaveStyle() // ************************************************************* bool OgrStyleHelper::SaveStyle(GDALDataset* dataset, CStringW xml, CStringW layerName, CStringW styleName) { xml.Replace(L"\n", L""); xml.Replace(L"'", L"''''"); if (xml.GetLength() == 0) return false; CStringW sql; sql.Format(L"INSERT INTO %s(layername, stylename, style) VALUES ('%s', '%s', '%s')", GetStyleTableName(layerName), layerName, styleName, xml); CPLErrorReset(); OGRLayer* layer = dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL); return CPLGetLastErrorNo() == OGRERR_NONE; }
CString OptUtf8ToStr(const CStringW& rwstr) { CStringA astr; for (int i = 0; i < rwstr.GetLength(); i++) { if (rwstr[i] >= 0x100) { // this is no UTF8 string (it's already an Unicode string)... return rwstr; // just return the string } astr += (BYTE)rwstr[i]; } return OptUtf8ToStr(astr); }
BOOL CRegistryKey::Write( LPCTSTR lpSubKey, CStringW strVal ) { INVALID_KEY_RETURN; int nLen = strVal.GetLength() * 2; const BYTE * p = (const BYTE *)(LPCWSTR)strVal; long lReturn=RegSetValueEx(m_hKey,lpSubKey,0L,REG_SZ, p, nLen); if(lReturn==ERROR_SUCCESS) return TRUE; return FALSE; }
bool SpellCheck::TestWord(CHARRANGE range) { // Get the word to be checked CStringW text = m_edit->GetTextRange(range.cpMin,range.cpMax); // Discard any leading and trailing non-alpha characters int start = 0; int length = text.GetLength(); while (length > 0) { wchar_t c = text[start]; if (IsTestCharacter(c)) break; start++; length--; } while (length > 0) { wchar_t c = text[start+length-1]; if (IsTestCharacter(c)) break; length--; } // Make sure that there is a word to be checked if (length == 0) return false; // Check the list of ignored words CStringW wordU((LPCWSTR)text+start,length); if (m_ignoreWords.find(wordU) != m_ignoreWords.end()) return false; // Check the dictionary for the word CString word = TextFormat::UnicodeToLatin1(wordU); if (spell->spell(word) != 0) return false; // Select the word, as it is not in the dictionary m_edit->SetSelect(range); // Make sure that the tab containing the selected word is visible if (m_edit->IsWindowVisible() == FALSE) { Panel::GetPanel(m_edit)->SetActiveTab(Panel::Tab_Source); m_badWord.SetFocus(); } return true; }
CStringW Skein::Node::StripWhite(const CStringW& inStr) { CStringW outStr; outStr.Preallocate(inStr.GetLength()+1); for (int i = 0; i < inStr.GetLength(); i++) { WCHAR c = inStr.GetAt(i); switch (c) { case L'\n': case L'\r': case L' ': case L'\t': break; case '>': if (i < inStr.GetLength()-1) outStr.AppendChar(c); default: outStr.AppendChar(c); break; } } return outStr; }