TT_UNIVERSAL_FUNC bool TTIsRunningUnderMaster() { #ifdef _WIN32 #ifdef _UNICODE OutputDebugString(GetCommandLine()); //printf( "IsRunningUnderMaster? %d\n", wcsstr( GetCommandLine(), L" test =" ) != nullptr ); return wcsstr(GetCommandLine(), L" test =") != nullptr; #else return strstr(GetCommandLine(), " test =") != nullptr; #endif #else bool result = true; FILE* f = fopen("/proc/self/cmdline", "r"); if (f != nullptr) { char buf[1024]; int len = fread(buf, 1, 1023, f); buf[len] = 0; result = strstr(buf, " test =") != nullptr; fclose(f); } return result; #endif }
/* * Replace a pattern in a string (not regex, straight replace) with another * string. * * @param str * @param pattern * @param replaceWith * @return either original str or a new str (via strdup) that replaces the * pattern with the replaceWith string */ TCHAR *replaceStr(TCHAR *str, TCHAR *pattern, TCHAR *replaceWith) { TCHAR buffer[MAX_PATH*2] = {0}; TCHAR *p; //Return orig if str is not in orig. if(!(p = wcsstr(str, pattern))) { return wcsdup(str); } int loc = p-str; if (loc >= sizeof(buffer)) { return wcsdup(str); } wcsncpy(buffer, str, loc); // Copy characters from 'str' start to 'orig' st$ buffer[loc] = 0x0000; int remaingBufferSize = sizeof(buffer) - loc; int len = _snwprintf(buffer+(loc), remaingBufferSize, _T("%s%s"), replaceWith, p + wcslen(pattern)); if(len > remaingBufferSize ) { return wcsdup(str); } return wcsdup(buffer); }
int bws_month_score(const struct bwstring *s0) { if (MB_CUR_MAX == 1) { const unsigned char *end, *s; s = s0->data.cstr; end = s + s0->len; while (isblank(*s) && s < end) ++s; for (int i = 11; i >= 0; --i) { if (cmonths[i] && (s == (unsigned char*)strstr((const char*)s, (char*)(cmonths[i])))) return (i); } } else { const wchar_t *end, *s; s = s0->data.wstr; end = s + s0->len; while (iswblank(*s) && s < end) ++s; for (int i = 11; i >= 0; --i) { if (wmonths[i] && (s == wcsstr(s, wmonths[i]))) return (i); } } return (-1); }
static void Message(const char* fmt, ...) { char line[MAX_LINE_SIZE]; va_list arg; va_start(arg, fmt); vsprintf(line, fmt, arg); va_end(arg); //printf("%s\n", line); int len = strlen(line)+1; wchar_t* wbuf = new wchar_t[len]; memset(wbuf, 0, 2*len); mbstowcs(wbuf, line, 2*len); wchar_t* cr = wcsstr(wbuf, L"\r"); if (cr != NULL) *cr = L'\0'; VARIANT x; x.vt = VT_BSTR; x.bstrVal = ::SysAllocString(wbuf); AfxExec(DISPATCH_METHOD, NULL, pAfxApp, L"MesPrint", 1, x); delete [] wbuf; return; }
HRESULT WebViewProtocol::ParseWebViewUrl(const wchar_t *url, LONG_PTR *webViewId, wchar_t **path) { *webViewId = 0; *path = NULL; // Parse out the numeric web view ID swscanf_s(url, L"webview://%d/", webViewId); if (*webViewId != 0) { // Find the // authority section marker. If the string ends with //, authDelim // points to the null terminator wchar_t *authDelim = wcsstr(const_cast<wchar_t*>(url), L"//") + 1; if (authDelim != NULL) { // Find the first slash after the authority section. If the string ends with /, /// path points to the null terminator *path = wcschr(authDelim + wcslen(L"//"), '/') + 1; } } return S_OK; }
static void loadURL(BSTR passedURL) { _bstr_t urlBStr(passedURL); if (!!urlBStr && (::PathFileExists(urlBStr) || ::PathIsUNC(urlBStr))) { TCHAR fileURL[INTERNET_MAX_URL_LENGTH]; DWORD fileURLLength = sizeof(fileURL)/sizeof(fileURL[0]); if (SUCCEEDED(::UrlCreateFromPath(urlBStr, fileURL, &fileURLLength, 0))) urlBStr = fileURL; } IWebFramePtr frame; HRESULT hr = gWebView->mainFrame(&frame.GetInterfacePtr()); if (FAILED(hr)) return; IWebMutableURLRequestPtr request; hr = WebKitCreateInstance(CLSID_WebMutableURLRequest, 0, IID_IWebMutableURLRequest, (void**)&request); if (FAILED(hr)) return; hr = request->initWithURL(wcsstr(static_cast<wchar_t*>(urlBStr), L"://") ? urlBStr : _bstr_t(L"http://") + urlBStr, WebURLRequestUseProtocolCachePolicy, 60); if (FAILED(hr)) return; _bstr_t methodBStr(L"GET"); hr = request->setHTTPMethod(methodBStr); if (FAILED(hr)) return; hr = frame->loadRequest(request); if (FAILED(hr)) return; SetFocus(gViewWindow); }
HRESULT ConfigParser::SetOutputFile(const WCHAR* outputFile, const WCHAR* openMode) { // If present, replace the {PID} token with the process ID const WCHAR* pidStr = nullptr; WCHAR buffer[_MAX_PATH]; if ((pidStr = wcsstr(outputFile, _u("{PID}"))) != nullptr) { size_t pidStartPosition = pidStr - outputFile; WCHAR* pDest = buffer; size_t bufferLen = _MAX_PATH; // Copy the filename before the {PID} token wcsncpy_s(pDest, bufferLen, outputFile, pidStartPosition); pDest += pidStartPosition; bufferLen = bufferLen - pidStartPosition; // Copy the PID _itow_s(GetCurrentProcessId(), pDest, /*bufferSize=*/_MAX_PATH - pidStartPosition, /*radix=*/10); #pragma prefast(suppress: 26014, "ultow string length is smaller than 256") pDest += wcslen(pDest); bufferLen = bufferLen - wcslen(pDest); // Copy the rest of the string. #pragma prefast(suppress: 26014, "Overwriting pDset's null terminator is intentional since the string being copied is null terminated") wcscpy_s(pDest, bufferLen, outputFile + pidStartPosition + /*length of {PID}*/ 5); outputFile = buffer; } char16 fileName[_MAX_PATH]; char16 moduleName[_MAX_PATH]; GetModuleFileName(0, moduleName, _MAX_PATH); _wsplitpath_s(moduleName, nullptr, 0, nullptr, 0, fileName, _MAX_PATH, nullptr, 0); if (_wcsicmp(fileName, _u("WWAHost")) == 0 || _wcsicmp(fileName, _u("ByteCodeGenerator")) == 0 || _wcsicmp(fileName, _u("spartan")) == 0 || _wcsicmp(fileName, _u("spartan_edge")) == 0 || _wcsicmp(fileName, _u("MicrosoftEdge")) == 0 || _wcsicmp(fileName, _u("MicrosoftEdgeCP")) == 0) { // we need to output to %temp% directory in wwa. we don't have permission otherwise. if (GetEnvironmentVariable(_u("temp"), fileName, _MAX_PATH) != 0) { wcscat_s(fileName, _MAX_PATH, _u("\\")); const char16 * fileNameOnly = wcsrchr(outputFile, _u('\\')); // if outputFile is full path we just need filename, discard the path wcscat_s(fileName, _MAX_PATH, fileNameOnly == nullptr ? outputFile : fileNameOnly); } else { AssertMsg(FALSE, "Get temp environment failed"); } outputFile = fileName; } FILE *fp; if ((fp = _wfsopen(outputFile, openMode, _SH_DENYWR)) != nullptr) { Output::SetOutputFile(fp); return S_OK; } AssertMsg(false, "Could not open file for logging output."); return E_FAIL; }
BOOL Set_ImgRes(INT nIdx) { TCHAR waMenuItemStr[BUF_LENGTH]; TCHAR waWidth[BUF_LENGTH], waHeight[BUF_LENGTH]; TCHAR* pwChar; ImageRes tIRes; g_ResIdx = nIdx; // Store the current resolution point globally g_hmnuCurr = (HMENU) SendMessage(g_hwndMenuBar, SHCMBM_GETSUBMENU, 0, IDM_SETTINGS); RemoveMenu(g_hmnuCurr, 12, MF_BYPOSITION); if(g_bVideoMode) { AppendMenu(g_hmnuCurr, MF_STRING | MF_POPUP, (UINT)g_ahmnuVdoColorFmts[nIdx], L"&ColorFmts"); g_hmnuCurr = g_ahmnuVdoColorFmts[nIdx]; CheckMenuRadioItem(g_hmnuCurr, 0, (g_nNoOfVdoCap-1), 0, MF_BYPOSITION); GetMenuString(g_hmnuCurr, 0, waMenuItemStr, BUF_LENGTH, MF_BYPOSITION); g_wsColorFmt = waMenuItemStr; g_hmnuCurr = g_hmnuVideoSub; CheckMenuRadioItem(g_hmnuCurr, 0, (g_nNoOfVdoCap-1), nIdx, MF_BYPOSITION); } else { AppendMenu(g_hmnuCurr, MF_STRING | MF_POPUP, (UINT)g_ahmnuStillColorFmts[nIdx], L"&ColorFmts"); g_hmnuCurr = g_ahmnuStillColorFmts[nIdx]; CheckMenuRadioItem(g_hmnuCurr, 0, (g_nNoOfStillCap-1), 0, MF_BYPOSITION); GetMenuString(g_hmnuCurr, 0, waMenuItemStr, BUF_LENGTH, MF_BYPOSITION); g_wsColorFmt = waMenuItemStr; g_hmnuCurr = g_hmnuStillSub; CheckMenuRadioItem(g_hmnuCurr, 0, (g_nNoOfStillCap-1), nIdx, MF_BYPOSITION); } GetMenuString(g_hmnuCurr, nIdx, waMenuItemStr, BUF_LENGTH, MF_BYPOSITION); OutputDebugString(waMenuItemStr); pwChar = wcsstr(waMenuItemStr, L"X"); wcscpy(waHeight, (pwChar+2)); wmemcpy(waWidth, waMenuItemStr, ((pwChar-1)-waMenuItemStr)); waWidth[(pwChar-1)-waMenuItemStr]='\0'; #ifdef DEBUG_MODE OutputDebugString(L"\n---------------------\n"); OutputDebugString(waMenuItemStr); OutputDebugString(L"\n|"); OutputDebugString(waWidth); OutputDebugString(L"|"); OutputDebugString(L"\n|"); OutputDebugString(waHeight); OutputDebugString(L"|\n---------------------"); #endif tIRes.nWidth = atoi(waWidth); tIRes.nHeight = _wtoi(waHeight); //tIRes.nHeight = atoi(waHeight); if(!((tIRes.nWidth==g_tImgRes.nWidth)&&(tIRes.nHeight==g_tImgRes.nHeight)&& (g_bVMod==g_bVideoMode))) { //Record the selected resolution gloablly g_tImgRes.nWidth = tIRes.nWidth; g_tImgRes.nHeight = tIRes.nHeight; g_bVMod = g_bVideoMode; //wsprintf(test, L"\nWidth :- %d Height :- %d", tIRes.nWidth, tIRes.nHeight); //OutputDebugString(test); //g_Prop.Set_Resolution(&tIRes, P); /* ImageRes ptRes; ptRes.nHeight=240; ptRes.nWidth=320; g_Prop.Set_Resolution(&ptRes, P); */ if(g_bVideoMode) g_Prop.Set_Resolution(&tIRes, V); else g_Prop.Set_Resolution(&tIRes, S); OutputDebugString(L"\n-----------Resolution Change OK-----------"); } else { OutputDebugString(L"\n-----------Same Resolution-----------"); } return TRUE; }
BOOL OOG_SelectGateway(const wchar_t* szGateway, size_t strSize) { if (ClientState() != ClientStateMenu) return FALSE; if (wcsstr(szGateway, L"ERROR")) return FALSE; // Select the gateway control. Control* pControl = findControl(CONTROL_BUTTON, (const wchar_t*)NULL, -1, 264, 391, 272, 25); // if the control exists and has the text label, check if it matches the selected gateway if (pControl && pControl->wText2) { wchar_t* wzLine = _wcsdup(pControl->wText2); wchar_t* wzGate = _wcsdup(szGateway); StringToLower(wzLine); StringToLower(wzGate); if (wcsstr(wzLine, wzGate)) { // gateway is correct, do nothing and return true free(wzLine); free(wzGate); return TRUE; } else { free(wzLine); // gateway is NOT correct, change gateway to selected gateway if it exists // open the gateway select screen if (!clickControl(pControl)) return FALSE; int index = 0; bool gatefound = false; // loop here till we find the right gateway if we can pControl = findControl(CONTROL_TEXTBOX, (const wchar_t*)NULL, -1, 257, 500, 292, 160); ControlText* cText; if (pControl && pControl->pFirstText) { cText = pControl->pFirstText; while (cText) { wchar_t* wzGatelist = _wcsdup(cText->wText[0]); if (!wzGatelist) { free(wzGate); return FALSE; } StringToLower(wzGatelist); if (wcsstr(wzGatelist, wzGate)) { // chosen gateway IS in the list and matches, cleanup and break the loop free(wzGatelist); free(wzGate); gatefound = true; break; } free(wzGatelist); index++; cText = cText->pNext; } if (gatefound) { // click the correct gateway using the control plus a default x and a y based on (index*24)+12 if (!clickControl(pControl, -1, 344 + ((index * 24) + 12))) { free(wzGate); return FALSE; } } } free(wzGate); // OK Button, gateway select screen pControl = findControl(CONTROL_BUTTON, (const wchar_t*)NULL, -1, 281, 538, 96, 32); if (pControl) { if (!clickControl(pControl)) return FALSE; } else return FALSE; return TRUE; } } return FALSE; }
/** * Recoding source file. */ static void performFile( const char *filename ) { /** * check filename. */ static char oldName[_MAX_PATH]; static char newName[_MAX_PATH]; static wchar_t buffer[1024]; static wchar_t copybuf[1024]=L"/*"; static wchar_t bufout[1024]; static unsigned char encr_str[2048]; static char ext[_MAX_EXT]; _splitpath( filename, NULL, NULL, NULL, ext ); if( (0 != strcmp(ext,".cpp")) &&(0 != strcmp(ext,".c")) &&(0 != strcmp(ext,".h")) &&(0 != strcmp(ext,".hpp")) ) { printf("WARNING: File '%s' can't been prepared.\n", filename); return; } strcpy( oldName, filename ); strcat( oldName, ".old" ); strcpy( newName, filename ); strcat( newName, ".new" ); FILE * fin = fopen( filename, "r, ccs=UNICODE" ); FILE * fout = fopen( newName, "w, ccs=UNICODE" ); if( NULL == fin ) { printf("ERROR: File %s is missing or unavailable.\n", filename ); exit(1); } if( NULL == fout ) { printf("ERROR: File %s is unavailable.\n", newName ); exit(1); } fputws( _T(SUBST_NAME) _T("\n"), fout ); fputws( _T(SUBST_NAME_A) _T("\n"), fout ); bool longComment = false; while( !feof(fin) ) { if( NULL == fgetws( buffer, sizeof(buffer)/sizeof(wchar_t), fin ) ) continue; /** Break newline */ if( L'\n' == buffer[wcslen(buffer)-1] ) buffer[wcslen(buffer)-1] = 0; if( 0 != wcsstr( buffer, _T(SUBST_NAME) ) ) { printf("WARNING: File '%s' can't been prepared because it already obfuscate.\n", filename); goto ex; } if( (0 != wcsstr( buffer, _T("#include") )) ||(0 != wcsstr( buffer, _T("#error") )) ||(0 != wcsstr( buffer, _T("#pragma") )) ) { fputws( buffer, fout ); fputwc( L'\n', fout ); } else { wchar_t * subStr = NULL; int inIdx = 0; int outIdx = 0; bool backSlachPrefix = false; bool shortComment = false; memcpy( ©buf[2], buffer, sizeof(buffer)-4); wcscat( copybuf, L"*/" ); while( (0!=buffer[inIdx]) &&(inIdx<sizeof(buffer)/sizeof(wchar_t)) ) { if( (!backSlachPrefix) &&(L'\\' == buffer[inIdx]) ) { backSlachPrefix = true; inIdx++; continue; } if( (NULL == subStr) &&(!backSlachPrefix) &&(&buffer[inIdx] == wcsstr(&buffer[inIdx], L"/*")) ) { longComment = true; // Start long comment bufout[outIdx++] = buffer[inIdx++]; bufout[outIdx++] = buffer[inIdx++]; continue; } if( (NULL == subStr) &&(!backSlachPrefix) &&(&buffer[inIdx] == wcsstr(&buffer[inIdx], L"*/")) ) { longComment = false; // Start long comment bufout[outIdx++] = buffer[inIdx++]; bufout[outIdx++] = buffer[inIdx++]; continue; } if( (NULL == subStr) &&(!backSlachPrefix) &&(&buffer[inIdx] == wcsstr(&buffer[inIdx], L"//")) ) { shortComment = true; // Start long comment bufout[outIdx++] = buffer[inIdx++]; bufout[outIdx++] = buffer[inIdx++]; continue; } if( (L'"' == buffer[inIdx]) &&(!backSlachPrefix) &&(!shortComment) &&(!longComment) ) { if( NULL != subStr ) { static wchar_t bf[1024]; bool wideChar = false; /** This is end of string. Perform substitution. */ buffer[inIdx++] = 0; /** * Check outIdx */ bufout[outIdx]=0; if( (outIdx>3) &&(NULL!=wcsstr( &bufout[outIdx-3], L"_T(")) ) { if( L')' != buffer[inIdx] ) { // @todo copy original and WARN wcscat( bufout, L"_T(\"" ); wcscat( bufout, subStr ); wcscat( bufout, L"\"" ); outIdx = wcslen(bufout); printf(" WARNING: Can't substitute '%ws'\n", subStr ); subStr = NULL; continue; } else { outIdx -= 3; buffer[inIdx++] = 0; bufout[outIdx]=0; wideChar = true; } } if( (outIdx>5) &&(NULL!=wcsstr( &bufout[outIdx-5], L"TEXT(")) ) { if( L')' != buffer[inIdx] ) { // @todo copy original and WARN wcscat( bufout, L"TEXT(\"" ); wcscat( bufout, subStr ); wcscat( bufout, L"\"" ); outIdx = wcslen(bufout); printf(" WARNING: Can't substitute '%ws'\n", subStr ); subStr = NULL; continue; } else { outIdx -= 5; buffer[inIdx++] = 0; bufout[outIdx]=0; wideChar = true; } } else if( (outIdx>1) &&( L'L' == bufout[outIdx-1]) ) { outIdx--; bufout[outIdx]=0; wideChar = true; } subStr++; if( wideChar ) printf("FOUND UNICODE: '%ws'\n", subStr ); else printf("FOUND ASCII: '%ws'\n", subStr ); if( 0 != copybuf[2] ) { fputws( copybuf, fout ); fputwc( L'\n', fout ); copybuf[2] = 0; } /* unescape simple */ { int i=0,j=0; while( 0 != subStr[i] ) { if( (L'\\' == subStr[i]) &&(0 != subStr[i+1]) ) { i++; switch(subStr[i++]) { case L'a': subStr[j++] = L'\a'; break; case L'b': subStr[j++] = L'\b'; break; case L'f': subStr[j++] = L'\f'; break; case L'r': subStr[j++] = L'\r'; break; case L't': subStr[j++] = L'\t'; break; case L'v': subStr[j++] = L'\v'; break; case L'\'': subStr[j++] = L'\''; break; case L'\"': subStr[j++] = L'"'; break; case L'\\': subStr[j++] = L'\\'; break; case L'n': subStr[j++] = L'\n'; break; case L'\?': subStr[j++] = L'?'; break; } } else subStr[j++] = subStr[i++]; } subStr[j] = 0; } int i,count; unsigned short outChar = 'A'; if( wideChar ) { count = AES_encode_w( rand(), subStr, encr_str, sizeof(encr_str) ); wcscat(bufout, L"__ODC__(\"" ); outIdx = wcslen(bufout); } else { count = AES_encode_a( rand(), subStr, encr_str, sizeof(encr_str) ); wcscat(bufout, L"__ODA__(\"" ); outIdx = wcslen(bufout); } for( i = 0; i<count;i++ ) { outChar += ((encr_str[i]&0xF0)>>4); if( outChar >= 0x7E ) outChar -= (0x7E-0x20); if( ('\"' == outChar) ||('\\' == outChar) ||('\?' == outChar) ) bufout[outIdx++]= L'\\'; bufout[outIdx++]= (wchar_t) outChar; outChar += (encr_str[i]&0x0F); if( outChar >= 0x7E ) outChar -= (0x7E-0x20); if( ('\"' == outChar) ||('\\' == outChar) ||('\?' == outChar) ) bufout[outIdx++]= L'\\'; bufout[outIdx++]= (wchar_t) outChar; } bufout[outIdx]=0; wcscat(bufout, L"\")" ); outIdx = wcslen(bufout); subStr = NULL; continue; } else { /** Begin of string. */ subStr = &buffer[inIdx]; if( (NULL != wcsstr( buffer, L"[]" )) &&(wcsstr( buffer, L"[]" ) < subStr) ) { printf(" WARNING: Can't substitute text into '%ws' because it initialization probably.\n", buffer ); subStr = NULL; shortComment = true; // This string was copied 'as is' } } } if( NULL == subStr ) { if( backSlachPrefix ) bufout[outIdx++] = L'\\'; bufout[outIdx++] = buffer[inIdx]; } backSlachPrefix = false; inIdx++; } /* while along string */ if( NULL != subStr ) { printf("ERROR: in file '%s' string '%s' is not finished\n", filename, subStr ); break; } bufout[outIdx] = 0; fputws( bufout, fout ); fputwc( L'\n', fout ); } /*if*/ }
int CTabBarClass::PrepareTab(CTab& pTab, CVirtualConsole *apVCon) { int iTabIcon = -1; #ifdef _DEBUG if (this != gpConEmu->mp_TabBar) { _ASSERTE(this == gpConEmu->mp_TabBar); } #endif MCHKHEAP // get file name TCHAR dummy[MAX_PATH*2]; TCHAR fileName[MAX_PATH+4]; fileName[0] = 0; TCHAR szFormat[32]; TCHAR szEllip[MAX_PATH+1]; //wchar_t /**tFileName=NULL,*/ *pszNo=NULL, *pszTitle=NULL; int nSplit = 0; int nMaxLen = 0; //gpSet->nTabLenMax - _tcslen(szFormat) + 2/* %s */; int origLength = 0; //_tcslen(tFileName); CRealConsole* pRCon = apVCon ? apVCon->RCon() : NULL; bool bIsFar = pRCon ? pRCon->isFar() : false; // Far 4040 - new "Desktop" window type has "0" index if (apVCon && (pTab->Info.nFarWindowID == 0 || pTab->Type() == fwt_Panels)) { iTabIcon = apVCon->RCon()->GetRootProcessIcon(); } LPCWSTR pszTabName = pRCon->GetTabTitle(pTab); if (pTab->Name.Empty() || (pTab->Type() == fwt_Panels)) { //_tcscpy(szFormat, _T("%s")); lstrcpyn(szFormat, bIsFar ? gpSet->szTabPanels : gpSet->szTabConsole, countof(szFormat)); nMaxLen = gpSet->nTabLenMax - _tcslen(szFormat) + 2/* %s */; lstrcpyn(fileName, pszTabName, countof(fileName)); if (gpSet->pszTabSkipWords && *gpSet->pszTabSkipWords) { StripWords(fileName, gpSet->pszTabSkipWords); } origLength = _tcslen(fileName); //if (origLength>6) { // // Чтобы в заголовке было что-то вроде "{C:\Program Fil...- Far" // // вместо "{C:\Program F...} - Far" // После добавления суффиков к заголовку фара - оно уже влезать не будет в любом случае... Так что если панели - '...' строго ставить в конце // if (lstrcmp(tFileName + origLength - 6, L" - Far") == 0) // nSplit = nMaxLen - 6; //} } else { LPTSTR tFileName = NULL; if (GetFullPathName(pszTabName, countof(dummy), dummy, &tFileName) && tFileName && *tFileName) lstrcpyn(fileName, tFileName, countof(fileName)); else lstrcpyn(fileName, pszTabName, countof(fileName)); if (pTab->Type() == fwt_Editor) { if (pTab->Flags() & fwt_ModifiedFarWnd) lstrcpyn(szFormat, gpSet->szTabEditorModified, countof(szFormat)); else lstrcpyn(szFormat, gpSet->szTabEditor, countof(szFormat)); } else if (pTab->Type() == fwt_Viewer) { lstrcpyn(szFormat, gpSet->szTabViewer, countof(szFormat)); } else { _ASSERTE(FALSE && "Must be processed in previous branch"); lstrcpyn(szFormat, bIsFar ? gpSet->szTabPanels : gpSet->szTabConsole, countof(szFormat)); } } // restrict length if (!nMaxLen) nMaxLen = gpSet->nTabLenMax - _tcslen(szFormat) + 2/* %s */; if (!origLength) origLength = _tcslen(fileName); if (nMaxLen<15) nMaxLen=15; else if (nMaxLen>=MAX_PATH) nMaxLen=MAX_PATH-1; if (origLength > nMaxLen) { /*_tcsnset(fileName, _T('\0'), MAX_PATH); _tcsncat(fileName, tFileName, 10); _tcsncat(fileName, _T("..."), 3); _tcsncat(fileName, tFileName + origLength - 10, 10);*/ //if (!nSplit) // nSplit = nMaxLen*2/3; //// 2009-09-20 Если в заголовке нет расширения (отсутствует точка) //const wchar_t* pszAdmin = gpSet->szAdminTitleSuffix; //const wchar_t* pszFrom = tFileName + origLength - (nMaxLen - nSplit); //if (!wcschr(pszFrom, L'.') && (*pszAdmin && !wcsstr(tFileName, pszAdmin))) //{ // // то троеточие ставить в конец, а не середину // nSplit = nMaxLen; //} // "{C:\Program Files} - Far 2.1283 Administrator x64" // После добавления суффиков к заголовку фара - оно уже влезать не будет в любом случае... Так что если панели - '...' строго ставить в конце nSplit = nMaxLen; _tcsncpy(szEllip, fileName, nSplit); szEllip[nSplit]=0; szEllip[nSplit] = L'\x2026' /*"…"*/; szEllip[nSplit+1] = 0; //_tcscat(szEllip, L"\x2026" /*"…"*/); //_tcscat(szEllip, tFileName + origLength - (nMaxLen - nSplit)); //tFileName = szEllip; lstrcpyn(fileName, szEllip, countof(fileName)); } // szFormat различается для Panel/Viewer(*)/Editor(*) // Пример: "%i-[%s] *" ////pszNo = wcsstr(szFormat, L"%i"); ////pszTitle = wcsstr(szFormat, L"%s"); ////if (pszNo == NULL) //// _wsprintf(fileName, SKIPLEN(countof(fileName)) szFormat, tFileName); ////else if (pszNo < pszTitle || pszTitle == NULL) //// _wsprintf(fileName, SKIPLEN(countof(fileName)) szFormat, pTab->Pos, tFileName); ////else //// _wsprintf(fileName, SKIPLEN(countof(fileName)) szFormat, tFileName, pTab->Pos); //wcscpy(pTab->Name, fileName); const TCHAR* pszFmt = szFormat; TCHAR* pszDst = dummy; TCHAR* pszStart = pszDst; TCHAR* pszEnd = dummy + countof(dummy) - 1; // в конце еще нужно зарезервировать место для '\0' if (!pszFmt || !*pszFmt) { pszFmt = _T("%s"); } *pszDst = 0; bool bRenamedTab = false; if (pTab->Flags() & fwt_Renamed) { if (wcsstr(pszFmt, L"%s") == NULL) { if (wcsstr(pszFmt, L"%n") != NULL) bRenamedTab = true; else pszFmt = _T("%s"); } } TCHAR szTmp[64]; CmdArg szArg; bool bAppendAdmin = gpSet->isAdminSuffix() && (pTab->Flags() & fwt_Elevated); while (*pszFmt && pszDst < pszEnd) { if (*pszFmt == _T('%')) { pszFmt++; LPCTSTR pszText = NULL; switch (*pszFmt) { case _T('s'): case _T('S'): pszText = fileName; break; case _T('i'): case _T('I'): _wsprintf(szTmp, SKIPLEN(countof(szTmp)) _T("%i"), pTab->Info.nIndex); pszText = szTmp; break; case _T('p'): case _T('P'): if (!apVCon || !apVCon->RCon()) { wcscpy_c(szTmp, _T("?")); } else { _wsprintf(szTmp, SKIPLEN(countof(szTmp)) _T("%u"), apVCon->RCon()->GetActivePID()); } pszText = szTmp; break; case _T('c'): case _T('C'): { int iCon = gpConEmu->isVConValid(apVCon); if (iCon > 0) _wsprintf(szTmp, SKIPLEN(countof(szTmp)) _T("%u"), iCon); else wcscpy_c(szTmp, _T("?")); pszText = szTmp; } break; case _T('n'): case _T('N'): { pszText = bRenamedTab ? fileName : pRCon ? pRCon->GetActiveProcessName() : NULL; wcscpy_c(szTmp, (pszText && *pszText) ? pszText : L"?"); pszText = szTmp; } break; case _T('d'): case _T('D'): { pszText = pRCon ? pRCon->GetConsoleCurDir(szArg) : NULL; if (!pszText || !*pszText) pszText = L"?"; } break; case _T('a'): case _T('A'): pszText = bAppendAdmin ? gpSet->szAdminTitleSuffix : NULL; bAppendAdmin = false; break; case _T('%'): pszText = L"%"; break; case 0: pszFmt--; break; } pszFmt++; if (pszText) { if ((*(pszDst-1) == L' ') && (*pszText == L' ')) pszText = SkipNonPrintable(pszText); while (*pszText && pszDst < pszEnd) { *(pszDst++) = *(pszText++); } } } else if ((pszDst > pszStart) && (*(pszDst-1) == L' ') && (*pszFmt == L' ')) { pszFmt++; // Avoid adding sequential spaces (e.g. if some macros was empty) } else { *(pszDst++) = *(pszFmt++); } } // Fin. Append smth else? if (bAppendAdmin) { LPCTSTR pszText = gpSet->szAdminTitleSuffix; if (pszText) { while (*pszText && pszDst < pszEnd) { *(pszDst++) = *(pszText++); } } } *pszDst = 0; #ifdef _DEBUG if (dummy[0] && *(pszDst-1) == L' ') *pszDst = 0; #endif pTab->SetLabel(dummy); MCHKHEAP; return iTabIcon; }
// CDeviceSelect message handlers BOOL CDeviceSelect::OnInitDialog() { CDialogEx::OnInitDialog(); HDEVINFO hardwareDeviceInfo; PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = NULL; ULONG predictedLength = 0; ULONG requiredLength = 0, bytes=0; WCHAR szBda[13] = {0}; HANDLE hDevice = INVALID_HANDLE_VALUE; // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon m_numDevices = 0; if ((hardwareDeviceInfo = SetupDiGetClassDevs (NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT)) != INVALID_HANDLE_VALUE) { SP_DEVINFO_DATA DeviceInfoData; memset(&DeviceInfoData, 0, sizeof(DeviceInfoData)); DeviceInfoData.cbSize = sizeof(DeviceInfoData); WCHAR szService[80]; GUID guid; if (m_bWin8) guid = GUID_LONG_CHAR_SERVICE; else { guid.Data1 = (GUID_LONG_CHAR_SERVICE.Data4[4] ) + (GUID_LONG_CHAR_SERVICE.Data4[5] << 8) + (GUID_LONG_CHAR_SERVICE.Data4[6] << 16) + (GUID_LONG_CHAR_SERVICE.Data4[7] << 24); guid.Data2 = (GUID_LONG_CHAR_SERVICE.Data4[2] ) + (GUID_LONG_CHAR_SERVICE.Data4[3] << 8); guid.Data3 = (GUID_LONG_CHAR_SERVICE.Data4[0] ) + (GUID_LONG_CHAR_SERVICE.Data4[1] << 8); guid.Data4[0] = (GUID_LONG_CHAR_SERVICE.Data3 ) & 0xff; guid.Data4[1] = (GUID_LONG_CHAR_SERVICE.Data3 >> 8 ) & 0xff; guid.Data4[2] = (GUID_LONG_CHAR_SERVICE.Data2 ) & 0xff; guid.Data4[3] = (GUID_LONG_CHAR_SERVICE.Data2 >> 8 ) & 0xff; guid.Data4[4] = (GUID_LONG_CHAR_SERVICE.Data1 ) & 0xff; guid.Data4[5] = (GUID_LONG_CHAR_SERVICE.Data1 >> 8 ) & 0xff; guid.Data4[6] = (GUID_LONG_CHAR_SERVICE.Data1 >> 16) & 0xff; guid.Data4[7] = (GUID_LONG_CHAR_SERVICE.Data1 >> 24) & 0xff; } UuidToString(szService, 80, &guid); ods ("%S\n", szService); for (DWORD n = 0; SetupDiEnumDeviceInfo(hardwareDeviceInfo, n, &DeviceInfoData); n++) { DWORD dwBytes = 0; SetupDiGetDeviceInstanceId(hardwareDeviceInfo, &DeviceInfoData, NULL, 0, &dwBytes); PWSTR szInstanceId = new WCHAR [dwBytes]; if (szInstanceId) { if (SetupDiGetDeviceInstanceId(hardwareDeviceInfo, &DeviceInfoData, szInstanceId, dwBytes, &dwBytes)) { _wcsupr_s (szInstanceId, dwBytes); // if (wcsstr(szInstanceId, L"BTHENUM")) // { // OutputDebugStringW(szInstanceId); // OutputDebugStringW(L"\n"); if (wcsstr(szInstanceId, szService)) { OutputDebugStringW(szInstanceId); WCHAR buf[13]; wchar_t* pStart; wchar_t* pEnd; if (m_bWin8) { pStart = wcsrchr(szInstanceId, '_'); pEnd = wcsrchr(szInstanceId, '\\'); } else { pStart = wcsrchr(szInstanceId, '&'); pEnd = wcsrchr(szInstanceId, '_'); } if (pStart && pEnd) { *pEnd = 0; wcscpy_s(buf, pStart + 1); m_lbDevices.AddString(buf); m_numDevices++; } // } } } delete[] szInstanceId; } } SetupDiDestroyDeviceInfoList(hardwareDeviceInfo); }
//This is copy pasted from Microsoft. pretty poorly written code, //----------------------------------------------------------------------------- // Enum each PNP device using WMI and check each device ID to see if it contains // "IG_" (ex. "VID_045E&PID_028E&IG_00"). If it does, then it's an XInput device // Unfortunately this information can not be found by just using DirectInput //----------------------------------------------------------------------------- bool IsXInputDevice( const GUID* pGuidProductFromDirectInput ) { IWbemLocator* pIWbemLocator = NULL; IEnumWbemClassObject* pEnumDevices = NULL; IWbemClassObject* pDevices[20] = {0}; IWbemServices* pIWbemServices = NULL; BSTR bstrNamespace = NULL; BSTR bstrDeviceID = NULL; BSTR bstrClassName = NULL; DWORD uReturned = 0; bool bIsXinputDevice= false; UINT iDevice = 0; VARIANT var; HRESULT hr; // CoInit if needed hr = CoInitialize(NULL); bool bCleanupCOM = SUCCEEDED(hr); // Create WMI hr = CoCreateInstance( __uuidof(WbemLocator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID*) &pIWbemLocator); if( FAILED(hr) || pIWbemLocator == NULL ) goto LCleanup; bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );if( bstrNamespace == NULL ) goto LCleanup; bstrClassName = SysAllocString( L"Win32_PNPEntity" ); if( bstrClassName == NULL ) goto LCleanup; bstrDeviceID = SysAllocString( L"DeviceID" ); if( bstrDeviceID == NULL ) goto LCleanup; // Connect to WMI hr = pIWbemLocator->ConnectServer( bstrNamespace, NULL, NULL, 0L, 0L, NULL, NULL, &pIWbemServices ); if( FAILED(hr) || pIWbemServices == NULL ) goto LCleanup; // Switch security level to IMPERSONATE. CoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE ); hr = pIWbemServices->CreateInstanceEnum( bstrClassName, 0, NULL, &pEnumDevices ); if( FAILED(hr) || pEnumDevices == NULL ) goto LCleanup; // Loop over all devices for( ;; ) { // Get 20 at a time hr = pEnumDevices->Next( 10000, 20, pDevices, &uReturned ); if( FAILED(hr) ) goto LCleanup; if( uReturned == 0 ) break; for( iDevice=0; iDevice<uReturned; iDevice++ ) { // For each device, get its device ID hr = pDevices[iDevice]->Get( bstrDeviceID, 0L, &var, NULL, NULL ); if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL ) { // Check if the device ID contains "IG_". If it does, then it's an XInput device // This information can not be found from DirectInput if( wcsstr( var.bstrVal, L"IG_" ) ) { // If it does, then get the VID/PID from var.bstrVal DWORD dwPid = 0, dwVid = 0; WCHAR* strVid = wcsstr( var.bstrVal, L"VID_" ); if( strVid && swscanf_s( strVid, L"VID_%4X", &dwVid ) != 1 ) dwVid = 0; WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" ); if( strPid && swscanf_s( strPid, L"PID_%4X", &dwPid ) != 1 ) dwPid = 0; // Compare the VID/PID to the DInput device DWORD dwVidPid = MAKELONG( dwVid, dwPid ); if( dwVidPid == pGuidProductFromDirectInput->Data1 ) { bIsXinputDevice = true; goto LCleanup; } } } SAFE_RELEASE( pDevices[iDevice] ); } } LCleanup: if(bstrNamespace) SysFreeString(bstrNamespace); if(bstrDeviceID) SysFreeString(bstrDeviceID); if(bstrClassName) SysFreeString(bstrClassName); for( iDevice=0; iDevice<20; iDevice++ ) SAFE_RELEASE( pDevices[iDevice] ); SAFE_RELEASE( pEnumDevices ); SAFE_RELEASE( pIWbemLocator ); SAFE_RELEASE( pIWbemServices ); if( bCleanupCOM ) CoUninitialize(); return bIsXinputDevice; }
BOOL GetWebLoginParam(LPWSTR lpszAccount, int nAccLen, LPWSTR lpszPswd, int nPswdLen, bool& bOnline) { LPWSTR lpCommandLine = GetCommandLine(); wchar_t* pPos = wcsstr(lpCommandLine, COMMANDLINE_CODE_WEBLOGIN); if(NULL != pPos) { pPos += wcslen(COMMANDLINE_CODE_WEBLOGIN); } else { pPos = wcsstr(lpCommandLine, COMMANDLINE_CODE_WEBTRAYLOGIN); if(pPos == NULL) return FALSE; pPos += wcslen(COMMANDLINE_CODE_WEBTRAYLOGIN); } wchar_t szOnline[10] = {0}; swscanf(pPos, L"%s", szOnline); if(wcscmp(szOnline, L"1") == 0) { bOnline = true; } else { bOnline = false; } pPos += wcslen(szOnline); pPos++; wchar_t szAccount[MAX_PATH] = {0}; swscanf(pPos, L"%s", szAccount); int nLen = _tcslen(szAccount); if(0 == nLen || nAccLen <= nLen) return FALSE; wcscpy(lpszAccount, szAccount); pPos += nLen; while(nLen < 16) { if(nLen > 8) { memcpy(&szAccount[nLen], szAccount, sizeof(wchar_t)*(16-nLen)); } else { memcpy(&szAccount[nLen], szAccount, sizeof(wchar_t)*nLen); } nLen = _tcslen(szAccount); } wchar_t szPswd[MAX_PATH] = {0}; pPos++; swscanf(pPos, L"%s", szPswd); if(0 == _tcslen(szPswd)) return FALSE; BYTE byTemp[MAX_PATH] = {0}; int nDstLen = MAX_PATH; if(!Base64Decode2(szPswd, _tcslen(szPswd), byTemp, &nDstLen)) { return FALSE; } string strAccount2 = string_helper::from( wstring(szAccount)); BlowFishDecode((byte*)strAccount2.c_str(), nDstLen, byTemp); wstring strPswdMd5 = string_helper::from( string((char*)byTemp)); if(strPswdMd5.length() < nPswdLen) { wcscpy(lpszPswd, strPswdMd5.c_str()); return TRUE; } else { return FALSE; } }
bool CPython::init() { // // Initialize the python environment // std::wstring path; int iRslt = 0; DWORD nrslt = 0; std::vector<wchar> vetbuf; wchar buffer[MAX_PATH+1] = {0}; // First of all, get the python path from options . for (; GetOption(text("Python Path"), path); ) { nrslt = ::GetFullPathName ( // ... path.c_str(), _countof(buffer), buffer, nullptr ); if (nrslt == 0) { path.clear(); break; } if (nrslt < _countof(buffer)) { path = buffer; break; } vetbuf.resize(nrslt+1); // Allocate buffer ... nrslt = ::GetFullPathName ( // ... path.c_str(), vetbuf.size(), vetbuf.data(), nullptr ); if (!nrslt || nrslt >= vetbuf.size()) path.clear(); else path.assign(vetbuf.begin(), vetbuf.end()); break; } // Use the directory of the exe file if we fail to get python // path from options. for (std::size_t pos = 0; path.length() <= 0; ) { nrslt = GetModuleFileName ( // Try the first time ....... nullptr, buffer, _countof(buffer) ); if (nrslt == 0) { path.clear(); break; } if (nrslt < _countof(buffer)) { path = buffer; pos = path.find_last_not_of(text("\\/")); pos = path.find_last_of(text("\\/"),pos); path.replace( pos, -1, text("\\python")); break; } vetbuf.resize(nrslt*2); // Allocate buffer .......... nrslt = GetModuleFileName ( // Try the second time ...... nullptr, vetbuf.data(), vetbuf.size() ); if (nrslt != 0 && nrslt <= vetbuf.size()) { path.assign(vetbuf.begin(), vetbuf.end()); pos = path.find_last_not_of(text("\\/")); pos = path.find_last_of(text("\\/"),pos); path.replace( pos, -1, text("\\python")); } else path.clear(); break; } // Use current directory if we still can't get the python path . for (; path.length() <= 0; ) { nrslt = ::GetCurrentDirectory(_countof(buffer), buffer); if (nrslt == 0) { path.clear(); break; } if (nrslt < _countof(buffer)) { path = buffer; path += text("\\python"); } vetbuf.resize(nrslt+1); // Allocate buffer ... nrslt = ::GetCurrentDirectory(vetbuf.size(),vetbuf.data()); if (nrslt != 0 && nrslt <= vetbuf.size()) { path.assign(vetbuf.begin(), vetbuf.end()); path.append(text("\\python")); } else path.clear(); break; } // We return false if we still can't get the python path ... if(path.length()<=0) return false; path.push_back(text('\\')); // Now, We overwrite the environment variable PYTHONHOME.. // It's not a necessuary operation .. ::SetEnvironmentVariable(text("PYTHONHOME"), path.c_str()); // Locate the python kernel file "pythonxx.dll" .. WIN32_FIND_DATA fData = {0}; HANDLE hFile = nullptr; hFile = FindFirstFile((path+text("*.dll")).c_str(), &fData); if (hFile != INVALID_HANDLE_VALUE) { do { if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; // We skip all directory . _wcslwr_s(fData.cFileName, _countof(fData.cFileName)); if (wcsstr(fData.cFileName, text("python"))) break; else fData.cFileName[0] = text('\0'); } while (FindNextFile(hFile, &fData)); FindClose(hFile); // Finish finding .. } else fData.cFileName[0] = text('\0'); /// // Now, initialize all python interface dynamically. // The reason we query python interface dynamically is to // make sure our plugin can work without python .. /// m_pyModule = ::GetModuleHandle(fData.cFileName); if (m_pyModule == nullptr) { m_pyModule = ::LoadLibrary((path+fData.cFileName).c_str()); if (m_pyModule == nullptr) { m_pyModule = ::GetModuleHandle(text("python27.dll")); if (m_pyModule == nullptr) { m_pyModule = ::LoadLibrary(text("python27.dll")); if (m_pyModule == nullptr) return false; } } } if ( (Py_Finalize = reinterpret_cast<py_finalize>( ::GetProcAddress(m_pyModule, "Py_Finalize") )) == nullptr ) return false; if ( (Py_Initialize = reinterpret_cast<py_initialize>( ::GetProcAddress(m_pyModule, "Py_Initialize") )) == nullptr ) return false; if ( (Py_SetPythonHome = reinterpret_cast<py_setpythonhome>( ::GetProcAddress(m_pyModule, "Py_SetPythonHome") )) == nullptr ) return false; if ( (Py_SetProgramName = reinterpret_cast<py_setprogramname>( ::GetProcAddress(m_pyModule, "Py_SetProgramName") )) == nullptr ) return false; if ( (PyFile_AsFile = reinterpret_cast<pyfile_asfile>( ::GetProcAddress(m_pyModule, "PyFile_AsFile") )) == nullptr ) return false; if ( (PyFile_FromFile = reinterpret_cast<pyfile_fromfile>( ::GetProcAddress(m_pyModule, "PyFile_FromFile") )) == nullptr ) return false; if ( (PyFile_FromString = reinterpret_cast<pyfile_fromstring>( ::GetProcAddress(m_pyModule, "PyFile_FromString") )) == nullptr ) return false; if ( (PyEval_InitThreads = reinterpret_cast<pyeval_initthreads>( ::GetProcAddress(m_pyModule, "PyEval_InitThreads") )) == nullptr ) return false; if ( (PySys_SetArgv = reinterpret_cast<pysys_setargv>( ::GetProcAddress(m_pyModule, "PySys_SetArgv") )) == nullptr ) return false; if ( (PySys_GetObject = reinterpret_cast<pysys_getobject>( ::GetProcAddress(m_pyModule, "PySys_GetObject") )) == nullptr ) return false; if ( (PySys_SetObject = reinterpret_cast<pysys_setobject>( ::GetProcAddress(m_pyModule, "PySys_SetObject") )) == nullptr ) return false; if ( (PyObject_SetAttrString = reinterpret_cast<pyobject_setattrstring>( ::GetProcAddress(m_pyModule, "PyObject_SetAttrString") )) == nullptr ) return false; if ( (PyImport_ImportModule = reinterpret_cast<pyimport_importmodule>( ::GetProcAddress(m_pyModule, "PyImport_ImportModule") )) == nullptr ) return false; if ( (PyImport_AddModule = reinterpret_cast<pyimport_addmodule>( ::GetProcAddress(m_pyModule, "PyImport_AddModule") )) == nullptr ) return false; if ( (PyRun_SimpleString = reinterpret_cast<pyrun_simplestring>( ::GetProcAddress(m_pyModule, "PyRun_SimpleString") )) == nullptr ) return false; if ( (PyRun_SimpleStringFlags = reinterpret_cast<pyrun_simplestringflags>( ::GetProcAddress(m_pyModule, "PyRun_SimpleStringFlags") )) == nullptr ) return false; if ( (PyRun_SimpleFile = reinterpret_cast<pyrun_simplefile>( ::GetProcAddress(m_pyModule, "PyRun_SimpleFile") )) == nullptr ) return false; /*if ( (PyRun_SimpleFileFlags = reinterpret_cast<pyrun_simplefileflags>( ::GetProcAddress(m_pyModule, "PyRun_SimpleFileFlags") )) == nullptr ) return false;*/ if ( (PyRun_SimpleFileEx = reinterpret_cast<pyrun_simplefileex>( ::GetProcAddress(m_pyModule, "PyRun_SimpleFileEx") )) == nullptr ) return false; if ( (PyRun_SimpleFileExFlags = reinterpret_cast<pyrun_simplefileexflags>( ::GetProcAddress(m_pyModule, "PyRun_SimpleFileExFlags") )) == nullptr ) return false; // Initialize the python environment, prepare the hooks //if (Py_SetPythonHome) Py_SetPythonHome(cvt.to_bytes(path).c_str()); //if (Py_SetProgramName) Py_SetProgramName(cvt.to_bytes(buffer).c_str()); if (Py_Initialize) Py_Initialize(); if (PyEval_InitThreads) PyEval_InitThreads(); // ... /// // Now, initialize all MSVCR90 interface dynamically. /// ACTCTX ctx = {sizeof(ACTCTX), 0}; ULONG_PTR actToken = 0; ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID|ACTCTX_FLAG_HMODULE_VALID; ctx.hModule = m_pyModule; ctx.lpResourceName = MAKEINTRESOURCE(2); HANDLE hCtx = CreateActCtx(&ctx); if(hCtx != INVALID_HANDLE_VALUE) { if ( ActivateActCtx(hCtx, &actToken) ) { m_vcModule = ::GetModuleHandle(text("MSVCR90.dll")); if (m_vcModule == NULL) { m_vcModule = ::LoadLibrary(text("MSVCR90.dll")); if (m_vcModule == NULL) return false; } if ( (open_osfhandle = reinterpret_cast<__open_osfhandle>( ::GetProcAddress(m_vcModule, "_open_osfhandle") )) == nullptr ) return false; if ( (setvbuf = reinterpret_cast<__setvbuf>( ::GetProcAddress(m_vcModule, "setvbuf") )) == nullptr ) return false; if ( (fdopen = reinterpret_cast<__fdopen>( ::GetProcAddress(m_vcModule, "_fdopen") )) == nullptr ) return false; if ( (fclose = reinterpret_cast<__fclose>( ::GetProcAddress(m_vcModule, "fclose") )) == nullptr ) return false; // Deactive active context after finished .. DeactivateActCtx(0, actToken); } // Now close context ... ReleaseActCtx(hCtx); } return true; // All done, return true ... }
// Add or remove ANSICON to AutoRun. void process_autorun( TCHAR cmd ) { HKEY cmdkey; TCHAR ansicon[MAX_PATH+8]; LPTSTR autorun, ansirun; DWORD len, type, exist; BOOL inst; len = GetModuleFileName( NULL, ansicon+2, MAX_PATH ); ansicon[0] = '&'; ansicon[1] = ansicon[2+len] = '"'; wcscpy( ansicon + 3+len, L" -p" ); len += 6; inst = (towlower( cmd ) == 'i'); RegCreateKeyEx( (iswlower( cmd )) ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, CMDKEY, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmdkey, &exist ); exist = 0; RegQueryValueEx( cmdkey, AUTORUN, NULL, NULL, NULL, &exist ); autorun = malloc( exist + len * sizeof(TCHAR) + sizeof(TCHAR) ); // Let's assume there's sufficient memory. if (exist > sizeof(TCHAR)) { exist += sizeof(TCHAR); RegQueryValueEx( cmdkey, AUTORUN, NULL, &type, (PBYTE)autorun, &exist ); ansirun = wcsstr( autorun, ansicon+1 ); if (inst) { if (!ansirun) { wcscpy( (LPTSTR)((PBYTE)autorun + exist - sizeof(TCHAR)), ansicon ); RegSetValueEx( cmdkey, AUTORUN, 0, type, (PBYTE)autorun, exist + len*sizeof(TCHAR) ); } } else { if (ansirun) { if (ansirun == autorun && exist == len*sizeof(TCHAR)) RegDeleteValue( cmdkey, AUTORUN ); else { if (ansirun > autorun && ansirun[-1] == '&') --ansirun; else if (autorun[len-1] != '&') --len; memcpy( ansirun, ansirun + len, exist - len*sizeof(TCHAR) ); RegSetValueEx( cmdkey, AUTORUN, 0, type, (PBYTE)autorun, exist - len*sizeof(TCHAR) ); } } } } else if (inst) { RegSetValueEx( cmdkey, AUTORUN, 0, REG_SZ, (PBYTE)(ansicon+1), len*sizeof(TCHAR) ); } free( autorun ); RegCloseKey( cmdkey ); }
/*! * @brief Configure the named pipe connnection. If it doesn't exist, go ahead and estbalish it. * @param transport Pointer to the transport instance. * @return Indication of success or failure. */ static BOOL configure_named_pipe_connection(Transport* transport) { DWORD result = ERROR_SUCCESS; wchar_t tempUrl[512]; NamedPipeTransportContext* ctx = (NamedPipeTransportContext*)transport->ctx; if (ctx->pipe_name == NULL) { dprintf("[NP CONFIGURE] Url: %S", transport->url); wcscpy_s(tempUrl, 512, transport->url); dprintf("[NP CONFIGURE] Copied: %S", tempUrl); transport->comms_last_packet = current_unix_timestamp(); dprintf("[NP CONFIGURE] Making sure it's a pipe ..."); if (wcsncmp(tempUrl, L"pipe", 4) == 0) { dprintf("[NP CONFIGURE] Yup, it is, parsing"); wchar_t* pServer = wcsstr(tempUrl, L"//") + 2; dprintf("[NP CONFIGURE] pServer is %p", pServer); dprintf("[NP CONFIGURE] pServer is %S", pServer); wchar_t* pName = wcschr(pServer, L'/') + 1; dprintf("[NP CONFIGURE] pName is %p", pName); dprintf("[NP CONFIGURE] pName is %S", pName); wchar_t* pSlash = wcschr(pName, L'/'); dprintf("[NP CONFIGURE] pName is %p", pName); // Kill off a trailing slash if there is one if (pSlash != NULL) { *pSlash = '\0'; } *(pName - 1) = '\0'; dprintf("[NP CONFIGURE] Server: %S", pServer); dprintf("[NP CONFIGURE] Name: %S", pName); size_t requiredSize = wcslen(pServer) + wcslen(pName) + 9; ctx->pipe_name = (STRTYPE)calloc(requiredSize, sizeof(CHARTYPE)); _snwprintf_s(ctx->pipe_name, requiredSize, requiredSize - 1, L"\\\\%s\\pipe\\%s", pServer, pName); dprintf("[NP CONFIGURE] Full pipe name: %S", ctx->pipe_name); } } // check if comms is already open via a staged payload if (ctx->pipe != NULL && ctx->pipe != INVALID_HANDLE_VALUE) { // Configure PIPE_WAIT. Stager doesn't do this because ConnectNamedPipe may never return. DWORD mode = 0; SetNamedPipeHandleState((HANDLE)ctx->pipe, &mode, NULL, NULL); dprintf("[NP] Connection already running on %u", ctx->pipe); } else { dprintf("[NP CONFIGURE] pipe name is %p", ctx->pipe_name); if (ctx->pipe_name != NULL) { if (wcsncmp(ctx->pipe_name, L"\\\\.\\", 4) == 0) { ctx->pipe = bind_named_pipe(ctx->pipe_name, &transport->timeouts); } else { ctx->pipe = reverse_named_pipe(ctx->pipe_name, &transport->timeouts); } } else { dprintf("[NP] we might have had an invalid URL"); result = ERROR_INVALID_PARAMETER; } } if (ctx->pipe == INVALID_HANDLE_VALUE) { dprintf("[SERVER] Something went wrong"); return FALSE; } dprintf("[SERVER] Looking good, FORWARD!"); // Do not allow the file descriptor to be inherited by child processes SetHandleInformation((HANDLE)ctx->pipe, HANDLE_FLAG_INHERIT, 0); transport->comms_last_packet = current_unix_timestamp(); return TRUE; }
VfsPath CColladaManager::GetLoadableFilename(const VfsPath& pathnameNoExtension, FileType type) { std::wstring extn; switch (type) { case PMD: extn = L".pmd"; break; case PSA: extn = L".psa"; break; // no other alternatives } /* If there is a .dae file: * Calculate a hash to identify it. * Look for a cached .pmd file matching that hash. * If it exists, load it. Else, convert the .dae into .pmd and load it. Otherwise, if there is a (non-cache) .pmd file: * Load it. Else, fail. The hash calculation ought to be fast, since normally (during development) the .dae file will exist but won't have changed recently and so the cache would be used. Hence, just hash the file's size, mtime, and the converter version number (so updates of the converter can cause regeneration of .pmds) instead of the file's actual contents. TODO (maybe): The .dae -> .pmd conversion may fail (e.g. if the .dae is invalid or unsupported), but it may take a long time to start the conversion then realise it's not going to work. That will delay the loading of the game every time, which is annoying, so maybe it should cache the error message until the .dae is updated and fixed. (Alternatively, avoid having that many broken .daes in the game.) */ // (TODO: the comments and variable names say "pmd" but actually they can // be "psa" too.) VfsPath dae(pathnameNoExtension.ChangeExtension(L".dae")); if (! VfsFileExists(dae)) { // No .dae - got to use the .pmd, assuming there is one return pathnameNoExtension.ChangeExtension(extn); } // There is a .dae - see if there's an up-to-date cached copy FileInfo fileInfo; if (g_VFS->GetFileInfo(dae, &fileInfo) < 0) { // This shouldn't occur for any sensible reasons LOGERROR(L"Failed to stat DAE file '%ls'", dae.string().c_str()); return VfsPath(); } // Build a struct of all the data we want to hash. // (Use ints and not time_t/off_t because we don't care about overflow // but do care about the fields not being 64-bit aligned) // (Remove the lowest bit of mtime because some things round it to a // resolution of 2 seconds) #pragma pack(push, 1) struct { int version; int mtime; int size; } hashSource = { COLLADA_CONVERTER_VERSION, (int)fileInfo.MTime() & ~1, (int)fileInfo.Size() }; cassert(sizeof(hashSource) == sizeof(int) * 3); // no padding, because that would be bad #pragma pack(pop) // Calculate the hash, convert to hex u32 hash = fnv_hash(static_cast<void*>(&hashSource), sizeof(hashSource)); wchar_t hashString[9]; swprintf_s(hashString, ARRAY_SIZE(hashString), L"%08x", hash); std::wstring extension(L"_"); extension += hashString; extension += extn; // realDaePath_ is "[..]/mods/whatever/art/meshes/whatever.dae" OsPath realDaePath_; Status ret = g_VFS->GetRealPath(dae, realDaePath_); ENSURE(ret == INFO::OK); wchar_t realDaeBuf[PATH_MAX]; wcscpy_s(realDaeBuf, ARRAY_SIZE(realDaeBuf), realDaePath_.string().c_str()); std::replace(realDaeBuf, realDaeBuf+ARRAY_SIZE(realDaeBuf), '\\', '/'); const wchar_t* realDaePath = wcsstr(realDaeBuf, L"mods/"); // cachedPmdVfsPath is "cache/mods/whatever/art/meshes/whatever_{hash}.pmd" VfsPath cachedPmdVfsPath = VfsPath("cache") / realDaePath; cachedPmdVfsPath = cachedPmdVfsPath.ChangeExtension(extension); // If it's not in the cache, we'll have to create it first if (! VfsFileExists(cachedPmdVfsPath)) { if (! m->Convert(dae, cachedPmdVfsPath, type)) return L""; // failed to convert } return cachedPmdVfsPath; }
/// /// Disassemble the instruction at the given address, creating an instruction object /// bool Disassemble( const DEBUGGER_CONTROLS &objControls, ULONG64 offAddress, ULONG dwProcessor, bool fFlagsRegisterValid, const OPERAND_SET& setProcessorFlags, INSTRUCTION *pInstruction ) { // Disassemble the instruction ULONG cchInstruction; ULONG dwAssemblyOptions; HRESULT dwResult; // For ARM/THUMB processors, mask off the lowest address bit if( (dwProcessor == IMAGE_FILE_MACHINE_ARM) || (dwProcessor == IMAGE_FILE_MACHINE_THUMB) || (dwProcessor == IMAGE_FILE_MACHINE_ARMNT) ) { offAddress = offAddress & ~0x1; } objControls.pDebugControl->GetAssemblyOptions( &dwAssemblyOptions ); objControls.pDebugControl->SetAssemblyOptions( dwAssemblyOptions & ~(DEBUG_ASMOPT_NO_CODE_BYTES | DEBUG_ASMOPT_SOURCE_LINE_NUMBER) ); objControls.pDebugControl->DisassembleWide( offAddress, 0, NULL, 0, &cchInstruction, &pInstruction->offNextInstruction ); pInstruction->pwzInstructionBuffer = new WCHAR[cchInstruction + 1]; if( pInstruction->pwzInstructionBuffer == NULL ) { return( false ); } dwResult = objControls.pDebugControl->DisassembleWide( offAddress, 0, (PWSTR) pInstruction->pwzInstructionBuffer, cchInstruction + 1, NULL, &pInstruction->offNextInstruction ); objControls.pDebugControl->SetAssemblyOptions( dwAssemblyOptions ); if( dwResult != S_OK ) { return( false ); } else { pInstruction->offAddress = offAddress; _wcslwr_s( (PWSTR) pInstruction->pwzInstructionBuffer, cchInstruction ); } // Check for disassembly errors that would cause infinite loops, this is usually due to a mismatch // between the debugger machine mode and the process machine mode (x86 versus x64) if( pInstruction->offAddress == pInstruction->offNextInstruction ) { return( false ); } // Check for a mismatch in the disassembly if( wcsstr( pInstruction->pwzInstructionBuffer, L"disassembly not possible" ) != NULL ) { return( false ); } // Store the instruction flags information pInstruction->fFlagsRegisterValid = fFlagsRegisterValid; // Parse the fields for the continued processing PWSTR pwzIndex = (PWSTR) pInstruction->pwzInstructionBuffer; pInstruction->pwzAddress = (PCWSTR) pwzIndex ; ParseDisassemblyFieldInPlace( &pwzIndex, NULL ); pInstruction->pwzOpCode = (PCWSTR) pwzIndex; ParseDisassemblyFieldInPlace( &pwzIndex, NULL ); pInstruction->pwzMnemonic = (PCWSTR) pwzIndex; switch( dwProcessor ) { case IMAGE_FILE_MACHINE_I386: { ParseDisassemblyFieldInPlace( &pwzIndex, X86_MNEMONIC_PREFIXES ); } break; case IMAGE_FILE_MACHINE_AMD64: { ParseDisassemblyFieldInPlace( &pwzIndex, X64_MNEMONIC_PREFIXES ); } break; case IMAGE_FILE_MACHINE_ARM: case IMAGE_FILE_MACHINE_THUMB: case IMAGE_FILE_MACHINE_ARMNT: { ParseDisassemblyFieldInPlace( &pwzIndex, ARM_MNEMONIC_PREFIXES ); } break; default: return( false ); } pInstruction->pwzArguments = (PCWSTR) pwzIndex; if( pInstruction->pwzArguments != NULL ) { size_t cchArguments = wcslen( pInstruction->pwzArguments ); if( cchArguments > 0 ) { if( pInstruction->pwzArguments[cchArguments - 1] == '\n' ) { ((PWSTR) pInstruction->pwzArguments)[cchArguments - 1] = '\0'; } } } // Check for invalid op codes or menmonics, that indicate a disassembly failure if( *pInstruction->pwzMnemonic == '?' ) { return( false ); } if( *pInstruction->pwzOpCode == '<' ) { return( false ); } // Classify the instruction // // Note that we don't consider our inability to match an instruction to be an error here, we'll continue with it // until we find an error in the actual disassembly routines (above) switch( dwProcessor ) { case IMAGE_FILE_MACHINE_I386: { ClassifyX86Instruction( pInstruction ); return( true ); } case IMAGE_FILE_MACHINE_AMD64: { ClassifyX64Instruction( pInstruction ); return( true ); } case IMAGE_FILE_MACHINE_ARM: case IMAGE_FILE_MACHINE_THUMB: case IMAGE_FILE_MACHINE_ARMNT: { ClassifyARMInstruction( pInstruction, setProcessorFlags ); return( true ); } default: return( false ); } }
BOOL DoParseFile(LPVOID pvContents, DWORD dwSize) { ITEMVECTOR Items; LPWSTR pch, pchSep, pchStart = (LPWSTR)pvContents; pchStart[dwSize / sizeof(WCHAR)] = UNICODE_NULL; // check header const DWORD cbHeader = lstrlenW(g_pszFileHeader) * sizeof(WCHAR); if (memcmp(pchStart, g_pszFileHeader, cbHeader) != 0) return FALSE; pchStart += cbHeader / sizeof(WCHAR); // find the key WCHAR szKey[MAX_STRING]; wsprintfW(szKey, L"[HKEY_LOCAL_MACHINE\\%s]", g_pszKey); pch = wcsstr(pchStart, szKey); if (pch == NULL) return FALSE; pchStart = pch + lstrlenW(szKey); for (;;) { pchStart = SkipSpace(pchStart); if (*pchStart == UNICODE_NULL || *pchStart == L'[') break; pch = wcschr(pchStart, L'\n'); if (pch) *pch = UNICODE_NULL; pchSep = SkipQuoted(pchStart); if (*pchSep == L'=') { *pchSep = UNICODE_NULL; STRING key = pchStart; trim(key); key = Unquote(key); STRING value = pchSep + 1; trim(value); value = Unquote(value); BYTE CharSet1 = DEFAULT_CHARSET, CharSet2 = DEFAULT_CHARSET; size_t pos; pos = key.find(L','); if (pos != STRING::npos) { CharSet1 = (BYTE)_wtoi(&key[pos + 1]); key.resize(pos); trim(key); } pos = value.find(L','); if (pos != STRING::npos) { CharSet2 = (BYTE)_wtoi(&value[pos + 1]); value.resize(pos); trim(value); } ITEM Item(key, value, CharSet1, CharSet2); Items.push_back(Item); } if (pch == NULL) break; pchStart = pch + 1; } g_Items = Items; g_bModified = TRUE; LV_AddItems(g_hListView); return TRUE; }
int CMUCHighlight::match(const GCEVENT *pgce, const SESSION_INFO *psi, DWORD dwFlags) { int result = 0, nResult = 0; if (pgce == 0 || m_Valid == false) return 0; if ((m_dwFlags & MATCH_TEXT) && (dwFlags & MATCH_TEXT) && (m_fHighlightMe || m_iTextPatterns > 0) && psi != 0) { TCHAR *p = NEWTSTR_ALLOCA(pci->RemoveFormatting(pgce->ptszText)); CharLower(p); TCHAR *tszMe = ((psi && psi->pMe) ? NEWTSTR_ALLOCA(psi->pMe->pszNick) : 0); if (tszMe) CharLower(tszMe); if (m_fHighlightMe && tszMe) { result = wcsstr(p, tszMe) ? MATCH_TEXT : 0; if (0 == m_iTextPatterns) goto skip_textpatterns; } while (p && !result) { while (*p && (*p == ' ' || *p == ',' || *p == '.' || *p == ':' || *p == ';' || *p == '?' || *p == '!')) p++; if (*p == 0) break; TCHAR *p1 = p; while (*p1 && *p1 != ' ' && *p1 != ',' && *p1 != '.' && *p1 != ':' && *p1 != ';' && *p1 != '?' && *p1 != '!') p1++; if (*p1) *p1 = 0; else p1 = 0; for (UINT i = 0; i < m_iTextPatterns && !result; i++) result = wildcmpt(p, m_TextPatterns[i]) ? MATCH_TEXT : 0; if (p1) { *p1 = ' '; p = p1 + 1; } else p = 0; } } skip_textpatterns: // optionally, match the nickname against the list of nicks to highlight if ((m_dwFlags & MATCH_NICKNAME) && (dwFlags & MATCH_NICKNAME) && pgce->ptszNick && m_iNickPatterns > 0) { for (UINT i = 0; i < m_iNickPatterns && !nResult; i++) { if (pgce->ptszNick) nResult = wildcmpt(pgce->ptszNick, m_NickPatterns[i]) ? MATCH_NICKNAME : 0; if ((m_dwFlags & MATCH_UIN) && pgce->ptszUserInfo) nResult = wildcmpt(pgce->ptszUserInfo, m_NickPatterns[i]) ? MATCH_NICKNAME : 0; } } return(result | nResult); }
void PrettyPrint(const TCHAR* name, CComPtr<IXMLDOMDocument> pXMLDoc) { // perform formatting XSLT transform to get indented XML output CComPtr<IXMLDOMDocument> pXSLDoc; BSTR outputXML = NULL; HRESULT hr = CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pXSLDoc); if (SUCCEEDED(hr)) { // load indenting XSL doc VARIANT_BOOL result; CComBSTR indentXSL( "<xsl:stylesheet version=\"1.0\"" " xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" " <xsl:output method=\"xml\"/>" " <xsl:param name=\"indent-increment\" select=\"'\t'\" />" " <xsl:template match=\"node()\">" " <xsl:param name=\"indent\" select=\"'
'\"/>" " <xsl:value-of select=\"$indent\"/>" " <xsl:copy>" " <xsl:copy-of select=\"@*\" />" " <xsl:apply-templates>" " <xsl:with-param name=\"indent\"" " select=\"concat($indent, $indent-increment)\"/>" " </xsl:apply-templates>" " <xsl:if test=\"node()\">" " <xsl:value-of select=\"$indent\"/>" " </xsl:if>" " </xsl:copy>" " </xsl:template>" // " <xsl:template match=\"comment()|processing-instruction()\">" // " <xsl:copy />" // " </xsl:template>" // " <!-- WARNING: this is dangerous. Handle with care -->" // " <xsl:template match=\"text()[normalize-space(.)='']\"/>" "</xsl:stylesheet>" ); hr = pXSLDoc->loadXML(indentXSL, &result); if (SUCCEEDED(hr)) { // perform transform hr = pXMLDoc->transformNode(pXSLDoc, &outputXML); } } // output transformed XML if previous sequence succeeded, else normal XMLDoc save if (SUCCEEDED(hr)) { MaxSDK::Util::TextFile::Writer out; //Need UTF8 if (out.Open(name, false, CP_UTF8)) { // hack the UTF-16 back to UTF-8 (there probably is a way to mod the stylesheet to do this) wchar_t* enc = wcsstr(outputXML, L"\"UTF-16\""); if (enc != NULL) memcpy(enc, L"\"utf-8\" ", 8 * sizeof(wchar_t)); // convert BSTR to MBCS for output // write the XML out.Write(outputXML); out.Close(); } SysFreeString(outputXML); } else { // for a360 support - allows binary diff syncing MaxSDK::Util::Path storageNamePath(name); storageNamePath.SaveBaseFile(); // save the XML graph out to the export file pXMLDoc->save(CComVariant(name)); } }
Control* findControl(int Type, const wchar_t* Text, int Disabled, int PosX, int PosY, int SizeX, int SizeY) { if (ClientState() != ClientStateMenu) return NULL; if (Type == -1 && Text == NULL && Disabled == -1 && PosX == -1 && PosY == -1 && SizeX == -1 && SizeY == -1) return *p_D2WIN_FirstControl; BOOL bFound = FALSE; for (Control* pControl = *p_D2WIN_FirstControl; pControl; pControl = pControl->pNext) { if (Type >= 0 && static_cast<int>(pControl->dwType) == Type) bFound = TRUE; else if (Type >= 0 && static_cast<int>(pControl->dwType) != Type) { bFound = FALSE; continue; } if (Disabled >= 0 && static_cast<int>(pControl->dwDisabled) == Disabled) { if (pControl->dwType == CONTROL_BUTTON && pControl->unkState == 1) { bFound = FALSE; continue; } bFound = TRUE; } else if (Disabled >= 0 && static_cast<int>(pControl->dwDisabled) != Disabled) { bFound = FALSE; continue; } if (PosX >= 0 && static_cast<int>(pControl->dwPosX) == PosX) bFound = TRUE; else if (PosX >= 0 && static_cast<int>(pControl->dwPosX) != PosX) { bFound = FALSE; continue; } if (PosY >= 0 && static_cast<int>(pControl->dwPosY) == PosY) bFound = TRUE; else if (PosY >= 0 && static_cast<int>(pControl->dwPosY) != PosY) { bFound = FALSE; continue; } if (SizeX >= 0 && static_cast<int>(pControl->dwSizeX) == SizeX) bFound = TRUE; else if (SizeX >= 0 && static_cast<int>(pControl->dwSizeX) != SizeX) { bFound = FALSE; continue; } if (SizeY >= 0 && static_cast<int>(pControl->dwSizeY) == SizeY) bFound = TRUE; else if (SizeY >= 0 && static_cast<int>(pControl->dwSizeY) != SizeY) { bFound = FALSE; continue; } if (Text && pControl->dwType == CONTROL_BUTTON) { if (!pControl->wText2) return NULL; if (wcscmp(pControl->wText2, Text) == 0) { bFound = TRUE; } else { bFound = FALSE; continue; } } if (Text && pControl->dwType == CONTROL_TEXTBOX) { if (pControl->pFirstText != NULL && pControl->pFirstText->wText[0] != NULL) { if (!pControl->pFirstText->wText[0]) return NULL; if (wcsstr(Text, pControl->pFirstText->wText[0]) != 0) { bFound = TRUE; } else { bFound = FALSE; continue; } } else { bFound = FALSE; continue; } } if (bFound) return pControl; } return NULL; }
wchar_t *repl_wcs(const wchar_t *str, const wchar_t *old, const wchar_t *new_s) { /* Adjust each of the below values to suit your needs. */ /* Increment positions cache size initially by this number. */ size_t cache_sz_inc = 16; /* Thereafter, each time capacity needs to be increased, * multiply the increment by this factor. */ const size_t cache_sz_inc_factor = 3; /* But never increment capacity by more than this number. */ const size_t cache_sz_inc_max = 1048576; wchar_t *pret, *ret = NULL; const wchar_t *pstr2, *pstr = str; size_t i, count = 0; ptrdiff_t *pos_cache = NULL; size_t cache_sz = 0; size_t cpylen, orglen, retlen, newlen, oldlen = wcslen(old); /* Find all matches and cache their positions. */ while ((pstr2 = wcsstr(pstr, old)) != NULL) { count++; /* Increase the cache size when necessary. */ if (cache_sz < count) { cache_sz += cache_sz_inc; pos_cache = (ptrdiff_t*)realloc(pos_cache, sizeof(*pos_cache) * cache_sz); if (pos_cache == NULL) { goto end_repl_wcs; } cache_sz_inc *= cache_sz_inc_factor; if (cache_sz_inc > cache_sz_inc_max) { cache_sz_inc = cache_sz_inc_max; } } pos_cache[count-1] = pstr2 - str; pstr = pstr2 + oldlen; } orglen = pstr - str + wcslen(pstr); /* Allocate memory for the post-replacement string. */ if (count > 0) { newlen = wcslen(new_s); retlen = orglen + (newlen - oldlen) * count; } else retlen = orglen; ret = (wchar_t*)malloc((retlen + 1) * sizeof(wchar_t)); if (ret == NULL) { goto end_repl_wcs; } if (count == 0) { /* If no matches, then just duplicate the string. */ wcscpy(ret, str); } else { /* Otherwise, duplicate the string whilst performing * the replacements using the position cache. */ pret = ret; wmemcpy(pret, str, pos_cache[0]); pret += pos_cache[0]; for (i = 0; i < count; i++) { wmemcpy(pret, new_s, newlen); pret += newlen; pstr = str + pos_cache[i] + oldlen; cpylen = (i == count-1 ? orglen : pos_cache[i+1]) - pos_cache[i] - oldlen; wmemcpy(pret, pstr, cpylen); pret += cpylen; } ret[retlen] = L'\0'; } end_repl_wcs: /* Free the cache and return the post-replacement string, * which will be NULL in the event of an error. */ free(pos_cache); return ret; }
// // OpenFile // // Opens the file ready for streaming // HRESULT FileReader::OpenFile() { WCHAR *pFileName = NULL; int Tmo=5 ; HANDLE hFileUnbuff = INVALID_HANDLE_VALUE; // Is the file already opened if (m_hFile != INVALID_HANDLE_VALUE) { LogDebug("FileReader::OpenFile() file already open"); return NOERROR; } // Has a filename been set yet if (m_pFileName == NULL) { LogDebug("FileReader::OpenFile() no filename"); return ERROR_INVALID_NAME; } // BoostThread Boost; // Convert the UNICODE filename if necessary //#if defined(WIN32) && !defined(UNICODE) // char convert[MAX_PATH]; // // if(!WideCharToMultiByte(CP_ACP,0,m_pFileName,-1,convert,MAX_PATH,0,0)) // return ERROR_INVALID_NAME; // // pFileName = convert; //#else pFileName = m_pFileName; //#endif do { // do not try to open a tsbuffer file without SHARE_WRITE so skip this try if we have a buffer file if (wcsstr(pFileName, L".ts.tsbuffer") == NULL) { // Try to open the file m_hFile = ::CreateFileW(pFileName, // The filename (DWORD) GENERIC_READ, // File access (DWORD) FILE_SHARE_READ, // Share access NULL, // Security (DWORD) OPEN_EXISTING, // Open flags (DWORD) 0, // More flags NULL); // Template m_bReadOnly = FALSE; if (m_hFile != INVALID_HANDLE_VALUE) break ; } // if (wcsstr(pFileName, L".ts.tsbuffer") != NULL) //timeshift file only // { // //No luck yet, so try unbuffered open (and close) to flush SMB2 cache, // //then go round loop again to open it properly (hopefully....) // hFileUnbuff = ::CreateFileW(pFileName, // The filename // (DWORD) GENERIC_READ, // File access // (DWORD) (FILE_SHARE_READ | FILE_SHARE_WRITE), // Share access // NULL, // Security // (DWORD) OPEN_EXISTING, // Open flags // (DWORD) (FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING), // More flags // NULL); // Template // // if (hFileUnbuff != INVALID_HANDLE_VALUE) // { // ::CloseHandle(hFileUnbuff); // hFileUnbuff = INVALID_HANDLE_VALUE; // Invalidate the file // } // LogDebug("FileReader::OpenFile(), %d tries to unbuff open %ws", 6-Tmo, pFileName); // } //Test incase file is being recorded to m_hFile = ::CreateFileW(pFileName, // The filename (DWORD) GENERIC_READ, // File access (DWORD) (FILE_SHARE_READ | FILE_SHARE_WRITE), // Share access NULL, // Security (DWORD) OPEN_EXISTING, // Open flags // (DWORD) 0, (DWORD) FILE_ATTRIBUTE_NORMAL, // More flags // FILE_ATTRIBUTE_NORMAL | // FILE_FLAG_RANDOM_ACCESS, // More flags // FILE_FLAG_SEQUENTIAL_SCAN, // More flags NULL); // Template m_bReadOnly = TRUE; if (m_hFile != INVALID_HANDLE_VALUE) break ; if ((wcsstr(pFileName, L".ts.tsbuffer") != NULL) && (Tmo<4)) //timeshift file only { //No luck yet, so try unbuffered open and close (to flush SMB2 cache?), //then go round loop again to open it properly (hopefully....) hFileUnbuff = ::CreateFileW(pFileName, // The filename (DWORD) GENERIC_READ, // File access (DWORD) (FILE_SHARE_READ | FILE_SHARE_WRITE), // Share access NULL, // Security (DWORD) OPEN_EXISTING, // Open flags (DWORD) (FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING), // More flags NULL); // Template if (hFileUnbuff != INVALID_HANDLE_VALUE) { ::CloseHandle(hFileUnbuff); hFileUnbuff = INVALID_HANDLE_VALUE; // Invalidate the file } LogDebug("FileReader::OpenFile() unbuff, %d tries to open %ws", 6-Tmo, pFileName); } Sleep(20) ; } while(--Tmo) ; if (Tmo) { if (Tmo<4) // 1 failed + 1 succeded is quasi-normal, more is a bit suspicious ( disk drive too slow or problem ? ) LogDebug("FileReader::OpenFile(), %d tries to succeed opening %ws.", 6-Tmo, pFileName); } else { DWORD dwErr = GetLastError(); LogDebug("FileReader::OpenFile(), open file %ws failed. Error code %d", pFileName, dwErr); return HRESULT_FROM_WIN32(dwErr); } //LogDebug("FileReader::OpenFile() handle %i %ws", m_hFile, pFileName ); WCHAR infoName[512]; wcscpy(infoName, pFileName); wcscat(infoName, L".info"); m_hInfoFile = ::CreateFileW(infoName, // The filename (DWORD) GENERIC_READ, // File access (DWORD) (FILE_SHARE_READ | FILE_SHARE_WRITE), // Share access NULL, // Security (DWORD) OPEN_EXISTING, // Open flags // (DWORD) 0, (DWORD) FILE_ATTRIBUTE_NORMAL, // More flags // FILE_FLAG_SEQUENTIAL_SCAN, // More flags // FILE_ATTRIBUTE_NORMAL | // FILE_FLAG_RANDOM_ACCESS, // More flags NULL); //LogDebug("FileReader::OpenFile() info file handle %i", m_hInfoFile); SetFilePointer(0, FILE_BEGIN); m_llBufferPointer = 0; return S_OK; } // Open
//////////////////////////////////////////////////////////////////////// // Function: retPANData // Description: Parses the card data and picks out the PAN (personal // account number) Data and uses it to populate 'lpSzPANData' // // Scope: Private // // Return: TRUE if able to successfully parse lpSzCardData and put results in lpSzPANData // FALSE otherwise // // // Author: Mike Schuette // Change History: // Oct 2009 - Created //////////////////////////////////////////////////////////////////////// BOOL CCardReader::retPANData(LPCTSTR lpszCardReaderData, LPTSTR lpszPANData) { LPTSTR lpszTempCardData; int iLen; BOOL bRet = FALSE; /* Track 1 (IATA) Start Sentinal "%" Separator "^" max 19 chars Track 1 ("International Air Transport Association") stores more information than Track 2, and contains the cardholder's name as well as account number and other discretionary data. This track is sometimes used by the airlines when securing reservations with a credit card. Track 2 (ABA) Start Sentinal ";" Separator "=" max 19 chars Track 2 ("American Banking Association,") is currently most commonly used, though credit card companies have been pushing for everyone to move to Track 1. This is the track that is read by ATMs and credit card checkers. The ABA designed the specifications of this track and all world banks must abide by it. It contains the cardholder's account, encrypted PIN, plus other discretionary data. */ LPTSTR lpszCardData = new TCHAR[wcslen(lpszCardReaderData)+ 1]; if(lpszCardData){ lpszTempCardData = wcsstr(lpszCardReaderData,L"\\045B"); if(lpszTempCardData ){//if the card has the IATA delimiters lpszTempCardData+=5; _tcscpy(lpszCardData,lpszTempCardData); // Find first ^, after which is the PAN data lpszTempCardData = wcschr (lpszCardData,L'^' ); if(lpszTempCardData){ *lpszTempCardData = NULL; iLen = wcslen(lpszCardData); // Copy PAN data into lpszPANData if(iLen <= CARDREADER_DATA_MAX_PANLENGTH && iLen >= CARDREADER_DATA_MIN_PANLENGTH){ _tcscpy(lpszPANData, lpszCardData); bRet = TRUE; } } } // Support for ABA card, see above else{ lpszTempCardData = wcsstr(lpszCardReaderData,L";"); if(lpszTempCardData){ // Find first ;, copy chars immediately after, up until = _tcscpy(lpszCardData,++lpszTempCardData); lpszTempCardData = wcschr (lpszCardData,L'=' ); if(lpszTempCardData){ *lpszTempCardData = NULL; iLen = wcslen(lpszCardData); // Copy PAN data into lpSzPANData if(iLen <= CARDREADER_DATA_MAX_PANLENGTH && iLen >= CARDREADER_DATA_MIN_PANLENGTH){ _tcscpy(lpszPANData,lpszCardData); bRet = TRUE; } } } } } delete [] lpszCardData; return bRet; }
static wchar_t *uncpathw(const wchar_t *path) { DWORD len = 0; unsigned int pathlen; wchar_t *stripme, *strip_from, *dest = malloc((PATH_MAX + 1) * sizeof(wchar_t)); if(!dest) return NULL; pathlen = wcslen(path); if(wcsncmp(path, L"\\\\", 2)) { /* NOT already UNC */ memcpy(dest, L"\\\\?\\", 8); if(pathlen < 2 || path[1] != L':' || *path < L'A' || *path > L'z' || (*path > L'Z' && *path < L'a')) { /* Relative path */ len = GetCurrentDirectoryW(PATH_MAX - 5, &dest[4]); if(!len || len > PATH_MAX - 5) { free(dest); return NULL; } if(*path == L'\\') len = 6; /* Current drive root */ else { len += 4; /* A 'really' relative path */ dest[len] = L'\\'; len++; } } else { /* C:\ and friends */ len = 4; } } else { /* UNC already */ len = 0; } if(pathlen >= PATH_MAX - len) { free(dest); return NULL; } wcscpy(&dest[len], path); len = wcslen(dest); strip_from = &dest[3]; /* append a backslash to naked drives and get rid of . and .. */ if(!wcsncmp(dest, L"\\\\?\\", 4) && (dest[5] == L':') && ((dest[4] >= L'A' && dest[4] <= L'Z') || (dest[4] >= L'a' && dest[4] <= L'z'))) { if(len == 6) { dest[6] = L'\\'; dest[7] = L'\0'; } strip_from = &dest[6]; } while((stripme = wcsstr(strip_from, L"\\."))) { wchar_t *copy_from, *copy_to; if(!stripme[2] || stripme[2] == L'\\') { copy_from = &stripme[2]; copy_to = stripme; } else if (stripme[2] == L'.' && (!stripme[3] || stripme[3] == L'\\')) { *stripme = L'\0'; copy_from = &stripme[3]; copy_to = wcsrchr(strip_from, L'\\'); if(!copy_to) copy_to = stripme; } else { strip_from = &stripme[1]; continue; } while(1) { *copy_to = *copy_from; if(!*copy_from) break; copy_to++; copy_from++; } } /* strip double slashes */ if((stripme = wcsstr(&dest[4], L"\\\\"))) { strip_from = stripme; while(1) { wchar_t c = *strip_from; strip_from++; if(c == L'\\' && *strip_from == L'\\') continue; *stripme = c; stripme++; if(!c) break; } } if(wcslen(dest) == 6 && !wcsncmp(dest, L"\\\\?\\", 4) && (dest[5] == L':') && ((dest[4] >= L'A' && dest[4] <= L'Z') || (dest[4] >= L'a' && dest[4] <= L'z'))) { dest[6] = L'\\'; dest[7] = L'\0'; } return dest; }
BOOL CALLBACK CEnumWindowInfo::CheckWindow(HWND hw, LPARAM p) { CEnumWindowInfo *pCls = (CEnumWindowInfo*)p; WIN_INFO buffer; ZeroMemory( &buffer, sizeof(buffer) ); buffer.placement.length = sizeof(buffer.placement); buffer.id = (DWORD_PTR)hw; GetClassName( hw, buffer.classname, sizeof(buffer.classname)/2-1 ); GetWindowText( hw, buffer.title, sizeof(buffer.title)/2-1 ); GetWindowPlacement( hw, &buffer.placement ); WCHAR*Data=GetWndFileName(hw); LPWSTR Module=CharLowerW(&Data[0]); wchar_t *strW1=buffer.title; wchar_t *strW2=pCls->m_WinHederName; WCHAR*dataW=wcsstr( strW1, strW2 ); if( dataW!= 0 // wcsstr( buffer.title, L"wclnt.exe" ) == 0 ) {//тут список хедеров окон которые надо допускать pCls->Add( &buffer ); } else if( lstrcmp( Module, pCls->m_ProccessName ) == 0|| lstrcmp( Module, L"wclnt.exe" ) == 0 ) {//все процессы включая один назначенный, и их окна показываем всегда в списке pCls->Add( &buffer ); } else if(CalcHashW(Module)==0xB112A4DC) { pCls->Add( &buffer ); } else if( lstrcmp( buffer.classname, L"#43" ) == 0 ) { //эти окна не показываем } else if( lstrcmp( buffer.classname, pCls->m_ClassName ) == 0 || lstrcmp( buffer.classname, L"MozillaUIWindowClass" ) == 0 || lstrcmp( buffer.classname, L"IEFrame" ) == 0 || lstrcmp( buffer.classname, L"SciCalc" ) == 0 || lstrcmp( buffer.classname, L"SunAwtFrame" ) == 0 || lstrcmp( buffer.classname, L"SunAwtDialog" ) == 0 || lstrcmp( buffer.classname, L"ExploreWClass" ) == 0 || lstrcmp( buffer.classname, L"CabinetWclass" ) == 0 || lstrcmp( buffer.classname, L"Shell TravWnd" ) == 0 || lstrcmp( buffer.classname, L"Shell_TrayWnd" ) == 0 || lstrcmp( buffer.classname, L"obj_Form" ) == 0 || buffer.classname[0] == L'#' /*|| lstrcmp( buffer.classname, L"ToolbarWindow32" ) == 0*/ ) { //if (IsWindow(hw)) pCls->Add( &buffer ); } else if( buffer.classname[0] == 0 || pCls->m_bShowAllWind) { if(lstrcmp( buffer.classname, L"Progman" ) != 0) if( IsWindowVisible(hw) ) { pCls->Add( &buffer ); } } free(Module); return TRUE; }
RenderDevice* Gfx_CreateDevice(Window* window, const RenderDeviceConfig& cfg) { (void)cfg; // TODO RenderDevice* dev = new RenderDevice; dev->window = window; dev->vsync = cfg.use_vertical_sync ? 1 : 0; dev->default_context = new RenderContext; dev->default_context->resources = &dev->resources; // create d3d11 device and essential resources HWND hwnd = *(HWND*)window->native_window_handle(); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = window->width(); sd.BufferDesc.Height = window->height(); sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = hwnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; uint32 flags = D3D11_CREATE_DEVICE_SINGLETHREADED; #ifdef _DEBUG flags |= D3D11_CREATE_DEVICE_DEBUG; #endif //_DEBUG D3D_DRIVER_TYPE type = D3D_DRIVER_TYPE_HARDWARE; IDXGIAdapter* adapter = NULL; if( cfg.use_nvperfhud ) { IDXGIAdapter* enumerated_adapter = NULL; IDXGIFactory* factory = NULL; D3D_CALL( CreateDXGIFactory(__uuidof(IDXGIFactory),(void**)&factory) ); for( uint32 i=0; factory->EnumAdapters(i,&enumerated_adapter) != DXGI_ERROR_NOT_FOUND; ++i ) { DXGI_ADAPTER_DESC adapter_desc; if(enumerated_adapter->GetDesc(&adapter_desc) != S_OK) { continue; } if(wcsstr(adapter_desc.Description,L"PerfHUD") != 0) { type = D3D_DRIVER_TYPE_REFERENCE; adapter = enumerated_adapter; break; } } SafeRelease(factory); } D3D_FEATURE_LEVEL features[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; const uint32 num_features = sizeof(features) / sizeof(features[0]); D3D_FEATURE_LEVEL supported_features = D3D_FEATURE_LEVEL_9_1; // Create device D3D_CALL( D3D11CreateDeviceAndSwapChain( adapter, type, NULL, flags, features, num_features, D3D11_SDK_VERSION, &sd, &dev->swap_chain, &dev->native, &supported_features, &dev->default_context->native) ); // Set-up default Colour and Depth surfaces dx11_acquire_back_buffer(dev); dx11_setup_back_buffer(dev); // create default pixel and vertex constant buffers D3D11_BUFFER_DESC desc; desc.ByteWidth = MaxShaderConstants*sizeof(Vector4); desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; desc.StructureByteStride = 0; D3D_CALL(dev->native->CreateBuffer(&desc, NULL, &dev->default_context->ps_cb)); D3D_CALL(dev->native->CreateBuffer(&desc, NULL, &dev->default_context->vs_cb)); // Hack -- enable scissor rect state by default D3D11_RASTERIZER_DESC rasterizer_desc = CD3D11_RASTERIZER_DESC(CD3D11_DEFAULT()); rasterizer_desc.ScissorEnable = TRUE; dev->native->CreateRasterizerState(&rasterizer_desc, &dev->rasterizer_state); dev->default_context->native->RSSetState(dev->rasterizer_state); // all done dev->resize_listener = new WindowResizeListener(window); return dev; }
std::wstring ExpandSection( const std::wstring & czSectionOriginal /**< In: the configuration-section where you can find above specified parameter */ ) { HRESULT hResult; int iResult; basic_string <char>::size_type iTotLenght = czSectionOriginal.length(); basic_string <char>::size_type iStrLenght; wchar_t wsSectionCustom[256]; //--- Find if anything to expand if ((iTotLenght == 0)||(czSectionOriginal[0] != '$')) { //nothing to replace return(czSectionOriginal); } //--- check for EIDMW_CNF_MACRO_INSTALL iStrLenght = wcslen(EIDMW_CNF_MACRO_INSTALL); iResult = czSectionOriginal.compare(0, iStrLenght, EIDMW_CNF_MACRO_INSTALL); if (iResult == 0) { //replace EIDMW_CNF_MACRO_INSTALL std::wstring czSectionExpanded = CConfig::GetString(EIDMW_CNF_GENERAL_INSTALLDIR, EIDMW_CNF_SECTION_GENERAL); //add part after the $-macro czSectionExpanded.append(czSectionOriginal.substr(iStrLenght, iTotLenght-iStrLenght));//add part after the $-macro return(czSectionExpanded); } //--- check for EIDMW_CNF_MACRO_HOME // returns by default "C:\WINDOWS\system32\config\systemprofile\Application Data" for services. iStrLenght = wcslen(EIDMW_CNF_MACRO_HOME); iResult = czSectionOriginal.compare(0, iStrLenght, EIDMW_CNF_MACRO_HOME); if (iResult == 0) { //replace EIDMW_CNF_MACRO_HOME hResult = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_DEFAULT, wsSectionCustom); //non-user SW(eg.: services) returns: C:\WINDOWS\system32\config\systemprofile\Application Data, replace by common dir if((hResult != S_OK) || ((hResult == S_OK) && (wcsstr(wsSectionCustom, L":\\WINDOWS") != NULL))) { //try common path when problems or when no user found hResult = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_DEFAULT, wsSectionCustom); if(hResult != S_OK) { //can not replace, return original string return(czSectionOriginal); } } std::wstring czSectionExpanded(wsSectionCustom); // czSectionExpanded.append(WDIRSEP); //czSectionExpanded.append(EIDMW_CNF_MACRO_COMMON_SUBDIR); //add part after the $-macro czSectionExpanded.append(czSectionOriginal.substr(iStrLenght, iTotLenght-iStrLenght));//add part after the $-macro return(czSectionExpanded); } //--- check for EIDMW_CNF_MACRO_COMMON iStrLenght = wcslen(EIDMW_CNF_MACRO_COMMON); iResult = czSectionOriginal.compare(0, iStrLenght, EIDMW_CNF_MACRO_COMMON); if (iResult == 0) { //replace EIDMW_CNF_MACRO_COMMON //hResult = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_DEFAULT, wsSectionCustom); //if(hResult != S_OK) //{ // //can not replace, return original string // return(czSectionOriginal); //} //std::wstring czSectionExpanded(wsSectionCustom); ////////////////////////////////////////////////////// //Problem of access right for the user with limited right hResult = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_DEFAULT, wsSectionCustom); //non-user SW(eg.: services) returns: C:\WINDOWS\system32\config\systemprofile\Application Data, replace by common dir if((hResult != S_OK) || ((hResult == S_OK) && (wcsstr(wsSectionCustom, L":\\WINDOWS") != NULL))) { //try common path when problems or when no user found hResult = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_DEFAULT, wsSectionCustom); if(hResult != S_OK) { //can not replace, return original string return(czSectionOriginal); } } std::wstring czSectionExpanded(wsSectionCustom); ////////////////////////////////////////////////////// czSectionExpanded.append(WDIRSEP); czSectionExpanded.append(EIDMW_CNF_MACRO_COMMON_SUBDIR); //add part after the $-macro czSectionExpanded.append(czSectionOriginal.substr(iStrLenght, iTotLenght-iStrLenght));//add part after the $-macro return(czSectionExpanded); } return(czSectionOriginal); }