void CSynBCGPEditCtrl::InsertComment(BOOL bForward) { int iStartSel = min (m_iStartSel, m_iEndSel); int iEndSel = max (m_iStartSel, m_iEndSel); int nFirstSelRow, nLastSelRow; if (iStartSel == -1 || iEndSel == -1) { nFirstSelRow = GetCurrRowStart(FALSE); nLastSelRow = GetCurrRowEnd(FALSE); } else { int nEndRowOffset = GetRowStartByOffset (iEndSel, TRUE); if (nEndRowOffset == iEndSel) { iEndSel--; } nFirstSelRow = GetRowStartByOffset (iStartSel, TRUE); nLastSelRow = max (iEndSel, GetRowEndByOffset (iEndSel, TRUE)); } SetSel2(nFirstSelRow, nLastSelRow + 1, TRUE, FALSE); CString strSelText(GetSelText()); if (strSelText.IsEmpty()) { return; } CString strComment; BOOL bCaseSensitive; m_SynLanguage.GetLineComment(strComment, bCaseSensitive); int nPosPrior = 0; int nPos = strComment.Find(_T(","), nPosPrior); if(nPos != -1) { strComment = strComment.Mid(nPosPrior, nPos - nPosPrior); } if (strComment.IsEmpty()) { return; } if (bForward) { int nCommentLen = strComment.GetLength(); nPos = nCommentLen; strSelText.Insert(0, strComment); nPos = strSelText.Find(g_chEOL, nPos); while (nPos != -1) { if (nPos == strSelText.GetLength() - 1) { break; } strSelText.Insert(nPos + 1, strComment); nPos = strSelText.Find(g_chEOL, nPos + nCommentLen + 1); } SetLastUndoReason(g_dwUATComment); ReplaceSel(strSelText, TRUE); } else { int nCommentLen = strComment.GetLength(); BOOL bModify = FALSE; CString strMid, strLeft; int nPosComment; nPos = 0, nPosPrior = 0; nPos = strSelText.Find(g_chEOL, nPosPrior); // 当是最后一行时,也要处理 if (-1 == nPos) { nPos = strSelText.GetLength(); } while (nPos != -1) { strMid = strSelText.Mid(nPosPrior, nPos - nPosPrior); strLeft = strMid.TrimLeft(); strLeft = strLeft.Left(nCommentLen); if (strLeft.Compare(strComment) == 0) { nPosComment = strSelText.Find(strComment, nPosPrior); if (nPosComment != -1) { strSelText.Delete(nPosComment, nCommentLen); nPos -= nCommentLen; bModify = TRUE; } } nPosPrior = nPos + 1; nPos = strSelText.Find(g_chEOL, nPosPrior); if (-1 == nPos) { if (nPosPrior < strSelText.GetLength()) { nPos = strSelText.GetLength(); } } } if (bModify) { SetLastUndoReason(g_dwUATUncomment); ReplaceSel(strSelText, TRUE); } } }
BOOL CPatch::ParserGitPatch(CFileTextLines &PatchLines,int nIndex) { CString sLine; EOL ending = EOL_NOENDING; int state = 0; Chunks * chunks = NULL; Chunk * chunk = NULL; int nAddLineCount = 0; int nRemoveLineCount = 0; int nContextLineCount = 0; for ( ;nIndex<PatchLines.GetCount(); nIndex++) { sLine = PatchLines.GetAt(nIndex); ending = PatchLines.GetLineEnding(nIndex); if (ending != EOL_NOENDING) ending = EOL_AUTOLINE; switch (state) { case 0: { // diff --git if( sLine.Find(_T("diff --git"))==0) { if (chunks) { //this is a new file diff, so add the last one to //our array. m_arFileDiffs.Add(chunks); } chunks = new Chunks(); } //index if( sLine.Find(_T("index"))==0 ) { int dotstart=sLine.Find(_T("..")); if(dotstart>=0) { chunks->sRevision = sLine.Mid(dotstart-7,7); chunks->sRevision2 = sLine.Mid(dotstart+2,7); } } //--- if( sLine.Find(_T("--- "))==0 ) { if (sLine.Left(3).Compare(_T("---"))!=0) { //no starting "---" found //seems to be either garbage or just //a binary file. So start over... state = 0; nIndex--; if (chunks) { delete chunks; chunks = NULL; } break; } sLine = sLine.Mid(3); //remove the "---" sLine =sLine.Trim(); //at the end of the filepath there's a revision number... int bracket = sLine.ReverseFind('('); if (bracket < 0) // some patch files can have another '(' char, especially ones created in Chinese OS bracket = sLine.ReverseFind(0xff08); if (bracket < 0) { if (chunks->sFilePath.IsEmpty()) chunks->sFilePath = sLine.Trim(); } else chunks->sFilePath = sLine.Left(bracket-1).Trim(); if (chunks->sFilePath.Find('\t')>=0) { chunks->sFilePath = chunks->sFilePath.Left(chunks->sFilePath.Find('\t')); } if (chunks->sFilePath.Find(_T('"')) == 0 && chunks->sFilePath.ReverseFind(_T('"')) == chunks->sFilePath.GetLength() - 1) chunks->sFilePath=chunks->sFilePath.Mid(1, chunks->sFilePath.GetLength() - 2); if( chunks->sFilePath.Find(_T("a/")) == 0 ) chunks->sFilePath=chunks->sFilePath.Mid(2); if( chunks->sFilePath.Find(_T("b/")) == 0 ) chunks->sFilePath=chunks->sFilePath.Mid(2); chunks->sFilePath.Replace(_T('/'),_T('\\')); if (chunks->sFilePath == _T("\\dev\\null") || chunks->sFilePath == _T("/dev/null")) chunks->sFilePath = _T("NUL"); } // +++ if( sLine.Find(_T("+++ ")) == 0 ) { sLine = sLine.Mid(3); //remove the "---" sLine =sLine.Trim(); //at the end of the filepath there's a revision number... int bracket = sLine.ReverseFind('('); if (bracket < 0) // some patch files can have another '(' char, especially ones created in Chinese OS bracket = sLine.ReverseFind(0xff08); if (bracket < 0) chunks->sFilePath2 = sLine.Trim(); else chunks->sFilePath2 = sLine.Left(bracket-1).Trim(); if (chunks->sFilePath2.Find('\t')>=0) { chunks->sFilePath2 = chunks->sFilePath2.Left(chunks->sFilePath2.Find('\t')); } if (chunks->sFilePath2.Find(_T('"')) == 0 && chunks->sFilePath2.ReverseFind(_T('"')) == chunks->sFilePath2.GetLength() - 1) chunks->sFilePath2=chunks->sFilePath2.Mid(1, chunks->sFilePath2.GetLength() - 2); if( chunks->sFilePath2.Find(_T("a/")) == 0 ) chunks->sFilePath2=chunks->sFilePath2.Mid(2); if( chunks->sFilePath2.Find(_T("b/")) == 0 ) chunks->sFilePath2=chunks->sFilePath2.Mid(2); chunks->sFilePath2.Replace(_T('/'),_T('\\')); if (chunks->sFilePath2 == _T("\\dev\\null") || chunks->sFilePath2 == _T("/dev/null")) chunks->sFilePath2 = _T("NUL"); } //@@ -xxx,xxx +xxx,xxx @@ if( sLine.Find(_T("@@")) == 0 ) { sLine = sLine.Mid(2); sLine = sLine.Trim(); chunk = new Chunk(); CString sRemove = sLine.Left(sLine.Find(' ')); CString sAdd = sLine.Mid(sLine.Find(' ')); chunk->lRemoveStart = (-_ttol(sRemove)); if (sRemove.Find(',')>=0) { sRemove = sRemove.Mid(sRemove.Find(',')+1); chunk->lRemoveLength = _ttol(sRemove); } else { chunk->lRemoveStart = 0; chunk->lRemoveLength = (-_ttol(sRemove)); } chunk->lAddStart = _ttol(sAdd); if (sAdd.Find(',')>=0) { sAdd = sAdd.Mid(sAdd.Find(',')+1); chunk->lAddLength = _ttol(sAdd); } else { chunk->lAddStart = 1; chunk->lAddLength = _ttol(sAdd); } state =5; } } break; case 5: //[ |+|-] <sourceline> { //this line is either a context line (with a ' ' in front) //a line added (with a '+' in front) //or a removed line (with a '-' in front) TCHAR type; if (sLine.IsEmpty()) type = ' '; else type = sLine.GetAt(0); if (type == ' ') { //it's a context line - we don't use them here right now //but maybe in the future the patch algorithm can be //extended to use those in case the file to patch has //already changed and no base file is around... chunk->arLines.Add(RemoveUnicodeBOM(sLine.Mid(1))); chunk->arLinesStates.Add(PATCHSTATE_CONTEXT); chunk->arEOLs.push_back(ending); nContextLineCount++; } else if (type == '\\') { //it's a context line (sort of): //warnings start with a '\' char (e.g. "\ No newline at end of file") //so just ignore this... } else if (type == '-') { //a removed line chunk->arLines.Add(RemoveUnicodeBOM(sLine.Mid(1))); chunk->arLinesStates.Add(PATCHSTATE_REMOVED); chunk->arEOLs.push_back(ending); nRemoveLineCount++; } else if (type == '+') { //an added line chunk->arLines.Add(RemoveUnicodeBOM(sLine.Mid(1))); chunk->arLinesStates.Add(PATCHSTATE_ADDED); chunk->arEOLs.push_back(ending); nAddLineCount++; } else { //none of those lines! what the hell happened here? m_sErrorMessage.Format(IDS_ERR_PATCH_UNKOWNLINETYPE, nIndex); goto errorcleanup; } if ((chunk->lAddLength == (nAddLineCount + nContextLineCount)) && chunk->lRemoveLength == (nRemoveLineCount + nContextLineCount)) { //chunk is finished if (chunks) chunks->chunks.Add(chunk); else delete chunk; chunk = NULL; nAddLineCount = 0; nContextLineCount = 0; nRemoveLineCount = 0; state = 0; } } break; default: ASSERT(FALSE); } // switch (state) } // for ( ;nIndex<m_PatchLines.GetCount(); nIndex++) if (chunk) { m_sErrorMessage.LoadString(IDS_ERR_PATCH_CHUNKMISMATCH); goto errorcleanup; } if (chunks) m_arFileDiffs.Add(chunks); return TRUE; errorcleanup: if (chunk) delete chunk; if (chunks) { for (int i=0; i<chunks->chunks.GetCount(); i++) { delete chunks->chunks.GetAt(i); } chunks->chunks.RemoveAll(); delete chunks; } FreeMemory(); return FALSE; }
void CSettingsGeneralDlg::LoadSettings() { CPBXClientApp* pApp = (CPBXClientApp*)AfxGetApp(); CString value; int iValue; value = pApp->GetProfileString("Settings", "DelayTime", "3"); this->SetDlgItemText(IDC_EDIT_DELAY_TIME, value); iValue = pApp->GetProfileInt("Settings", "AutomaticStart", 1); this->CheckDlgButton(IDC_CHECK_AUTOMATIC_START, (iValue==1)?1:0); iValue = pApp->GetProfileInt("Settings", "AutomaticSignIn", 1); this->CheckDlgButton(IDC_CHECK_AUTOMATIC_CONNECT, (iValue==1)?1:0); iValue = pApp->GetProfileInt("Settings", "ShowSettingsOnStartup", 0); this->CheckDlgButton(IDC_CHECK_SHOW_AT_STARTUP, (iValue==1)?0:1); iValue = pApp->GetProfileInt("Settings", "IgnoreCalls", 0); m_chkIgnore.SetCheck((iValue==0)?FALSE:1); TCHAR chDigits[50]; for (int i=2; i<26; i++) { _itot(i, chDigits, 10); m_cboDigits.AddString(chDigits); } _itot(iValue, chDigits, 10); if (iValue==0) { m_cboDigits.EnableWindow(0); m_cboDigits.SetCurSel(0); } else { m_cboDigits.EnableWindow(1); m_cboDigits.SelectString(-1, chDigits); } FILE *file = _tfopen(::theApp.GetInstallDir()+"\\languages.txt", _T("r")); if (file) { CString str; int pos; char ch[100]; while (!feof(file)) { str = fgets(ch, 100, file); if (str.GetLength()<4) { continue; } pos = str.Find(_T(" ")); languages[str.Left(pos)] = str.Mid(pos+1, str.GetLength()-pos-3); } fclose(file); } WIN32_FIND_DATA FileData; HANDLE hFind; map<CString, CString>::iterator iter; CString CurrLanguage = pApp->GetProfileString("Settings", "Language", ""); m_cboLanguage.AddString(CString("(") + _("Default language") + CString(")")); hFind = FindFirstFile(::theApp.GetInstallDir() + "\\lang\\*.*", &FileData); if (hFind != INVALID_HANDLE_VALUE) { while (true) { if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (_tcscmp(FileData.cFileName, _T(".")) && _tcscmp(FileData.cFileName, _T(".."))) { iter = languages.find(FileData.cFileName); if (iter!=languages.end()) m_cboLanguage.AddString(iter->second); else m_cboLanguage.AddString(FileData.cFileName); } } if (!FindNextFile(hFind, &FileData)) break; } FindClose(hFind); } if (CurrLanguage=="") { m_cboLanguage.SetCurSel(0); } else { iter = languages.find(CurrLanguage); if (iter!=languages.end()) { m_cboLanguage.SelectString(-1, iter->second); } else { if (m_cboLanguage.SelectString(-1, CurrLanguage)==CB_ERR) { m_cboLanguage.SetCurSel(0); } } } }
int ParserFromRefLog(CString ref, std::vector<GitRev> &refloglist) { refloglist.clear(); if (g_Git.m_IsUseLibGit2) { CAutoRepository repo(g_Git.GetGitRepository()); if (!repo) { MessageBox(nullptr, CGit::GetLibGit2LastErr(_T("Could not open repository.")), _T("TortoiseGit"), MB_ICONERROR); return -1; } CAutoReflog reflog; if (git_reflog_read(reflog.GetPointer(), repo, CUnicodeUtils::GetUTF8(ref)) < 0) { MessageBox(nullptr, CGit::GetLibGit2LastErr(_T("Could not read reflog.")), _T("TortoiseGit"), MB_ICONERROR); return -1; } for (size_t i = 0; i < git_reflog_entrycount(reflog); ++i) { const git_reflog_entry *entry = git_reflog_entry_byindex(reflog, i); if (!entry) continue; GitRev rev; rev.m_CommitHash = (char *)git_reflog_entry_id_new(entry)->id; rev.m_Ref.Format(_T("%s@{%d}"), ref, i); rev.GetCommitterDate() = CTime(git_reflog_entry_committer(entry)->when.time); if (git_reflog_entry_message(entry) != nullptr) { CString one; g_Git.StringAppend(&one, (BYTE *)git_reflog_entry_message(entry)); int message = one.Find(_T(":"), 0); if (message > 0) { rev.m_RefAction = one.Left(message); rev.GetSubject() = one.Mid(message + 1); } } refloglist.push_back(rev); } } else if (g_Git.m_IsUseGitDLL) { git_for_each_reflog_ent(CUnicodeUtils::GetUTF8(ref), AddToRefLoglist, &refloglist); for (size_t i = 0; i < refloglist.size(); ++i) refloglist[i].m_Ref.Format(_T("%s@{%d}"), ref, i); } else { CString cmd, out; GitRev rev; cmd.Format(_T("git.exe reflog show --pretty=\"%%H %%gD: %%gs\" --date=raw %s"), ref); if (g_Git.Run(cmd, &out, NULL, CP_UTF8)) return -1; int i = 0; CString prefix = ref + _T("@{"); int pos = 0; while (pos >= 0) { CString one = out.Tokenize(_T("\n"), pos); int refPos = one.Find(_T(' '), 0); if (refPos < 0) continue; rev.Clear(); CString hashStr = one.Left(refPos); rev.m_CommitHash = hashStr; rev.m_Ref.Format(_T("%s@{%d}"), ref, i++); int prefixPos = one.Find(prefix, refPos + 1); if (prefixPos != refPos + 1) continue; int spacePos = one.Find(_T(' '), prefixPos + prefix.GetLength() + 1); if (spacePos < 0) continue; CString timeStr = one.Mid(prefixPos + prefix.GetLength(), spacePos - prefixPos - prefix.GetLength()); rev.GetCommitterDate() = CTime(_ttoi(timeStr)); int action = one.Find(_T("}: "), spacePos + 1); if (action > 0) { action += 2; int message = one.Find(_T(":"), action); if (message > 0) { rev.m_RefAction = one.Mid(action + 1, message - action - 1); rev.GetSubject() = one.Right(one.GetLength() - message - 1); } } refloglist.push_back(rev); } } return 0; }
TLSecurity TLSecurity::Deserialize(CString msg) { std::vector<CString> rec; CString del(" "); bool hasdel = msg.FindOneOf(del) != -1; if (hasdel) gsplit(msg,del,rec); else rec.push_back(msg); TLSecurity sec; // symbol is a requirement for every type sec.sym = rec[SecSym]; // check for option //bool isopt = (msg.Find(CString("PUT"))!=-1) || (msg.Find(CString("CALL"))!=-1); if (rec.size()>1 && _tstoi(rec[1])!=0) { // sym, date, details, price, ex sec.date = _tstoi(rec[1]); bool isput = msg.Find(CString("PUT"))!=-1; sec.details = isput ? CString("PUT") : CString("CALL"); sec.strike = _tstof(rec[3]); if (rec.size()>5) { sec.dest = rec[4]; sec.type = SecurityID(rec[5]); } else sec.type = SecurityID(rec[4]); }// see if both type and destination were specified else if (rec.size()>2) { // try to get type from both parameters int f2id = SecurityID(rec[2]); int f1id = SecurityID(rec[1]); // whichever one works, use type for that one and assume destination // is other parameter if (f1id!=-1) { sec.type = f1id; sec.dest = rec[2]; } else if (f2id!=-1) { sec.type = f2id; sec.dest = rec[1]; } } // otherwise if we only ahve one extra parameters else if (rec.size()>1) { // try to get it's type int id = SecurityID(rec[1]); // if it works assume it's type if (id!=-1) sec.type = id; else // otherwise it's exchange sec.dest = rec[1]; } return sec; }
void CFunctionView::vSetFunctionToEdit(const CString& omStrFunction) { m_omStrFnName = omStrFunction; CString omStrFnBody(""); BOOL bGlobalVar = FALSE; m_bIsValidFunction = FALSE; m_sStartPos = NULL; CFunctionEditorDoc* pDoc = NULL; pDoc = (CFunctionEditorDoc*)CView::GetDocument(); if ( pDoc != NULL ) { SBUS_SPECIFIC_INFO sBusSpecInfo; pDoc->bGetBusSpecificInfo(sBusSpecInfo); CString omStrFnHeader, omStrFnFooter; // If it is a global variable block then set the block // with global variable boundary if( omStrFunction == GLOBAL_VARIABLES ) { omStrFnHeader = BUS_VAR_HDR; omStrFnHeader.Replace("PLACE_HODLER_FOR_BUSNAME", sBusSpecInfo.m_omBusName); omStrFnFooter = BUS_VAR_FOOTER; omStrFnFooter.Replace("PLACE_HODLER_FOR_BUSNAME", sBusSpecInfo.m_omBusName); bGlobalVar = TRUE; } else { //Construct the Function Header omStrFnHeader = BUS_FN_HDR; omStrFnHeader.Replace("PLACE_HODLER_FOR_BUSNAME", sBusSpecInfo.m_omBusName); omStrFnHeader.Replace( "PLACE_HODLER_FOR_FUNCTIONNAME", omStrFunction ); //Construct the Function Footer omStrFnFooter = EDITOR_BUS_FN_FOOTER; omStrFnFooter.Replace(_T("PLACE_HODLER_FOR_BUSNAME"), sBusSpecInfo.m_omBusName); omStrFnFooter.Replace( _T("PLACE_HODLER_FOR_FUNCTIONNAME"), omStrFunction ); } POSITION sPos = pDoc->m_omSourceCodeTextList.GetHeadPosition(); int nLineNumber = 0; while ( sPos != NULL ) { //Iterate through the Source Code String-List CString omStrLine = pDoc->m_omSourceCodeTextList.GetNext(sPos); // Increment the line count nLineNumber++; //If the current line matches the Function Header... //(means the starting of the function we are looking for) if ( omStrLine == omStrFnHeader ) { if( bGlobalVar == FALSE) { m_nStartingLine = nLineNumber; //Skip Function name and parameters line omStrLine = pDoc->m_omSourceCodeTextList.GetNext(sPos); if (sPos != NULL) { //Get Next line omStrLine = pDoc->m_omSourceCodeTextList.GetNext(sPos); if (sPos != NULL) { //Opening brace indicates start of function body if ( omStrLine.Find('{') != -1 ) { //Store the start for later use m_sStartPos = sPos; //Loop through the function body till we encounter //the function footer while ( (sPos != NULL) && ( m_bIsValidFunction != TRUE) ) { omStrLine = pDoc->m_omSourceCodeTextList.GetNext(sPos); if ( omStrLine.Find(omStrFnFooter) >= 0 ) { m_bIsValidFunction = TRUE; } else { omStrFnBody += omStrLine; omStrFnBody += '\n'; } } } } } } else { //Store the start for later use m_sStartPos = sPos; m_nStartingLine = nLineNumber; while ( (sPos != NULL) && ( omStrLine != omStrFnFooter) ) { omStrLine = pDoc->m_omSourceCodeTextList.GetNext(sPos); if ( omStrLine.Find(omStrFnFooter) >= 0 ) { m_bIsValidFunction = TRUE; } else { omStrFnBody += omStrLine; omStrFnBody += '\n'; } } } } } if ( m_bIsValidFunction ) //If a function name is set... { if ( !omStrFnBody.IsEmpty() ) { //We got to remove the last '\n' that got added //when we constructed omStrFnBody from the source lines omStrFnBody.TrimRight(); if ( omStrFnBody.ReverseFind('}') >= 0) { } SetWindowText(omStrFnBody); GetRichEditCtrl().SetReadOnly(FALSE); } } else // Display Global Variable { SetWindowText(omStrFnBody); GetRichEditCtrl().SetReadOnly(TRUE); } } }
BOOL CGpsxConsoleApp::InitInstance() { AfxEnableControlContainer(); openCommandWindow(); TCHAR result[MAX_PATH]; GetModuleFileName(NULL,result,MAX_PATH);//daemon CString strProcess; strProcess.Format(_T("%s"),result); strProcess.MakeLower(); int nRet = strProcess.Find("daemon.exe"); if(__argc==1 && nRet>0 )//带参数 { printf("守护进程\r\nPress 'E' to exit\r\n"); nRet = strProcess.Find("daemon"); strProcess.Delete(nRet,6); HANDLE hProcess=NULL; DWORD dwProcessID=0; while(1){ if((dwProcessID=_IsProcessExist(strProcess))==0){ int nRet = DeleteFile(strProcess); if(nRet || GetLastError()==2){ if(CopyFile(result,strProcess,FALSE)){ PROCESS_INFORMATION pi; _CreateProcess(strProcess,pi,FALSE,""); hProcess = pi.hProcess; dwProcessID = pi.dwProcessId; }else{ } }else{ // printf("deletefile %d,%d\r\n",nRet,GetLastError()); } //printf("pi-->%d-->%d\r\n",hProcess,pi.dwProcessId); }else{ //printf("IS-->%d\r\n",hProcess); } //Sleep(30*1000); if(getch2(3*1000) == 101){ _KillProcess(dwProcessID); int i=0; do{ Sleep(i*100); BOOL bRet = DeleteFile(strProcess); printf("%s---%d\r\n",strProcess,bRet); }while(i++<4); return 1; } } } CString strLogServer("sonaps.logger.service.exe"); //* HANDLE hProcess=NULL; DWORD dwProcessID = 0; if(!_IsProcessExist(strLogServer,FALSE)){ PROCESS_INFORMATION pi; _CreateProcess(strLogServer,pi,FALSE,""); }/**/ // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. int nListenPort=GetPrivateProfileInt(_T("GPSSet"),_T("listenPort"),110,GetMgConfigFileName()); CString strTmp; strTmp.Format(_T("GPSXCONSOLE_H__BA472566_78AA_%d"),nListenPort); if(OpenMutex(MUTEX_ALL_ACCESS,FALSE,strTmp)) { return FALSE; } else { CreateMutex(NULL,FALSE,strTmp); } // IDumper *pDumper = CreateDumper(); // if(pDumper) // pDumper->SetExceptionFilter(); //自动抓取错误dump CMiniDumper::SetExceptionFilter(MiniDumpWithFullMemory); #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif CGpsxConsoleDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
bool CHooks::Create() { if (m_pInstance == NULL) m_pInstance = new CHooks(); CRegString reghooks = CRegString(L"Software\\TortoiseSVN\\hooks"); CString strhooks = reghooks; // now fill the map with all the hooks defined in the string // the string consists of multiple lines, where one hook script is defined // as six lines: // line 1: the hook type // line 2: path to working copy where to apply the hook script // line 3: command line to execute // line 4: 'true' or 'false' for waiting for the script to finish // line 5: 'show' or 'hide' on how to start the hook script // line 6: 'enforce' on whether to ask the user for permission (optional) hookkey key; int pos = 0; hookcmd cmd; while ((pos = strhooks.Find('\n')) >= 0) { // line 1 key.htype = GetHookType(strhooks.Mid(0, pos)); if (pos+1 < strhooks.GetLength()) strhooks = strhooks.Mid(pos+1); else strhooks.Empty(); bool bComplete = false; if ((pos = strhooks.Find('\n')) >= 0) { // line 2 key.path = CTSVNPath(strhooks.Mid(0, pos)); if (pos+1 < strhooks.GetLength()) strhooks = strhooks.Mid(pos+1); else strhooks.Empty(); if ((pos = strhooks.Find('\n')) >= 0) { // line 3 cmd.commandline = strhooks.Mid(0, pos); if (pos+1 < strhooks.GetLength()) strhooks = strhooks.Mid(pos+1); else strhooks.Empty(); if ((pos = strhooks.Find('\n')) >= 0) { // line 4 cmd.bWait = (strhooks.Mid(0, pos).CompareNoCase(L"true")==0); if (pos+1 < strhooks.GetLength()) strhooks = strhooks.Mid(pos+1); else strhooks.Empty(); if ((pos = strhooks.Find('\n')) >= 0) { // line 5 cmd.bShow = (strhooks.Mid(0, pos).CompareNoCase(L"show")==0); if (pos+1 < strhooks.GetLength()) strhooks = strhooks.Mid(pos+1); else strhooks.Empty(); cmd.bEnforce = false; if ((pos = strhooks.Find('\n')) >= 0) { // line 6 (optional) if (GetHookType(strhooks.Mid(0, pos)) == unknown_hook) { cmd.bEnforce = (strhooks.Mid(0, pos).CompareNoCase(L"enforce")==0); if (pos+1 < strhooks.GetLength()) strhooks = strhooks.Mid(pos+1); else strhooks.Empty(); } } cmd.bApproved = true; // user configured scripts are pre-approved bComplete = true; } } } } if (bComplete) { m_pInstance->insert(std::pair<hookkey, hookcmd>(key, cmd)); } } return true; }
bool CHooks::ParseAndInsertProjectProperty( hooktype t, const CString& strhook, const CTSVNPath& wcRootPath, const CString& rootPath, const CString& rootUrl, const CString& repoRootUrl ) { if (strhook.IsEmpty()) return false; // the string consists of multiple lines, where one hook script is defined // as four lines: // line 1: command line to execute // line 2: 'true' or 'false' for waiting for the script to finish // line 3: 'show' or 'hide' on how to start the hook script // line 4: 'force' on whether to ask the user for permission hookkey key; hookcmd cmd; key.htype = t; key.path = wcRootPath; int pos = 0; CString temp; temp = strhook.Tokenize(L"\n", pos); if (!temp.IsEmpty()) { ASSERT(t == GetHookType(temp)); temp = strhook.Tokenize(L"\n", pos); if (!temp.IsEmpty()) { int urlstart = temp.Find(L"%REPOROOT%"); if (urlstart >= 0) { temp.Replace(L"%REPOROOT%", repoRootUrl); CString fullUrl = temp.Mid(urlstart); int urlend = -1; if ((urlstart > 0)&&(temp[urlstart-1]=='\"')) urlend = temp.Find('\"', urlstart); else urlend = temp.Find(' ', urlstart); if (urlend < 0) urlend = temp.GetLength(); fullUrl = temp.Mid(urlstart, urlend-urlstart); fullUrl.Replace('\\', '/'); // now we have the full url of the script, e.g. // https://svn.osdn.net/svnroot/tortoisesvn/trunk/contrib/hook-scripts/client-side/checkyear.js CString sLocalPathUrl = rootUrl; CString sLocalPath = rootPath; // find the lowest common ancestor of the local path url and the script url while (fullUrl.Left(sLocalPathUrl.GetLength()).Compare(sLocalPathUrl)) { int sp = sLocalPathUrl.ReverseFind('/'); if (sp < 0) return false; sLocalPathUrl = sLocalPathUrl.Left(sp); sp = sLocalPath.ReverseFind('\\'); if (sp < 0) return false; sLocalPath = sLocalPath.Left(sp); } // now both sLocalPathUrl and sLocalPath can be used to construct // the path to the script CString partUrl = fullUrl.Mid(sLocalPathUrl.GetLength()); if (partUrl.Find('/') == 0) partUrl = partUrl.Mid(1); if (sLocalPath.ReverseFind('\\') == sLocalPath.GetLength() - 1 || sLocalPath.ReverseFind('/') == sLocalPath.GetLength() - 1) sLocalPath = sLocalPath.Left(sLocalPath.GetLength() - 1); sLocalPath = sLocalPath + L"\\" + partUrl; sLocalPath.Replace('/', '\\'); // now replace the full url in the command line with the local path temp.Replace(fullUrl, sLocalPath); } urlstart = temp.Find(L"%REPOROOT+%"); if (urlstart >= 0) { CString temp2 = temp; CString sExt = rootUrl.Mid(repoRootUrl.GetLength()); CString sLocalPath; do { temp = temp2; CString repoRootUrlExt = repoRootUrl + sExt; int slp = sExt.ReverseFind('/'); if (slp >= 0) sExt = sExt.Left(sExt.ReverseFind('/')); else if (sExt.IsEmpty()) return false; else sExt.Empty(); temp.Replace(L"%REPOROOT+%", repoRootUrlExt); CString fullUrl = temp.Mid(urlstart); int urlend = -1; if ((urlstart > 0)&&(temp[urlstart-1]=='\"')) urlend = temp.Find('\"', urlstart); else urlend = temp.Find(' ', urlstart); if (urlend < 0) urlend = temp.GetLength(); fullUrl = temp.Mid(urlstart, urlend-urlstart); fullUrl.Replace('\\', '/'); // now we have the full url of the script, e.g. // https://svn.osdn.net/svnroot/tortoisesvn/trunk/contrib/hook-scripts/client-side/checkyear.js CString sLocalPathUrl = rootUrl; sLocalPath = rootPath; // find the lowest common ancestor of the local path url and the script url while (fullUrl.Left(sLocalPathUrl.GetLength()).Compare(sLocalPathUrl)) { int sp = sLocalPathUrl.ReverseFind('/'); if (sp < 0) return false; sLocalPathUrl = sLocalPathUrl.Left(sp); sp = sLocalPath.ReverseFind('\\'); if (sp < 0) return false; sLocalPath = sLocalPath.Left(sp); } // now both sLocalPathUrl and sLocalPath can be used to construct // the path to the script CString partUrl = fullUrl.Mid(sLocalPathUrl.GetLength()); if (partUrl.Find('/') == 0) partUrl = partUrl.Mid(1); if (sLocalPath.ReverseFind('\\') == sLocalPath.GetLength() - 1 || sLocalPath.ReverseFind('/') == sLocalPath.GetLength() - 1) sLocalPath = sLocalPath.Left(sLocalPath.GetLength() - 1); sLocalPath = sLocalPath + L"\\" + partUrl; sLocalPath.Replace('/', '\\'); // now replace the full url in the command line with the local path temp.Replace(fullUrl, sLocalPath); } while (!PathFileExists(sLocalPath)); } cmd.commandline = temp; temp = strhook.Tokenize(L"\n", pos); if (!temp.IsEmpty()) { cmd.bWait = (temp.CompareNoCase(L"true")==0); temp = strhook.Tokenize(L"\n", pos); if (!temp.IsEmpty()) { cmd.bShow = (temp.CompareNoCase(L"show")==0); temp.Format(L"%d%s", (int)key.htype, (LPCTSTR)cmd.commandline); SVNPool pool; cmd.sRegKey = L"Software\\TortoiseSVN\\approvedhooks\\" + SVN::GetChecksumString(svn_checksum_sha1, temp, pool); CRegDWORD reg(cmd.sRegKey, 0); cmd.bApproved = (DWORD(reg) != 0); cmd.bStored = reg.exists(); temp = strhook.Tokenize(L"\n", pos); cmd.bEnforce = temp.CompareNoCase(L"enforce")==0; if (find(key) == end()) { m_pInstance->insert(std::pair<hookkey, hookcmd>(key, cmd)); return true; } } } } } return false; }
/* this is the main converter for external viewers. * it returns the stream object as well * as a data object that it can reference * internally to save the state of the document */ NET_StreamClass *external_viewer_disk_stream(int iFormatOut, void *pDataObj, URL_Struct *pUrl, MWContext *pContext) { ASSERT(pUrl); ASSERT(pUrl->address); // Lookup the helper app, if one exists. // If not found, create one on the fly. CNetscapeApp *pNetscape = (CNetscapeApp *)AfxGetApp(); CHelperApp *pHelper; XP_Bool isNewHelper = FALSE; if(0 == pNetscape->m_HelperListByType.Lookup(pUrl->content_type, (CObject *&)pHelper)) { // couldn't find one. // create the new mime type. CString csText = pUrl->content_type; // If there's no slash, just send the type as the file type // (this usually only happens on server error, but we // should still behave ourselves). int iSlash = csText.Find('/'); if(iSlash != -1) { // this mess splits the string into the stuff before the slash and // the stuff after the slash pHelper = fe_AddNewFileFormatType(csText.Left(iSlash), csText.Right(csText.GetLength() - iSlash - 1)); isNewHelper = TRUE; } else { pHelper = fe_AddNewFileFormatType(csText, ""); isNewHelper = TRUE; } } // The helper app is now defined for the mime type in any case. // See how it is to be handled. BOOL bExternal = FALSE; BOOL bSave = FALSE; BOOL bMoreInfo = FALSE; switch(pHelper->how_handle) { case HANDLE_UNKNOWN: { // See what this is supposed to do via user input. CUnknownTypeDlg dlgUnknown(GetFrame(pContext)->GetFrameWnd(), pUrl->content_type, pHelper); int iDlg = dlgUnknown.DoModal(); if(iDlg == IDCANCEL) { // User hit cancel. Abort the load. if (pHelper && pHelper->cd_item && isNewHelper) { if (XP_ListRemoveObject(cinfo_MasterListPointer(), pHelper->cd_item)) { if (pHelper->cd_item) { if (pHelper->cd_item->ci.type) { theApp.m_HelperListByType.RemoveKey(pHelper->cd_item->ci.type); XP_FREE( pHelper->cd_item->ci.type ); } XP_FREE (pHelper->cd_item); } delete pHelper; } } return(NULL); } else if(iDlg == HANDLE_EXTERNAL) { char buf[256]; bExternal = TRUE; // We need to indicate that this is a user-defined MIME type. If we // don't, then we won't remember it the next time the Navigator is run sprintf(buf,"TYPE%d",theApp.m_iNumTypesInINIFile); theApp.m_iNumTypesInINIFile++; theApp.WriteProfileString("Viewers", buf, pUrl->content_type); pHelper->bNewType = FALSE; } else if(iDlg == HANDLE_SAVE) { bSave = TRUE; } else if(iDlg == HANDLE_MOREINFO) { bMoreInfo = TRUE; } break; } case HANDLE_EXTERNAL: case HANDLE_BY_OLE: { bExternal = TRUE; break; } case HANDLE_SHELLEXECUTE: { bExternal = TRUE; break; } case HANDLE_SAVE: { bSave = TRUE; break; } default: { // Shouldn't ever be other than the above types at this // point! ASSERT(0); return(NULL); } } // We know that we are either saving or spawning an external // viewer at this point. NET_StreamClass *pRetval = NULL; if (bSave == TRUE) { return ExternalFileSave(iFormatOut, pUrl, pContext); } else if (bExternal == TRUE) { // Prompt the user for a file name. // Security rist to let path information in externally provided // filename (content disposition, filename =) // XXX This code could be cleaned up -- eliminate aFileName // and just use what was allocated by WH_TempFileName. char aFileName[_MAX_PATH]; char *pSuggestedName = NULL; BOOL bUseContentName = FALSE; if (pUrl->content_name != NULL && strstr(pUrl->content_name, "../") == NULL && strstr(pUrl->content_name, "..\\") == NULL) { bUseContentName = TRUE; } else { pSuggestedName = fe_URLtoLocalName(pUrl->address, pUrl->content_type); } char *pDestination; ASSERT(pNetscape->m_pTempDir); if(pNetscape->m_pTempDir != NULL && pSuggestedName != NULL) { sprintf(aFileName, "%s\\%s", pNetscape->m_pTempDir, pSuggestedName); XP_FREE(pSuggestedName); pSuggestedName = NULL; pDestination = aFileName; } else { char aExt[_MAX_EXT]; size_t stExt = 0; DWORD dwFlags = 0; const char *pName = pUrl->address; if(bUseContentName) { pName = pUrl->content_name; } #ifdef XP_WIN16 dwFlags |= EXT_DOT_THREE; #endif aExt[0] = '\0'; stExt = EXT_Invent(aExt, sizeof(aExt), dwFlags, pName, pUrl->content_type); char *pTemp = WH_TempFileName(xpTemporary, "M", aExt); if(pTemp) { strcpy(aFileName, pTemp); XP_FREE(pTemp); pTemp = NULL; } else { aFileName[0] = '\0'; } } pDestination = aFileName; // Figure out the application that we'll be spawning. // Strip off odd things at the right hand side. CString csCommand; if(pHelper->how_handle == HANDLE_EXTERNAL) { csCommand = pHelper->csCmd; int iStrip = csCommand.ReverseFind('%'); if(iStrip > 0) { csCommand = csCommand.Left(iStrip - 1); } } // See if it's actually OK to spawn this application. CString csSpawn = csCommand; BOOL bShellExecute = FALSE; if(pHelper->how_handle == HANDLE_SHELLEXECUTE || pHelper->how_handle == HANDLE_BY_OLE) { // Shell execute type, figure out the exe. char aExe[_MAX_PATH]; memset(aExe, 0, sizeof(aExe)); if(FEU_FindExecutable(pDestination, aExe, FALSE)) { csSpawn = aExe; if(pHelper->how_handle == HANDLE_SHELLEXECUTE) { bShellExecute = TRUE; } } else { csSpawn.Empty(); } } // See whether the user wants to be prompted before we open the file if (pContext->type != MWContextPrint && theApp.m_pSpawn->PromptBeforeOpening((LPCSTR)csSpawn)) { BOOL bFree = FALSE; LPCSTR lpszFilename = NULL; if (pUrl->content_name != NULL && strstr(pUrl->content_name, "../") == NULL && strstr(pUrl->content_name, "..\\") == NULL) { lpszFilename = pUrl->content_name; } if (!lpszFilename) { lpszFilename = fe_URLtoLocalName(pUrl->address, pUrl->content_type); bFree = TRUE; } char* docExt[1]; const char * ptr1 = lpszFilename; int type = NET_URL_Type(pUrl->address); BOOL canHandleOLE = FALSE; if ((type != MAILBOX_TYPE_URL) && (type !=NEWS_TYPE_URL) && (type != IMAP_TYPE_URL) ) { docExt[0] = FE_FindFileExt((char*)ptr1); if (docExt[0]) canHandleOLE = fe_CanHandleByOLE(docExt, 1); } CLaunchHelper dlg(lpszFilename, (LPCSTR)csSpawn, canHandleOLE, GetFrame(pContext)->GetFrameWnd()); if (bFree) XP_FREE((LPVOID)lpszFilename); // Initialize the dialog to some defaults. dlg.m_bAlwaysAsk = TRUE; //dlg.m_nAction = HELPER_SAVE_TO_DISK; //Old statement CRN_MIME dlg.m_nAction = (pHelper->how_handle == HANDLE_SHELLEXECUTE) ? HELPER_OPEN_IT : HELPER_SAVE_TO_DISK; //New Statement. Set m_nAction based on pHelper->how_handle... CRN_MIME dlg.m_bHandleByOLE = fe_IsHandleByOLE(pUrl->content_type); // Ask the user if (dlg.DoModal() == IDCANCEL) return NULL; // See if they no longer want to be asked if (!dlg.m_bAlwaysAsk) { if (dlg.m_nAction == HELPER_SAVE_TO_DISK) { // User wants to just save to disk pHelper->how_handle = HANDLE_SAVE; pHelper->csCmd = MIME_SAVE; pHelper->bChanged = TRUE; } else { ASSERT(dlg.m_nAction == HELPER_OPEN_IT); theApp.m_pSpawn->SetPromptBeforeOpening((LPCSTR)csSpawn, FALSE); } } // Check whether the user wants to launch the application or save it // do disk if (dlg.m_nAction == HELPER_SAVE_TO_DISK) return ExternalFileSave(iFormatOut, pUrl, pContext); else { // open it case. // user want to handle this by OLE. if (dlg.m_bHandleByOLE) { fe_SetHandleByOLE(pUrl->content_type, pHelper, TRUE); } // Since mail and new will not be able launch using OLE inplace server, so we should not try to change helper app // how_handle here. else if (pHelper->how_handle == HANDLE_BY_OLE) { fe_SetHandleByOLE(pUrl->content_type, pHelper, FALSE); } } } // MWH -- see could we handle this via OLE. if ((iFormatOut == FO_PRESENT || iFormatOut == FO_PRINT) && (pHelper->how_handle == HANDLE_BY_OLE) && FE_FileType(pUrl->address, pUrl->content_type, pUrl->content_encoding)) { // can be handle by OLE. return OLE_ViewStream(iFormatOut, pDataObj, pUrl,pContext); } // It's OK to spawn this application. // Attempt to split it off into a seperate context. if(bShellExecute) { pRetval = CSaveCX::ViewUrlObject(pUrl, NULL); } else { pRetval = CSaveCX::ViewUrlObject(pUrl, csSpawn); } if(pRetval != NULL) { return(pRetval); } // Couldn't split off into a new context. // Handle as was handled before. // We have a destination file name. FILE *pSink = XP_FileOpen(pDestination, xpTemporary, "wb"); if(pSink == NULL) { FE_Alert(pContext, szLoadString(IDS_FAILED_CREATE_TEMP_FILE)); XP_FREE(pDestination); return(NULL); } // Create the data object that will be passed along down // the stream. DataObject *pMe = new DataObject; if(!pMe) return(NULL); memset(pMe, 0, sizeof(DataObject)); pMe->how_handle = pHelper->how_handle; pMe->fp = pSink; pMe->context = pContext; pMe->format_out = iFormatOut; pMe->filename = pDestination; pMe->content_length = pUrl->content_length < 0 ? 0 : pUrl->content_length; pMe->cur_loc = 0; StrAllocCopy(pMe->address, pUrl->address); StrAllocCopy(pMe->format_in, pUrl->content_type); // The spawn command. if(pMe->how_handle == HANDLE_EXTERNAL) { pMe->params = XP_STRDUP(pDestination); } else if(pMe->how_handle == HANDLE_SHELLEXECUTE) { csCommand += pDestination; } else if(pMe->how_handle == HANDLE_BY_OLE) { csCommand += pDestination; } pMe->command = XP_STRDUP(csCommand); // Progress. FE_SetProgressBarPercent(pContext, 0); // Delete the file on exit. FE_DeleteFileOnExit(pDestination, pUrl->address); // Set the waiting mode??? FE_EnableClicking(pContext); // Create the stream. pRetval = NET_NewStream("ServeAndView", disk_stream_write, disk_stream_complete, disk_stream_abort, write_ready, pMe, pContext); } if(bMoreInfo == TRUE) { char * url = NULL; PREF_CopyConfigString("internal_url.more_info_plugin.url",&url); if (url) { CString csUrlAddress = url; csUrlAddress += "?"; csUrlAddress += pUrl->content_type; (ABSTRACTCX(pContext))->NormalGetUrl(csUrlAddress, pUrl->address, csUrlAddress); XP_FREE(url); } } // Return the stream that was created. return(pRetval); }
CString CPop3Message::GetHeaderItem(const CString& sName, int nItem) const { //Value which will be returned by this function CString sField; //Get the message header (add an extra "\r\n" at the //begining to aid in the parsing) CString sHeader(_T("\r\n")); sHeader += GetHeader(); CString sUpCaseHeader(sHeader); sUpCaseHeader.MakeUpper(); CString sUpCaseName(sName); sUpCaseName.MakeUpper(); //Find the specified line in the header CString sFind(CString(_T("\r\n")) + sUpCaseName + _T(":")); int nFindLength = sFind.GetLength(); int nFindStart = sUpCaseHeader.Find(sFind); int nFind = nFindStart; for (int i=0; i<nItem; i++) { //Get ready for the next loop around sUpCaseHeader = sUpCaseHeader.Right(sUpCaseHeader.GetLength() - nFind - nFindLength); nFind = sUpCaseHeader.Find(sFind); if (nFind == -1) return _T(""); //Not found else nFindStart += (nFind + nFindLength); } if (nFindStart != -1) nFindStart += (3 + sName.GetLength()); if (nFindStart != -1) { BOOL bFoundEnd = FALSE; int i = nFindStart; int nLength = sHeader.GetLength(); do { //Examine the current 3 characters TCHAR c1 = _T('\0'); if (i < nLength) c1 = sHeader[i]; TCHAR c2 = _T('\0'); if (i < (nLength-1)) c2 = sHeader[i+1]; TCHAR c3 = _T('\0'); if (i < (nLength-2)) c3 = sHeader[i+2]; //Have we found the terminator if ((c1 == _T('\0')) || ((c1 == _T('\r')) && (c2 == _T('\n')) && (c3 != _T(' ')) && c3 != _T('\t'))) { bFoundEnd = TRUE; } else { //Move onto the next character ++i; } } while (!bFoundEnd); sField = sHeader.Mid(nFindStart, i - nFindStart); //Remove any embedded "\r\n" sequences from the field int nEOL = sField.Find(_T("\r\n")); while (nEOL != -1) { sField = sField.Left(nEOL) + sField.Right(sField.GetLength() - nEOL - 2); nEOL = sField.Find(_T("\r\n")); } //Replace any embedded "\t" sequences with spaces int nTab = sField.Find(_T('\t')); while (nTab != -1) { sField = sField.Left(nTab) + _T(' ') + sField.Right(sField.GetLength() - nTab - 1); nTab = sField.Find(_T('\t')); } //Remove any leading or trailing white space from the Field Body sField.TrimLeft(); sField.TrimRight(); } return sField; }
CString CStringUtils::WordWrap(const CString& longstring, int limit, bool bCompactPaths, bool bForceWrap, int tabSize) { int nLength = longstring.GetLength(); CString retString; if (limit < 0) limit = 0; int nLineStart = 0; int nLineEnd = 0; int tabOffset = 0; for (int i = 0; i < nLength; ++i) { if (i-nLineStart+tabOffset >= limit) { if (nLineEnd == nLineStart) { if (bForceWrap) nLineEnd = i; else { while ((i < nLength) && (longstring[i] != ' ') && (longstring[i] != '\t')) ++i; nLineEnd = i; } } if (bCompactPaths) { CString longline = longstring.Mid(nLineStart, nLineEnd-nLineStart).Left(MAX_PATH-1); if ((bCompactPaths)&&(longline.GetLength() < MAX_PATH)) { if (((!PathIsFileSpec(longline))&&longline.Find(':')<3)||(PathIsURL(longline))) { TCHAR buf[MAX_PATH] = { 0 }; PathCompactPathEx(buf, longline, limit+1, 0); longline = buf; } } retString += longline; } else retString += longstring.Mid(nLineStart, nLineEnd-nLineStart); retString += L"\n"; tabOffset = 0; nLineStart = nLineEnd; } if (longstring[i] == ' ') nLineEnd = i; if (longstring[i] == '\t') { tabOffset += (tabSize - i % tabSize); nLineEnd = i; } } if (bCompactPaths) { CString longline = longstring.Mid(nLineStart).Left(MAX_PATH-1); if ((bCompactPaths)&&(longline.GetLength() < MAX_PATH)) { if (((!PathIsFileSpec(longline))&&longline.Find(':')<3)||(PathIsURL(longline))) { TCHAR buf[MAX_PATH] = { 0 }; PathCompactPathEx(buf, longline, limit+1, 0); longline = buf; } } retString += longline; } else retString += longstring.Mid(nLineStart); return retString; }
LRESULT CAddMemberVarGl::OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { DoDataExchange(TRUE); //получаем тип int StartType = 0; CString Delim = _T(" \t\r\n"); int n1 ,n2; BOOL bConst = FALSE; while(StartType >= 0) { n1 = m_Edit.Mid(StartType).FindOneOf(Delim) + StartType; if (n1 == -1) { MessageBox(_T("Wrong definition")); return 0; } n2 = n1; while((Delim.Find(m_Edit[n2]) != -1) && (n2 < m_Edit.GetLength())) { n2++; } //не совсем правильно, но в больштнстве случаев работает m_Type = m_Edit.Left(n1); m_Type.TrimLeft(); if (m_Type == _T("static")) { m_bStatic = TRUE; StartType = n2; continue; } if (m_Type == _T("virtual")) { m_bVirtual = TRUE; StartType = n2; continue; } if (m_Type == _T("const")) { bConst = TRUE; StartType = n2; continue; } StartType = -1; } if (bConst && m_AddType == ADD_TYPE_FUNCTION) { m_Type = _T("const ") + m_Type; } else { m_bConst |= bConst; } m_Body = m_Edit.Mid(n2); m_Body.TrimRight(); int k1 = m_ClassBox.GetCurSel(); if (k1 != -1) { m_pCurClass = (VSClass*)m_ClassBox.GetItemDataPtr(k1); } else { m_pCurClass = NULL; } EndDialog(IDOK); return 0; }
/* *函数介绍:解析GPS数据 *入口参数:aRecvStr :指待解析的GPS缓冲数据 *出口参数:(无) *返回值:指CGPSData结构体的指针,如果无效即为:NULL; */ PGPSData CGPS::AnalyseGpsData(CString &aRecvStr) { CString tmpTime; CString tmpState; CString tmpDate; CString tmpLONG; CString tmpLONGType; CString tmpLAT; CString tmpLATType; CString tmpSpeed; LPSTR pStrDate = NULL; LPSTR pStrTime = NULL; LPSTR pStrLong = NULL; LPSTR pStrLongType = NULL; LPSTR pStrLat = NULL; LPSTR pStrLatType = NULL; LPSTR pStrSpeed = NULL; PGPSData pGpsData = NULL; int tmpPos,tmpPos1; int len; tmpPos = aRecvStr.Find(',',0); //第1个值 tmpPos1 = aRecvStr.Find(',',tmpPos+1); //得到时间 tmpTime = aRecvStr.Mid(tmpPos+1,tmpPos1-tmpPos-1); tmpTime = tmpTime.Mid(0,2)+L":"+tmpTime.Mid(2,2)+L":"+tmpTime.Mid(4,2); len = tmpTime.GetLength(); pStrTime = LPSTR(LocalAlloc(LMEM_ZEROINIT,len)); WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,tmpTime.GetBuffer(len),len ,pStrTime,len ,NULL,NULL); //数据状态,是否有效 tmpPos = aRecvStr.Find(',',tmpPos+1); //第2个值 tmpPos1 = aRecvStr.Find(',',tmpPos+1); tmpState = aRecvStr.Mid(tmpPos+1,tmpPos1-tmpPos-1); if (tmpState != 'A')//代表数据无效,返回 { if (m_gpsDev_State != GPS_INVALID_DATA) { //设置GPS状态 m_gpsDev_State = GPS_INVALID_DATA; //发送GPS状态变化消息 ::PostMessage(m_pWnd->m_hWnd,WM_GPS_STATE_CHANGE_MESSAGE,WPARAM(GPS_INVALID_DATA),1); } LocalFree(pStrTime); return NULL; } else //代表数据有效 { if (m_gpsDev_State != GPS_VALID_DATA) { //设置GPS状态 m_gpsDev_State = GPS_VALID_DATA; //发送GPS状态变化消息 ::PostMessage(m_pWnd->m_hWnd,WM_GPS_STATE_CHANGE_MESSAGE,WPARAM(GPS_VALID_DATA),1); } } //得到纬度值 tmpPos = aRecvStr.Find(',',tmpPos+1);//第3个值 tmpPos1 = aRecvStr.Find(',',tmpPos+1); tmpLAT = aRecvStr.Mid(tmpPos+1,tmpPos1-tmpPos-1); len = tmpLAT.GetLength(); pStrLat = LPSTR(LocalAlloc(LMEM_ZEROINIT,len)); WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,tmpLAT.GetBuffer(len),len ,pStrLat,len ,NULL,NULL); tmpPos = aRecvStr.Find(',',tmpPos+1);//第4个值 tmpPos1 = aRecvStr.Find(',',tmpPos+1); tmpLATType = aRecvStr.Mid(tmpPos+1,tmpPos1-tmpPos-1); len = tmpLATType.GetLength(); pStrLatType = LPSTR(LocalAlloc(LMEM_ZEROINIT,len)); WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,tmpLATType.GetBuffer(len),len ,pStrLatType,len ,NULL,NULL); //得到经度值 tmpPos = aRecvStr.Find(',',tmpPos+1);//第5个值 tmpPos1 = aRecvStr.Find(',',tmpPos+1); tmpLONG = aRecvStr.Mid(tmpPos+1,tmpPos1-tmpPos-1); len = tmpLONG.GetLength(); pStrLong = LPSTR(LocalAlloc(LMEM_ZEROINIT,len)); WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,tmpLONG.GetBuffer(len),len ,pStrLong,len ,NULL,NULL); tmpPos = aRecvStr.Find(',',tmpPos+1);//第6个值 tmpPos1 = aRecvStr.Find(',',tmpPos+1); tmpLONGType = aRecvStr.Mid(tmpPos+1,tmpPos1-tmpPos-1); len = tmpLONGType.GetLength(); pStrLongType = LPSTR(LocalAlloc(LMEM_ZEROINIT,len)); WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,tmpLONGType.GetBuffer(len),len ,pStrLongType,len ,NULL,NULL); //得到车速 tmpPos = aRecvStr.Find(',',tmpPos+1);////第7个值 tmpPos1 = aRecvStr.Find(',',tmpPos+1); tmpSpeed = aRecvStr.Mid(tmpPos+1,tmpPos1-tmpPos-1); len = tmpSpeed.GetLength(); pStrSpeed = LPSTR(LocalAlloc(LMEM_ZEROINIT,len)); WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,tmpSpeed.GetBuffer(len),len ,pStrSpeed,len ,NULL,NULL); tmpPos = aRecvStr.Find(',',tmpPos+1);////第8个值 //得到日期 tmpPos = aRecvStr.Find(',',tmpPos+1);////第9个值 tmpPos1 = aRecvStr.Find(',',tmpPos+1); //格式化一下 tmpDate = aRecvStr.Mid(tmpPos+1,tmpPos1-tmpPos-1); tmpDate = L"20"+tmpDate.Mid(4,2)+L"-"+tmpDate.Mid(2,2)+L"-"+tmpDate.Mid(0,2); len = tmpDate.GetLength(); pStrDate = LPSTR(LocalAlloc(LMEM_ZEROINIT,len)); WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,tmpDate.GetBuffer(len),len ,pStrDate,len ,NULL,NULL); pGpsData = new GPSData(); ZeroMemory(pGpsData,sizeof(GPSData)); //得到GPS数据指针 CopyMemory(pGpsData->date,pStrDate,10); CopyMemory(pGpsData->time,pStrTime,8); CopyMemory(pGpsData->latitude_type,pStrLatType,1); CopyMemory(pGpsData->latitude,pStrLat,9); CopyMemory(pGpsData->longitude_type,pStrLongType,1); CopyMemory(pGpsData->longitude,pStrLong,10); //先置默认速度0 FillMemory(pGpsData->speed,5,'0'); CopyMemory(pGpsData->speed,pStrSpeed,5); //释放内存 LocalFree(pStrTime); LocalFree(pStrDate); LocalFree(pStrLatType); LocalFree(pStrLat); LocalFree(pStrLongType); LocalFree(pStrLong); LocalFree(pStrSpeed); return pGpsData; }
BOOL bIsModeMismatch( ifstream& omInReplayFile, BOOL bReplayHexON, WORD wLogReplayTimeMode) { BOOL bFlag = FALSE; BOOL bLine = TRUE; CHAR Line[500] = { NULL }; CString omStrLine; BOOL bLogModeChecked = FALSE; BOOL bReplayMsgTypeChecked = FALSE; if(omInReplayFile != NULL) { while( bLine && ! omInReplayFile.eof()) { omInReplayFile.getline( Line, sizeof(Line)); omStrLine = Line; if( omStrLine.Find(HEX_MODE) == 0) { bLogModeChecked = TRUE; if(bReplayHexON != TRUE) { bFlag = TRUE; } } else if (omStrLine.Find(DEC_MODE) == 0) { bLogModeChecked = TRUE; if(bReplayHexON != FALSE) { bFlag = TRUE; } } if( omStrLine.Find(SYSTEM_MODE) == 0) { bReplayMsgTypeChecked = TRUE; if( wLogReplayTimeMode != eSYSTEM_MODE) { bFlag = TRUE; bLine = FALSE; } } else if( omStrLine.Find(ABSOLUTE_MODE) == 0) { bReplayMsgTypeChecked = TRUE; if( wLogReplayTimeMode != eABSOLUTE_MODE) { bFlag = TRUE; bLine = FALSE; } } else if( omStrLine.Find(RELATIVE_MODE) == 0) { bReplayMsgTypeChecked = TRUE; if( wLogReplayTimeMode != eRELATIVE_MODE) { bFlag = TRUE; bLine = FALSE; } } if(bLogModeChecked == TRUE && bReplayMsgTypeChecked == TRUE) { bLine = FALSE; } } } return bFlag; }
void CPage_Node_Movement::SaveData() { bool bTurnVolumeModified = false; UpdateData(1); std::map<int, int> IncomingLinkMap; DTANode* pNode = m_pDoc->m_NodeNoMap [m_CurrentNodeID]; if( pNode->m_CycleLengthInSecond != m_CycleLengthInSec || pNode->m_SignalOffsetInSecond != m_Offset) { m_pDoc->Modify (true); pNode->m_SignalOffsetInSecond = m_Offset; } for (unsigned int i=0;i< pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector .size();i++) { int turning_prohibition_flag= pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].turning_prohibition_flag; int PrevQEM_lanes = pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].QEM_Lanes; int QEM_Phase1 = pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].QEM_Phase1; CString LaneString = m_ListCtrl.GetItemText (i,GetColumnIndex("# of Lanes")); int QEM_lanes= atoi(LaneString); // update # of lanes on link if(PrevQEM_lanes != QEM_lanes) { DTALink* pLink0 = m_pDoc->m_LinkNoMap[pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].IncomingLinkNo ]; switch (pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].movement_turn) { case DTA_Through: pLink0->m_NumberOfLanes = QEM_lanes; break; case DTA_LeftTurn: case DTA_LeftTurn2: pLink0->m_NumberOfLeftTurnLanes = QEM_lanes ; break; case DTA_RightTurn: case DTA_RightTurn2: pLink0->m_NumberOfRightTurnLanes = QEM_lanes ; break; } } int obs_turn_hourly_count = pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].obs_turn_hourly_count ; int obs_turn_delay = pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].obs_turn_delay ; DTA_SIG_MOVEMENT movement_approach_turn = pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].movement_approach_turn ; int effective_green= (int)(pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].QEM_EffectiveGreen); int saturation_flow_rate= (int)(pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].QEM_SatFlow); DTANodeMovement movement = pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i]; int colume_index = 3; CString str; str = m_ListCtrl.GetItemText (i,GetColumnIndex("Direction")); pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].movement_approach_turn = m_pDoc->GetTurnDirectionFromString(str); str = m_ListCtrl.GetItemText (i,GetColumnIndex("Prohibition")); if(str.Find("Prohibited") == -1) // not found pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].turning_prohibition_flag = 0; else pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].turning_prohibition_flag = 1; str = m_ListCtrl.GetItemText (i,GetColumnIndex("# of Lanes")); pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].QEM_Lanes = atoi(str); if(m_bSigalizedNode == true) { str = m_ListCtrl.GetItemText (i,GetColumnIndex("Green Start Time")); pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].QEM_StartTime = atoi(str); str = m_ListCtrl.GetItemText (i,GetColumnIndex("Green End Time")); pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].QEM_EndTime = atoi(str); str = m_ListCtrl.GetItemText (i,GetColumnIndex("Sat Flow Rate Per Lane Group")); pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].QEM_SatFlow = atoi(str); } if(movement_approach_turn != pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].movement_approach_turn || obs_turn_hourly_count != pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].obs_turn_hourly_count || obs_turn_delay != pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].obs_turn_delay || turning_prohibition_flag != pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].turning_prohibition_flag || QEM_lanes != pNode->m_MovementDataMap[m_TimingPlanName].m_MovementVector[i].QEM_Lanes ) { m_bModifiedFlag = true; m_pDoc->Modify (true); } } }
BOOL bGetMsgInfoFromMsgStr( CONST CString& omSendMsgLine, PSTCANDATA psCANData, BOOL bHexON) { CString omStrTemp =""; CString omStrMsgID =""; CString omStrDLC =""; CString omStrData =""; CString omStrMsgIDType =""; CHAR* pcStopString = NULL; BOOL nReturn = FALSE; CByteArray omByteArrayDataTx; // Get the string before first white space charactor omStrTemp = omSendMsgLine.SpanExcluding("\t "); if(omStrTemp.IsEmpty()==0) { INT nIndex = omStrTemp.GetLength(); if(nIndex>0) { // Remove the time stamp string omStrTemp = omSendMsgLine.Right(omSendMsgLine.GetLength() - nIndex -1); if(omStrTemp.IsEmpty() ==0) { omStrTemp.TrimLeft(); omStrTemp.TrimRight(); // Get the message ID after removing Tx/Rx string omStrMsgID = omStrTemp.SpanExcluding("\t "); if( omStrMsgID.Compare("Tx") == 0 ) { psCANData->m_ucDataType = TX_FLAG; } else { psCANData->m_ucDataType = RX_FLAG; } nIndex = omStrMsgID.GetLength(); omStrTemp = omStrTemp.Right(omStrTemp.GetLength() - nIndex - 1); omStrTemp.TrimLeft(); // Channel ID omStrMsgID = omStrTemp.SpanExcluding("\t "); UCHAR ucChannel = (UCHAR) strtol( (LPCTSTR )omStrMsgID,&pcStopString ,10); nIndex = omStrMsgID.GetLength(); omStrTemp = omStrTemp.Right(omStrTemp.GetLength() - nIndex -1); omStrTemp.TrimLeft(); // Get the message with name omStrMsgID = omStrTemp.SpanExcluding("\t "); // Get the rest of the string. nIndex = omStrMsgID.GetLength(); omStrTemp = omStrTemp.Right(omStrTemp.GetLength() - nIndex -1); omStrTemp.TrimLeft(); // Get message ID string after removing any message name. omStrMsgID = omStrMsgID.SpanExcluding(defMSGID_NAME_DELIMITER); UINT unMsgID = 0; if( bHexON == TRUE) { unMsgID = (UINT) strtol( (LPCTSTR )omStrMsgID,&pcStopString ,16); } else { unMsgID = (UINT) strtol( (LPCTSTR )omStrMsgID,&pcStopString ,10); } // Get the message ID Type omStrMsgIDType = omStrTemp.SpanExcluding("\t "); // Message Id type is EXTENDED if(omStrMsgIDType.Find(defMSGID_EXTENDED) != -1) { psCANData->m_uDataInfo.m_sCANMsg.m_ucEXTENDED = 1; }// Message Id type is STD else if(omStrMsgIDType.Find(defMSGID_STD)!= -1) { psCANData->m_uDataInfo.m_sCANMsg.m_ucEXTENDED = 0; } // Message Id type is RTR if(omStrMsgIDType.Find(defMSGID_RTR)!= -1) { psCANData->m_uDataInfo.m_sCANMsg.m_ucRTR = 1; } else { psCANData->m_uDataInfo.m_sCANMsg.m_ucRTR = 0; } nIndex = omStrMsgIDType.GetLength(); omStrTemp = omStrTemp.Right(omStrTemp.GetLength() - nIndex -1); omStrTemp.TrimLeft(); // Get the DLC omStrDLC = omStrTemp.SpanExcluding("\t "); nIndex = omStrDLC.GetLength(); UINT unDLC = (UINT) strtol((LPCTSTR)omStrDLC,&pcStopString ,16); omStrTemp = omStrTemp.Right(omStrTemp.GetLength() - nIndex -1); omStrTemp.TrimLeft(); // Get the data string omStrData = omStrTemp; // Check if Message ID and DLC is valid. if(unMsgID>0 && unDLC<=8 && unDLC>0) { nIndex = omStrData.GetLength(); vConvStrtoByteArray(&omByteArrayDataTx, omStrData.GetBuffer(nIndex),bHexON); omStrData.ReleaseBuffer(nIndex); INT nTotalData = (INT)omByteArrayDataTx.GetSize(); // Check if String to Byte array conversion // has return a valid data if(nTotalData<=8 ) { for(INT i = 0; i<nTotalData; i++) { psCANData->m_uDataInfo.m_sCANMsg.m_ucData[i] = omByteArrayDataTx.GetAt(i); } psCANData->m_uDataInfo.m_sCANMsg.m_unMsgID = unMsgID; psCANData->m_uDataInfo.m_sCANMsg.m_ucDataLen = (UCHAR)unDLC; psCANData->m_uDataInfo.m_sCANMsg.m_ucChannel = ucChannel; nReturn = TRUE; } } } } } return nReturn; }
void CMCASpecDataStat::OnClickListSpectra(NMHDR* /*pNMHDR*/, LRESULT* pResult) { int nItem; if (m_iShowSpectra && ((nItem = m_cListHistory.GetNextItem(-1,LVNI_SELECTED)) != -1)) { CString cString = m_cListHistory.GetItemText(nItem,0); // int nLine; // char szLine[MAX_PATH]; // nLine = ((CEdit*)GetDlgItem(IDC_EDIT_HISTORY))->LineFromChar(-1); // int iCount = ((CEdit*)GetDlgItem(IDC_EDIT_HISTORY))->GetLine(nLine,szLine,sizeof(szLine)); // szLine[iCount] = NULL; long lSpectrum[1024]; m_XYCtrl.m_crPixelColor = COLOR_DARKBLUE; //m_crPixelColor CString cName("Displayed Spectrum: "); cName += cString; SetDlgItemText(IDC_STATIC_SPECTRANAME,cName); if ((cString.Find(".chn") >= 0)|| (cString.Find(".CHN") >= 0)) //3/23/2005 PJM and DGP { CChnSpcEx Spec1(1024,lSpectrum,0,NULL,NULL); if (Spec1.Read((LPSTR)LPCSTR(cString))) { long nCh = Spec1.NumChans(); //load and display .chn ProcessSpectrumBufferForRealTimeGraphic(lSpectrum,nCh); } } else if ((cString.Find(".txt") >= 0) || (cString.Find(".TXT") >= 0)) //3/23/2005 PJM and DGP { //load and display .txt FILE *inFile; inFile = fopen(cString,"rt"); if (inFile) { int iSpectrumIndex = 0; while (!feof(inFile) && (iSpectrumIndex < 1024)) { fscanf(inFile,"%d",&(lSpectrum[iSpectrumIndex++])); } fclose(inFile); //load and display .chn ProcessSpectrumBufferForRealTimeGraphic(lSpectrum,iSpectrumIndex); } } else if ((cString.Find(".csv") >= 0) || (cString.Find(".CSV") >= 0)) //3/23/2005 PJM and DGP { //load and display .csv FILE *inFile; inFile = fopen(cString,"rt"); if (inFile) { int iSpectrumIndex = 0; while (!feof(inFile) && (iSpectrumIndex < 1024)) { fscanf(inFile,"%d,",&(lSpectrum[iSpectrumIndex])); iSpectrumIndex++; } fclose(inFile); //load and display .chn ProcessSpectrumBufferForRealTimeGraphic(lSpectrum,iSpectrumIndex); } } //allow incoming to be displayed // m_bBlockIncoming = false; } *pResult = 0; }
BOOL CFunctionView::UpdateFunctionInDocument() { BOOL bRetVal = FALSE; POSITION sStart = m_sStartPos; if ( sStart != NULL ) { CFunctionEditorDoc* pDoc = (CFunctionEditorDoc*)CView::GetDocument(); if ( pDoc != NULL ) { SBUS_SPECIFIC_INFO sBusSpecInfo; pDoc->bGetBusSpecificInfo(sBusSpecInfo); //Construct the Function Footer CString omStrFnFooter; // If it is global variable then select Global variable footer if( m_omStrFnName == GLOBAL_VARIABLES ) { omStrFnFooter = BUS_VAR_FOOTER; omStrFnFooter.Replace("PLACE_HODLER_FOR_BUSNAME", sBusSpecInfo.m_omBusName); } else { // Select function common footer omStrFnFooter = EDITOR_BUS_FN_FOOTER; // Form function specific footer omStrFnFooter.Replace("PLACE_HODLER_FOR_BUSNAME", sBusSpecInfo.m_omBusName); omStrFnFooter.Replace( "PLACE_HODLER_FOR_FUNCTIONNAME", m_omStrFnName ); } CString omStrLine(""); // Get the Edit control ref. CRichEditCtrl& romEditCtrl = GetRichEditCtrl(); // get the total lines of code in the rich edit control int nLineCount = romEditCtrl.GetLineCount(); long lStart, lEnd; // Get the cursor position romEditCtrl.GetSel(lStart, lEnd); // Get the cursor line and save m_nCurrentLine = (int) romEditCtrl.LineFromChar(lStart); BOOL bDone = FALSE; pDoc->m_omSourceCodeTextList.GetNext(sStart); POSITION sPos1 = NULL; POSITION sPos2 = NULL; for( sPos1 = sStart; ( ((sPos2 = sPos1) != NULL) && (!bDone) ); ) { CString omStrDel = pDoc->m_omSourceCodeTextList.GetNext( sPos1 ); if( omStrDel.Find(omStrFnFooter) >= 0 ) { bDone = TRUE; } else { pDoc->m_omSourceCodeTextList.RemoveAt( sPos2 ); } } BOOL bFirst = TRUE; POSITION sPos = m_sStartPos; for (int nLineIndex = 0; nLineIndex < nLineCount; nLineIndex++) { CString omStrNewItem(""); int nCharIndex = GetRichEditCtrl().LineIndex(nLineIndex); int nLineLength = GetRichEditCtrl().LineLength(nCharIndex); nLineLength = ( nLineLength < 4 ) ? 4 : nLineLength; GetRichEditCtrl().GetLine(nLineIndex, omStrNewItem.GetBuffer(nLineLength), nLineLength); omStrNewItem.ReleaseBuffer(nLineLength); omStrNewItem.TrimRight(); if ( bFirst ) { pDoc->m_omSourceCodeTextList.SetAt(sPos, omStrNewItem); bFirst = FALSE; } else { pDoc->m_omSourceCodeTextList.InsertAfter( sPos, omStrNewItem); pDoc->m_omSourceCodeTextList.GetNext(sPos); } } bRetVal = TRUE; } } return bRetVal; }
void CSchedulerWnd::Update(int nColumn, BOOL bSort) { HRESULT hr; CComPtr< IEnumWorkItems > pEnum; hr = m_pScheduler->Enum( &pEnum ); if ( FAILED( hr ) ) return; CLiveList pLiveList( 6 ); int nCount = 1; for ( ; ; ) { LPWSTR* pszTaskName = NULL; hr = pEnum->Next( 1, &pszTaskName, NULL ); if ( hr != S_OK ) // No tasks left break; CString sTaskName = *pszTaskName; CoTaskMemFree( pszTaskName ); CString sVendor = sTaskName.SpanExcluding( _T(".") ); if ( sVendor.Compare( CLIENT_NAME_T ) != 0 ) // Wrong name continue; DWORD_PTR nNumber = _tstoi( sTaskName.Mid( sVendor.GetLength() + 1 ) ); CComPtr< ITask > pTask; hr = m_pScheduler->Activate( sTaskName, IID_ITask, (IUnknown**)&pTask ); if ( FAILED( hr ) ) // Can't open task continue; DWORD nFlags = 0; hr = pTask->GetFlags( &nFlags ); BOOL bActive = ( ( nFlags & TASK_FLAG_DISABLED ) != TASK_FLAG_DISABLED ); HRESULT hrStatus = S_OK; hr = pTask->GetStatus( &hrStatus ); CString sTriggerString; LPWSTR szTriggerString = NULL; hr = pTask->GetTriggerString( 0, &szTriggerString ); if ( hr == S_OK ) { sTriggerString = szTriggerString; CoTaskMemFree( szTriggerString ); } CString strDate, strTime; SYSTEMTIME pTime = {}; hr = pTask->GetNextRunTime( &pTime ); if ( hr == S_OK ) { GetDateFormat( LOCALE_USER_DEFAULT, DATE_SHORTDATE, &pTime, NULL, strDate.GetBuffer( 64 ), 64 ); GetTimeFormat( LOCALE_USER_DEFAULT, TIME_NOSECONDS, &pTime, NULL, strTime.GetBuffer( 64 ), 64 ); strDate.ReleaseBuffer(); strTime.ReleaseBuffer(); } else if ( hr == SCHED_S_TASK_DISABLED ) bActive = FALSE; CString sStatus; DWORD nExitCode = 0; hr = pTask->GetExitCode( &nExitCode ); if ( SUCCEEDED( hr ) ) { sStatus.Format( _T("0x%08X"), nExitCode ); } int nAction = -1; LPWSTR szParams = NULL; hr = pTask->GetParameters( &szParams ); if ( SUCCEEDED( hr ) ) { CString sParams = szParams; CoTaskMemFree( szParams ); int nPos = sParams.Find( _T("task") ); if ( nPos != -1 ) nAction = _tstoi( sParams.Mid( nPos + 4 ) ); else nAction = SYSTEM_START; } CString sComment; LPWSTR szComment = NULL; hr = pTask->GetComment( &szComment ); if ( SUCCEEDED( hr ) ) { sComment = szComment; CoTaskMemFree( szComment ); } //Adding tasks we got from Scheduler to temp list and getting a handle //to modify their properties according to scheduler item. CLiveItem* pItem = pLiveList.Add( nNumber ); if ( ( nFlags & TASK_FLAG_DISABLED ) != TASK_FLAG_DISABLED ) pItem->SetImage( 0, SCHEDULE_ITEM_ACTIVE ); else pItem->SetImage( 0, SCHEDULE_ITEM_INACTIVE ); //Action column switch ( nAction ) { case BANDWIDTH_FULLSPEED: pItem->Set( 0, LoadString( IDS_SCHEDULER_BANDWIDTH_FULLSPEED ) ); break; case BANDWIDTH_REDUCEDSPEED: pItem->Set( 0, LoadString( IDS_SCHEDULER_BANDWIDTH_REDUCEDSPEED ) ); break; case BANDWIDTH_STOP: pItem->Set( 0, LoadString( IDS_SCHEDULER_BANDWIDTH_STOP ) ); break; case SYSTEM_DIALUP_DC: pItem->Set( 0, LoadString( IDS_SCHEDULER_SYSTEM_DIALUP_DC ) ); break; case SYSTEM_EXIT: pItem->Set( 0, LoadString( IDS_SCHEDULER_SYSTEM_EXIT ) ); break; case SYSTEM_SHUTDOWN: pItem->Set( 0, LoadString( IDS_SCHEDULER_SYSTEM_SHUTDOWN ) ); break; case SYSTEM_START: pItem->Set( 0, LoadString( IDS_SCHEDULER_SYSTEM_START ) ); break; } // Date column pItem->Set( 1, sTriggerString ); // Time column pItem->Set( 2, strDate + _T(" ") + strTime ); // Active column if ( bActive ) { switch ( hrStatus ) { case SCHED_S_TASK_NO_MORE_RUNS: pItem->Set( 3, LoadString( IDS_SCHEDULER_TASK_DONE ) ); break; case SCHED_S_TASK_RUNNING: pItem->Set( 3, LoadString( IDS_SCHEDULER_TASK_ACTIVE ) ); break; default: pItem->Set( 3, LoadString( IDS_SCHEDULER_TASK_WAITING ) ); } } else pItem->Set( 3, LoadString( IDS_SCHEDULER_TASK_INACTIVE ) ); // Status column pItem->Set( 4, sStatus ); //Description column pItem->Set( 5, sComment ); ++nCount; } // In case scheduler gave nothing if ( nCount == 1 ) { CLiveItem* pDefault = pLiveList.Add( (DWORD_PTR)0 ); pDefault->Set( 0, LoadString( IDS_SCHEDULER_NOTASK ) ); pDefault->SetImage( 0, SCHEDULE_NO_ITEM ); } if ( nColumn >= 0 ) { SetWindowLongPtr( m_wndList.GetSafeHwnd(), GWLP_USERDATA, 0 - nColumn - 1 ); } pLiveList.Apply( &m_wndList, bSort ); //Putting items in the main list tLastUpdate = GetTickCount(); // Update time after it's done doing its work }
// strURL: URL to decode. CString CURLEncode::Decode(CString strURL) { int i=strURL.Find(_T('%')); TCHAR tc1=0, tc2=0; BYTE b=0; BOOL bFound=FALSE; while (i>-1) { tc1=strURL.GetAt(i+1); tc2=strURL.GetAt(i+2); if (isHex(tc1) && isHex(tc2)) { b=hexToDec(tc1, tc2); // first deal with 1-byte unprintable characters if (b<0x1F || b==0x7F) { strURL.SetAt(i, b); strURL.Delete(i+1, 2); } else { // Then deal with 1-byte unsafe/reserved characters // We are reading for those static LPCTSTR strings, // so we have nice support for Unicode bFound=FALSE; for (int ii=0; ii<m_iUnsafeLen && !bFound; ii++) { if (__toascii(m_lpszUnsafeString[ii])==b) { strURL.SetAt(i, m_lpszUnsafeString[ii]); strURL.Delete(i+1, 2); bFound=TRUE; } } for (int ii=0; ii<m_iReservedLen && !bFound; ii++) { if (__toascii(m_lpszReservedString[ii])==b) { strURL.SetAt(i, m_lpszReservedString[ii]); strURL.Delete(i+1, 2); bFound=TRUE; } } // Then deal with UTF-8 (2-bytes) characters if (!bFound) { // We need to have 2 bytes for decoding if (strURL.GetAt(i+3)==_T('%')) { tc1=strURL.GetAt(i+4); tc2=strURL.GetAt(i+5); if (isHex(tc1) && isHex(tc2)) { BYTE b2=hexToDec(tc1, tc2); strURL.SetAt(i, fromUTF8(MAKEWORD(b2, b))); strURL.Delete(i+1, 5); } } } } } i=strURL.Find(_T('%'), i+1); } return strURL; }
CString COnlineSearch::_DoSearchOnline(LPCTSTR szText) { #ifdef _WIN32_WCE if(!CUtil::IsOnline()) return FALSE; #endif //CHttp *http = new CHttp(); //if(http != NULL) { if(m_proxyInfo.bProxy) /*CHttp::GetInstance().*/m_pHttp->SetProxy(CStringW(m_proxyInfo.sServer), m_proxyInfo.nPort, CStringW(m_proxyInfo.sUser), CStringW(m_proxyInfo.sPass)); /*CHttp::GetInstance().m_pHttp->ResetArguments();*/ CStringArray arr; CString s(szText); int pos = s.Find('|'); int num = _wtol(s.Mid(0, pos)); s = s.Mid(pos+1); CUtil::Tokenize(s, arr, num); for(int i = 0; i < arr.GetCount(); i++) { CString sParam = arr.GetAt(i); pos = sParam.Find('='); /*CHttp::GetInstance().*/m_pHttp->AddArguments(sParam.Mid(0, pos).Trim(), sParam.Mid(pos+1).Trim()); } if(/*CHttp::GetInstance().*/m_pHttp->Request(CStringW(m_sURL))) { CString sText = /*CHttp::GetInstance().*/m_pHttp->Response(); int nCode; if((sText.IsEmpty() || !CUtil::ValidatePost(&sText, TRUE, &nCode)) /*&& m_lpfnNoRecords != NULL*/) { STLOG_WRITE("%s: Sem registros ou erro na recepчуo. Retorno servidor: [%d: %S]", __FUNCTION__, nCode, sText); //m_lpfnNoRecords(GetParent(), this); } else { STLOG_WRITE(sText); //if(m_lpfnSelection != NULL) //if(_listener != NULL) //{ // //m_lpfnSelection(GetParent(), this, s1); // _listener->OnSelection(GetParent(), this, s1); // //delete http; return sText; //} } } else { STLOG_WRITE("CEditDB::_DoSearchOnline: Erro na pesquisa online"); } //delete http; } return L""; }
LRESULT CRefLogDlg::OnFindDialogMessage(WPARAM /*wParam*/, LPARAM /*lParam*/) { ASSERT(m_pFindDialog != NULL); if (m_RefList.m_arShownList.IsEmpty()) return 0; // If the FR_DIALOGTERM flag is set, // invalidate the handle identifying the dialog box. if (m_pFindDialog->IsTerminating()) { m_pFindDialog = NULL; return 0; } // If the FR_FINDNEXT flag is set, // call the application-defined search routine // to search for the requested string. if (m_pFindDialog->FindNext()) { //read data from dialog CString findString = m_pFindDialog->GetFindString(); bool bFound = false; bool bCaseSensitive = !!(m_pFindDialog->m_nFlags & FR_MATCHCASE); if (!bCaseSensitive) findString.MakeLower(); int i = m_nSearchLine; if (i < 0 || i >= m_RefList.m_arShownList.GetCount()) i = 0; do { GitRev * data = (GitRev*)m_RefList.m_arShownList.SafeGetAt(i); CString str; str += data->m_Ref; str += _T("\n"); str += data->m_RefAction; str += _T("\n"); str += data->m_CommitHash.ToString(); str += _T("\n"); str += data->GetSubject(); str += _T("\n"); str += data->GetBody(); str += _T("\n"); if (!bCaseSensitive) str.MakeLower(); if (str.Find(findString) >= 0) bFound = true; ++i; if(!bFound && i >= m_RefList.m_arShownList.GetCount()) i=0; } while (i != m_nSearchLine && (!bFound)); if (bFound) { m_RefList.SetHotItem(i - 1); m_RefList.EnsureVisible(i - 1, FALSE); m_nSearchLine = i; } else MessageBox(_T("\"") + findString + _T("\" ") + CString(MAKEINTRESOURCE(IDS_NOTFOUND)), _T("TortoiseGit"), MB_ICONINFORMATION); } return 0; }
CString ProjectProperties::GetBugIDFromLog(CString& msg) { CString sBugID; if (!sMessage.IsEmpty()) { CString sBugLine; CString sFirstPart; CString sLastPart; BOOL bTop = FALSE; if (nBugIdPos < 0) return sBugID; sFirstPart = sMessage.Left(nBugIdPos); sLastPart = sMessage.Mid(nBugIdPos + 7); msg.TrimRight('\n'); if (msg.ReverseFind('\n')>=0) { if (bAppend) sBugLine = msg.Mid(msg.ReverseFind('\n')+1); else { sBugLine = msg.Left(msg.Find('\n')); bTop = TRUE; } } else { if (bNumber) { // find out if the message consists only of numbers bool bOnlyNumbers = true; for (int i=0; i<msg.GetLength(); ++i) { if (!_istdigit(msg[i])) { bOnlyNumbers = false; break; } } if (bOnlyNumbers) sBugLine = msg; } else sBugLine = msg; } if (sBugLine.IsEmpty() && (msg.ReverseFind('\n') < 0)) { sBugLine = msg.Mid(msg.ReverseFind('\n')+1); } if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0) sBugLine.Empty(); if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0) sBugLine.Empty(); if (sBugLine.IsEmpty()) { if (msg.Find('\n')>=0) sBugLine = msg.Left(msg.Find('\n')); if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0) sBugLine.Empty(); if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0) sBugLine.Empty(); bTop = TRUE; } if (sBugLine.IsEmpty()) return sBugID; sBugID = sBugLine.Mid(sFirstPart.GetLength(), sBugLine.GetLength() - sFirstPart.GetLength() - sLastPart.GetLength()); if (bTop) { msg = msg.Mid(sBugLine.GetLength()); msg.TrimLeft('\n'); } else { msg = msg.Left(msg.GetLength()-sBugLine.GetLength()); msg.TrimRight('\n'); } } return sBugID; }
BOOL CPatch::OpenUnifiedDiffFile(const CString& filename) { CString sLine; EOL ending = EOL_NOENDING; INT_PTR nIndex = 0; INT_PTR nLineCount = 0; CCrashReport::Instance().AddFile2(filename, NULL, _T("unified diff file"), CR_AF_MAKE_FILE_COPY); CFileTextLines PatchLines; if (!PatchLines.Load(filename)) { m_sErrorMessage = PatchLines.GetErrorString(); return FALSE; } m_UnicodeType = PatchLines.GetUnicodeType(); FreeMemory(); nLineCount = PatchLines.GetCount(); //now we got all the lines of the patch file //in our array - parsing can start... for(nIndex=0;nIndex<PatchLines.GetCount();nIndex++) { sLine = PatchLines.GetAt(nIndex); if(sLine.Left(10).Compare(_T("diff --git")) == 0) { this->m_IsGitPatch=true; break; } } //first, skip possible garbage at the beginning //garbage is finished when a line starts with "Index: " //and the next line consists of only "=" characters if( !m_IsGitPatch ) { for (nIndex=0; nIndex<PatchLines.GetCount(); nIndex++) { sLine = PatchLines.GetAt(nIndex); if (sLine.Left(4).Compare(_T("--- "))==0) break; if ((nIndex+1)<PatchLines.GetCount()) { sLine = PatchLines.GetAt(nIndex+1); if(sLine.IsEmpty()&&m_IsGitPatch) continue; sLine.Remove('='); if (sLine.IsEmpty()) break; } } } if ((PatchLines.GetCount()-nIndex) < 2) { //no file entry found. m_sErrorMessage.LoadString(IDS_ERR_PATCH_NOINDEX); return FALSE; } if( m_IsGitPatch ) return ParserGitPatch(PatchLines,nIndex); //from this point on we have the real unified diff data int state = 0; Chunks * chunks = NULL; Chunk * chunk = NULL; int nAddLineCount = 0; int nRemoveLineCount = 0; int nContextLineCount = 0; for ( ;nIndex<PatchLines.GetCount(); nIndex++) { sLine = PatchLines.GetAt(nIndex); ending = PatchLines.GetLineEnding(nIndex); if (ending != EOL_NOENDING) ending = EOL_AUTOLINE; if (state == 0) { if ((sLine.Left(4).Compare(_T("--- "))==0)&&((sLine.Find('\t') >= 0)||this->m_IsGitPatch)) { state = 2; if (chunks) { //this is a new file diff, so add the last one to //our array. m_arFileDiffs.Add(chunks); } chunks = new Chunks(); int nTab = sLine.Find('\t'); int filestart = 4; if(m_IsGitPatch) { nTab=sLine.GetLength(); filestart = 6; } if (nTab >= 0) { chunks->sFilePath = sLine.Mid(filestart, nTab-filestart).Trim(); } } } switch (state) { case 0: //Index: <filepath> { CString nextLine; if ((nIndex+1)<PatchLines.GetCount()) { nextLine = PatchLines.GetAt(nIndex+1); if (!nextLine.IsEmpty()) { nextLine.Remove('='); if (nextLine.IsEmpty()) { if (chunks) { //this is a new file diff, so add the last one to //our array. m_arFileDiffs.Add(chunks); } chunks = new Chunks(); int nColon = sLine.Find(':'); if (nColon >= 0) { chunks->sFilePath = sLine.Mid(nColon+1).Trim(); if (chunks->sFilePath.Find('\t')>=0) chunks->sFilePath.Left(chunks->sFilePath.Find('\t')).TrimRight(); if (chunks->sFilePath.Right(9).Compare(_T("(deleted)"))==0) chunks->sFilePath.Left(chunks->sFilePath.GetLength()-9).TrimRight(); if (chunks->sFilePath.Right(7).Compare(_T("(added)"))==0) chunks->sFilePath.Left(chunks->sFilePath.GetLength()-7).TrimRight(); } state++; } } } if (state == 0) { if (nIndex > 0) { nIndex--; state = 4; if (chunks == NULL) { //the line //Index: <filepath> //was not found at the start of a file diff! break; } } } } break; case 1: //==================== { sLine.Remove('='); if (sLine.IsEmpty()) { // if the next line is already the start of the chunk, // then the patch/diff file was not created by svn. But we // still try to use it if (PatchLines.GetCount() > (nIndex + 1)) { if (PatchLines.GetAt(nIndex+1).Left(2).Compare(_T("@@"))==0) { state += 2; } } state++; } else { //the line //========================= //was not found m_sErrorMessage.Format(IDS_ERR_PATCH_NOEQUATIONCHARLINE, nIndex); goto errorcleanup; } } break; case 2: //--- <filepath> { if (sLine.Left(3).Compare(_T("---"))!=0) { //no starting "---" found //seems to be either garbage or just //a binary file. So start over... state = 0; nIndex--; if (chunks) { delete chunks; chunks = NULL; } break; } sLine = sLine.Mid(3); //remove the "---" sLine =sLine.Trim(); //at the end of the filepath there's a revision number... int bracket = sLine.ReverseFind('('); if (bracket < 0) // some patch files can have another '(' char, especially ones created in Chinese OS bracket = sLine.ReverseFind(0xff08); CString num = sLine.Mid(bracket); //num = "(revision xxxxx)" num = num.Mid(num.Find(' ')); num = num.Trim(_T(" )")); // here again, check for the Chinese bracket num = num.Trim(0xff09); chunks->sRevision = num; if (bracket < 0) { if (chunks->sFilePath.IsEmpty()) chunks->sFilePath = sLine.Trim(); } else chunks->sFilePath = sLine.Left(bracket-1).Trim(); if (chunks->sFilePath.Find('\t')>=0) { chunks->sFilePath = chunks->sFilePath.Left(chunks->sFilePath.Find('\t')); } state++; } break; case 3: //+++ <filepath> { if (sLine.Left(3).Compare(_T("+++"))!=0) { //no starting "+++" found m_sErrorMessage.Format(IDS_ERR_PATCH_NOADDFILELINE, nIndex); goto errorcleanup; } sLine = sLine.Mid(3); //remove the "---" sLine =sLine.Trim(); //at the end of the filepath there's a revision number... int bracket = sLine.ReverseFind('('); if (bracket < 0) // some patch files can have another '(' char, especially ones created in Chinese OS bracket = sLine.ReverseFind(0xff08); CString num = sLine.Mid(bracket); //num = "(revision xxxxx)" num = num.Mid(num.Find(' ')); num = num.Trim(_T(" )")); // here again, check for the Chinese bracket num = num.Trim(0xff09); chunks->sRevision2 = num; if (bracket < 0) chunks->sFilePath2 = sLine.Trim(); else chunks->sFilePath2 = sLine.Left(bracket-1).Trim(); if (chunks->sFilePath2.Find('\t')>=0) { chunks->sFilePath2 = chunks->sFilePath2.Left(chunks->sFilePath2.Find('\t')); } state++; } break; case 4: //@@ -xxx,xxx +xxx,xxx @@ { //start of a new chunk if (sLine.Left(2).Compare(_T("@@"))!=0) { //chunk doesn't start with "@@" //so there's garbage in between two file diffs state = 0; if (chunk) { delete chunk; chunk = 0; if (chunks) { for (int i=0; i<chunks->chunks.GetCount(); i++) { delete chunks->chunks.GetAt(i); } chunks->chunks.RemoveAll(); delete chunks; chunks = NULL; } } break; //skip the garbage } sLine = sLine.Mid(2); sLine = sLine.Trim(); chunk = new Chunk(); CString sRemove = sLine.Left(sLine.Find(' ')); CString sAdd = sLine.Mid(sLine.Find(' ')); chunk->lRemoveStart = (-_ttol(sRemove)); if (sRemove.Find(',')>=0) { sRemove = sRemove.Mid(sRemove.Find(',')+1); chunk->lRemoveLength = _ttol(sRemove); } else { chunk->lRemoveStart = 0; chunk->lRemoveLength = (-_ttol(sRemove)); } chunk->lAddStart = _ttol(sAdd); if (sAdd.Find(',')>=0) { sAdd = sAdd.Mid(sAdd.Find(',')+1); chunk->lAddLength = _ttol(sAdd); } else { chunk->lAddStart = 1; chunk->lAddLength = _ttol(sAdd); } state++; } break; case 5: //[ |+|-] <sourceline> { //this line is either a context line (with a ' ' in front) //a line added (with a '+' in front) //or a removed line (with a '-' in front) TCHAR type; if (sLine.IsEmpty()) type = ' '; else type = sLine.GetAt(0); if (type == ' ') { //it's a context line - we don't use them here right now //but maybe in the future the patch algorithm can be //extended to use those in case the file to patch has //already changed and no base file is around... chunk->arLines.Add(RemoveUnicodeBOM(sLine.Mid(1))); chunk->arLinesStates.Add(PATCHSTATE_CONTEXT); chunk->arEOLs.push_back(ending); nContextLineCount++; } else if (type == '\\') { //it's a context line (sort of): //warnings start with a '\' char (e.g. "\ No newline at end of file") //so just ignore this... } else if (type == '-') { //a removed line chunk->arLines.Add(RemoveUnicodeBOM(sLine.Mid(1))); chunk->arLinesStates.Add(PATCHSTATE_REMOVED); chunk->arEOLs.push_back(ending); nRemoveLineCount++; } else if (type == '+') { //an added line chunk->arLines.Add(RemoveUnicodeBOM(sLine.Mid(1))); chunk->arLinesStates.Add(PATCHSTATE_ADDED); chunk->arEOLs.push_back(ending); nAddLineCount++; } else { //none of those lines! what the hell happened here? m_sErrorMessage.Format(IDS_ERR_PATCH_UNKOWNLINETYPE, nIndex); goto errorcleanup; } if ((chunk->lAddLength == (nAddLineCount + nContextLineCount)) && chunk->lRemoveLength == (nRemoveLineCount + nContextLineCount)) { //chunk is finished if (chunks) chunks->chunks.Add(chunk); else delete chunk; chunk = NULL; nAddLineCount = 0; nContextLineCount = 0; nRemoveLineCount = 0; state = 0; } } break; default: ASSERT(FALSE); } // switch (state) } // for ( ;nIndex<m_PatchLines.GetCount(); nIndex++) if (chunk) { m_sErrorMessage.LoadString(IDS_ERR_PATCH_CHUNKMISMATCH); goto errorcleanup; } if (chunks) m_arFileDiffs.Add(chunks); return TRUE; errorcleanup: if (chunk) delete chunk; if (chunks) { for (int i=0; i<chunks->chunks.GetCount(); i++) { delete chunks->chunks.GetAt(i); } chunks->chunks.RemoveAll(); delete chunks; } FreeMemory(); return FALSE; }
std::vector<CHARRANGE> ProjectProperties::FindBugIDPositions(const CString& msg) { size_t offset1 = 0; size_t offset2 = 0; std::vector<CHARRANGE> result; // first use the checkre string to find bug ID's in the message if (!sCheckRe.IsEmpty()) { if (!sBugIDRe.IsEmpty()) { // match with two regex strings (without grouping!) try { AutoUpdateRegex(); const std::tr1::wsregex_iterator end; std::wstring s = msg; for (std::tr1::wsregex_iterator it(s.begin(), s.end(), regCheck); it != end; ++it) { // (*it)[0] is the matched string std::wstring matchedString = (*it)[0]; ptrdiff_t matchpos = it->position(0); for (std::tr1::wsregex_iterator it2(matchedString.begin(), matchedString.end(), regBugID); it2 != end; ++it2) { ATLTRACE(_T("matched id : %s\n"), (*it2)[0].str().c_str()); ptrdiff_t matchposID = it2->position(0); CHARRANGE range = {(LONG)(matchpos+matchposID), (LONG)(matchpos+matchposID+(*it2)[0].str().size())}; result.push_back(range); } } } catch (std::exception) {} } else { try { AutoUpdateRegex(); const std::tr1::wsregex_iterator end; std::wstring s = msg; for (std::tr1::wsregex_iterator it(s.begin(), s.end(), regCheck); it != end; ++it) { const std::tr1::wsmatch match = *it; // we define group 1 as the whole issue text and // group 2 as the bug ID if (match.size() >= 2) { ATLTRACE(_T("matched id : %s\n"), std::wstring(match[1]).c_str()); CHARRANGE range = {(LONG)(match[1].first-s.begin()), (LONG)(match[1].second-s.begin())}; result.push_back(range); } } } catch (std::exception) {} } } else if (result.empty() && (!sMessage.IsEmpty())) { CString sBugLine; CString sFirstPart; CString sLastPart; BOOL bTop = FALSE; if (nBugIdPos < 0) return result; sFirstPart = sMessage.Left(nBugIdPos); sLastPart = sMessage.Mid(nBugIdPos + 7); CString sMsg = msg; sMsg.TrimRight('\n'); if (sMsg.ReverseFind('\n')>=0) { if (bAppend) sBugLine = sMsg.Mid(sMsg.ReverseFind('\n')+1); else { sBugLine = sMsg.Left(sMsg.Find('\n')); bTop = TRUE; } } else sBugLine = sMsg; if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0) sBugLine.Empty(); if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0) sBugLine.Empty(); if (sBugLine.IsEmpty()) { if (sMsg.Find('\n')>=0) sBugLine = sMsg.Left(sMsg.Find('\n')); if (sBugLine.Left(sFirstPart.GetLength()).Compare(sFirstPart)!=0) sBugLine.Empty(); if (sBugLine.Right(sLastPart.GetLength()).Compare(sLastPart)!=0) sBugLine.Empty(); bTop = TRUE; } if (sBugLine.IsEmpty()) return result; CString sBugIDPart = sBugLine.Mid(sFirstPart.GetLength(), sBugLine.GetLength() - sFirstPart.GetLength() - sLastPart.GetLength()); if (sBugIDPart.IsEmpty()) return result; //the bug id part can contain several bug id's, separated by commas if (!bTop) offset1 = sMsg.GetLength() - sBugLine.GetLength() + sFirstPart.GetLength(); else offset1 = sFirstPart.GetLength(); sBugIDPart.Trim(_T(",")); while (sBugIDPart.Find(',')>=0) { offset2 = offset1 + sBugIDPart.Find(','); CHARRANGE range = {(LONG)offset1, (LONG)offset2}; result.push_back(range); sBugIDPart = sBugIDPart.Mid(sBugIDPart.Find(',')+1); offset1 = offset2 + 1; } offset2 = offset1 + sBugIDPart.GetLength(); CHARRANGE range = {(LONG)offset1, (LONG)offset2}; result.push_back(range); } return result; }
void CDlgIADs::OnDblClkAttrValue() { int idx; HRESULT hr; idx = m_cValueList.GetCurSel(); if ( idx == LB_ERR ) { return; } // If someone click this it may be an interface that has the UI. // The interface value start with --> in the UI CString s; int xx; CString sArrow = ARROW_SYMBOL; m_cValueList.GetText( idx, s ); if ( s.Find(sArrow,0 ) == 0 ) { s = s.Mid( sArrow.GetLength() ); // Find the appropriate dialog box xx=0; while( !IsEqualIID( *adsiIfs[xx].pIID, IID_NULL ) && s != adsiIfs[xx].szIf ) { xx++; } if ( adsiIfs[xx].pFn ) { CString sAttr; VARIANT var; // We need to get the value again USES_CONVERSION; m_cAttrList.GetLBText( m_cAttrList.GetCurSel(), sAttr ); hr = m_pADs->Get( T2OLE(sAttr), &var); if ( SUCCEEDED(hr) ) { IUnknown *pUnk; hr = V_DISPATCH(&var)->QueryInterface( IID_IUnknown, (void**) &pUnk ); if ( SUCCEEDED(hr) ) { (*adsiIfs[xx].pFn)( pUnk, NULL ); } } } else { AfxMessageBox(_T("No UI implemented yet")); } return; } }
bool CWebpageHandler::ExtractInfo(int order) { CString tmpDisplay = _T(""); CString htmlStr = m_htmlStr; int endIndex, index, nextIndex; vector<ExtractionInfo>::iterator iter = m_extractionInfo.begin(); // feature 内部解析循环feature for(; iter!=m_extractionInfo.end(); ++iter) { CString ss = iter->title; tmpDisplay.Format(_T("%s<title>%s"), tmpDisplay, ss); tmpDisplay += _T("\n"); index = htmlStr.Find(iter->feature); htmlStr.Delete(0, index+1); index = htmlStr.Find(iter->field); htmlStr.Delete(0, index+1); index = htmlStr.Find(_T("href=")); htmlStr.Delete(0, index+5); CString token = htmlStr.Left(1); htmlStr.Delete(0); index = htmlStr.Find(token); tmpDisplay += (_T("<href>")+htmlStr.Left(index)+_T("\n")); // 添加链接标记 // field内部第一次解析信息(循环pos) vector<int>::iterator iter0 = iter->pos.begin(); int i = 0; for(; iter0!=iter->pos.end(); ++iter0) { if(*iter0 != 0) { for(; i<(*iter0); i++) index = htmlStr.Find(iter->startToken); (iter->startToken).ReleaseBuffer(); int len = (iter->startToken).GetLength(); htmlStr.Delete(0, index+len); index = htmlStr.Find(iter->endToken); tmpDisplay += (htmlStr.Left(index)+_T("\n")); htmlStr.Delete(0, index+1); } else { index=htmlStr.Find(iter->startToken); nextIndex = htmlStr.Find(iter->field); for(; index<nextIndex; index=htmlStr.Find(iter->startToken)) { (iter->startToken).ReleaseBuffer(); int len = (iter->startToken).GetLength(); htmlStr.Delete(0, index+len); index = htmlStr.Find(iter->endToken); tmpDisplay += (htmlStr.Left(index)+_T("\n")); htmlStr.Delete(0, index+1); nextIndex = htmlStr.Find(iter->field); } break; } } // field内部循环field(循环pos) if(iter->isGroup) { index = htmlStr.Find(iter->field); endIndex = htmlStr.Find(iter->endFeature); while(index < endIndex) { htmlStr.Delete(0, index+1); index = htmlStr.Find(_T("href=")); if(index >= endIndex) break; htmlStr.Delete(0, index+5); CString token = htmlStr.Left(1); htmlStr.Delete(0); index = htmlStr.Find(token); tmpDisplay += (_T("<href>")+htmlStr.Left(index)+_T("\n")); // 添加链接标记 htmlStr.Delete(0, index+1); vector<int>::iterator iter1 = iter->pos.begin(); int i = 0; for(; iter1!=iter->pos.end(); ++iter1) { if(*iter1 != 0) { for(; i<(*iter1); i++) index = htmlStr.Find(iter->startToken); (iter->startToken).ReleaseBuffer(); int len = (iter->startToken).GetLength(); htmlStr.Delete(0, index+len); index = htmlStr.Find(iter->endToken); tmpDisplay += (htmlStr.Left(index)+_T("\n")); htmlStr.Delete(0, index+1); } else { index=htmlStr.Find(iter->startToken); nextIndex = htmlStr.Find(iter->field); for(; index<nextIndex; index=htmlStr.Find(iter->startToken)) { (iter->startToken).ReleaseBuffer(); int len = (iter->startToken).GetLength(); htmlStr.Delete(0, index+len); index = htmlStr.Find(iter->endToken); tmpDisplay += (htmlStr.Left(index)+_T("\n")); htmlStr.Delete(0, index+1); nextIndex = htmlStr.Find(iter->field); } break; } } index = htmlStr.Find(iter->field); endIndex = htmlStr.Find(iter->endFeature); } } tmpDisplay += _T("\n"); } m_extractionInfo.clear(); m_displayExtractionInfo.insert(make_pair(order, tmpDisplay)); return true; }
void CPlaylistItem::AutoLoadFiles() { if (m_fns.IsEmpty()) { return; } const CAppSettings& s = AfxGetAppSettings(); CString fn = m_fns.GetHead(); if (s.fAutoloadAudio && fn.Find(_T("://")) < 0) { int i = fn.ReverseFind('.'); if (i > 0) { const CMediaFormats& mf = s.m_Formats; CString ext = fn.Mid(i + 1).MakeLower(); if (!mf.FindExt(ext, true)) { CString path = fn; path.Replace('/', '\\'); path = path.Left(path.ReverseFind('\\') + 1); WIN32_FIND_DATA fd; ZeroMemory(&fd, sizeof(WIN32_FIND_DATA)); HANDLE hFind = FindFirstFile(fn.Left(i) + _T("*.*"), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } CString fullpath = path + fd.cFileName; CString ext2 = fullpath.Mid(fullpath.ReverseFind('.') + 1).MakeLower(); if (!FindFileInList(m_fns, fullpath) && ext != ext2 && mf.FindExt(ext2, true) && mf.IsUsingEngine(fullpath, DirectShow)) { m_fns.AddTail(fullpath); } } while (FindNextFile(hFind, &fd)); FindClose(hFind); } } } } if (s.IsISRAutoLoadEnabled()) { const CString& pathList = s.strSubtitlePaths; CAtlArray<CString> paths; int pos = 0; do { CString path = pathList.Tokenize(_T(";"), pos); if (!path.IsEmpty()) { paths.Add(path); } } while (pos != -1); CString dir = fn; dir.Replace('\\', '/'); int l = dir.ReverseFind('/') + 1; int l2 = dir.ReverseFind('.'); if (l2 < l) { // no extension, read to the end l2 = fn.GetLength(); } CString title = dir.Mid(l, l2 - l); paths.Add(title); CAtlArray<Subtitle::SubFile> ret; Subtitle::GetSubFileNames(fn, paths, ret); for (size_t i = 0; i < ret.GetCount(); i++) { if (!FindFileInList(m_subs, ret[i].fn)) { m_subs.AddTail(ret[i].fn); } } } }
void CSynBCGPEditCtrl::SelectLanguage( UINT nLanguage ) { RemoveXMLSettings(); theApp.m_nSynLanguage = nLanguage; // 1)设置语言 m_SynLanguage.SetCurLanguage(nLanguage); // 2)设置分隔符 m_strWordDelimeters = m_SynLanguage.GetWordDelimeters(); m_strSpecialDelimiters = m_SynLanguage.GetSpecialDelimiters(); m_strIntelliSenseChars = m_SynLanguage.GetIntelliSenseChars(); CString strEscapeSequence, strEscapeSequences; int nPos, nPosPrior = 0; strEscapeSequences = m_SynLanguage.GetEscapeSequences(); nPos = strEscapeSequences.Find(_T(","), nPosPrior); while (nPos != -1) { strEscapeSequence = strEscapeSequences.Mid(nPosPrior, nPos - nPosPrior); AddEscapeSequence (strEscapeSequence); nPosPrior = nPos + 1; nPos = strEscapeSequences.Find(_T(","), nPosPrior); } // 3)设置关键字 BOOL bCaseSensitive; CString strWords; CString strWord; nPosPrior = 0; m_SynLanguage.GetWords(strWords, bCaseSensitive); nPos = strWords.Find(_T(","), nPosPrior); while (nPos != -1) { strWord = strWords.Mid(nPosPrior, nPos - nPosPrior); SetWordColor(strWord, m_clrSyn, -1, bCaseSensitive); nPosPrior = nPos + 1; nPos = strWords.Find(_T(","), nPosPrior); } nPosPrior = 0; m_SynLanguage.GetTypeWords(strWords, bCaseSensitive); nPos = strWords.Find(_T(","), nPosPrior); while (nPos != -1) { strWord = strWords.Mid(nPosPrior, nPos - nPosPrior); SetWordColor(strWord, m_clrType, -1, bCaseSensitive); nPosPrior = nPos + 1; nPos = strWords.Find(_T(","), nPosPrior); } m_SynLanguage.GetIsNumberColor(m_bNumberColor); // 4)设置注释 CString strBlockOpen, strBlockClose; m_SynLanguage.GetMultilineComment(strBlockOpen, strBlockClose, bCaseSensitive); if (_T("") != strBlockOpen.Trim()) { SetBlockColor(strBlockOpen, strBlockClose, TRUE, m_clrComment, -1, bCaseSensitive); } CString strBlockOpens; m_SynLanguage.GetLineComment(strBlockOpens, bCaseSensitive); nPosPrior = 0; nPos = strBlockOpens.Find(_T(","), nPosPrior); while (nPos != -1) { strBlockOpen = strBlockOpens.Mid(nPosPrior, nPos - nPosPrior); SetBlockColor(strBlockOpen, _T(""), FALSE, m_clrComment, -1, bCaseSensitive); nPosPrior = nPos + 1; nPos = strBlockOpens.Find(_T(","), nPosPrior); } // 5)设置字符串 m_SynLanguage.GetString(strBlockOpen, strBlockClose, bCaseSensitive); if (_T("") != strBlockOpen.Trim()) { SetBlockColor(strBlockOpen, strBlockClose, FALSE, m_clrString, -1, bCaseSensitive); } m_SynLanguage.GetChar(strBlockOpen, strBlockClose, bCaseSensitive); if (_T("") != strBlockOpen.Trim()) { SetBlockColor(strBlockOpen, strBlockClose, FALSE, m_clrChar, -1, bCaseSensitive); } // 6)设置折叠 if (m_pOutlineParser != NULL) { m_OutlineNodes.DeleteAllBlocks (); m_pOutlineParser->RemoveAllBlockTypes (); // 7)大纲设置 m_pOutlineParser->m_strDelimiters = m_strWordDelimeters; m_pOutlineParser->m_bCaseSensitive = m_SynLanguage.GetOutlineCaseSensitive(); m_pOutlineParser->m_bWholeWords = m_SynLanguage.GetOutlineWholeWords(); // 8)转义字符 m_SynLanguage.GetOutlineEscapeSequences(strEscapeSequences); nPosPrior = 0; nPos = strEscapeSequences.Find(_T(","), nPosPrior); while (nPos != -1) { strEscapeSequence = strEscapeSequences.Mid(nPosPrior, nPos - nPosPrior); m_pOutlineParser->AddEscapeSequence (strEscapeSequence); nPosPrior = nPos + 1; nPos = strEscapeSequences.Find(_T(","), nPosPrior); } // 9)折叠块 CString strBlock, strBlocks; CString strReplace, strNested, strIgnore; CStringList lstKeywordsList; int nBlockPos, nBlockPosPrior = 0; m_SynLanguage.GetOutlineBlockType(strBlocks); nPosPrior = 0; nPos = strBlocks.Find(_T("|"), nPosPrior); while (nPos != -1) { strBlock = strBlocks.Mid(nPosPrior, nPos - nPosPrior); nBlockPosPrior = 0; nBlockPos = strBlock.Find(_T(","), nBlockPosPrior); if (nBlockPos != -1) { strBlockOpen = strBlock.Mid(nBlockPosPrior, nBlockPos - nBlockPosPrior); nBlockPosPrior = nBlockPos + 1; nBlockPos = strBlock.Find(_T(","), nBlockPosPrior); if (nBlockPos != -1) { strBlockClose = strBlock.Mid(nBlockPosPrior, nBlockPos - nBlockPosPrior); nBlockPosPrior = nBlockPos + 1; nBlockPos = strBlock.Find(_T(","), nBlockPosPrior); if (nBlockPos != -1) { strReplace = strBlock.Mid(nBlockPosPrior, nBlockPos - nBlockPosPrior); nBlockPosPrior = nBlockPos + 1; nBlockPos = strBlock.Find(_T(","), nBlockPosPrior); if (nBlockPos != -1) { strNested = strBlock.Mid(nBlockPosPrior, nBlockPos - nBlockPosPrior); nBlockPosPrior = nBlockPos + 1; nBlockPos = strBlock.Find(_T(","), nBlockPosPrior); if (nBlockPos != -1) { strIgnore = strBlock.Mid(nBlockPosPrior, nBlockPos - nBlockPosPrior); nBlockPosPrior = nBlockPos + 1; nBlockPos = strBlock.Find(_T(","), nBlockPosPrior); lstKeywordsList.RemoveAll(); while (nBlockPos != -1) { lstKeywordsList.AddTail(strBlock.Mid(nBlockPosPrior, nBlockPos - nBlockPosPrior)); nBlockPosPrior = nBlockPos + 1; nBlockPos = strBlock.Find(_T(","), nBlockPosPrior); } m_pOutlineParser->AddBlockType(strBlockOpen, strBlockClose, strReplace, _ttoi(strNested), _ttoi(strIgnore), &lstKeywordsList); } } } } } nPosPrior = nPos + 1; nPos = strBlocks.Find(_T("|"), nPosPrior); } EnableAutoOutlining(!strBlocks.IsEmpty()); //禁止掉无大纲的语言,这样可以有“隐藏选定区域”功能 } // 10)设置超链接 m_lstURLPrefixes.RemoveAll (); m_arrHyperlinks.RemoveAll (); m_nCurrHyperlink = -1; m_nCurrHyperlinkHot = -1; m_lstURLPrefixes.AddTail (_T("http://")); m_lstURLPrefixes.AddTail (_T("ftp://")); m_lstURLPrefixes.AddTail (_T("mailto:")); m_lstURLPrefixes.AddTail (_T("news://")); m_lstURLPrefixes.AddTail (_T("file://")); m_lstURLPrefixes.AddTail (_T("telnet://")); m_lstURLPrefixes.AddTail (_T("gopher://")); m_lstURLPrefixes.AddTail (_T("prospero://")); m_lstURLPrefixes.AddTail (_T("wais://")); m_lstURLPrefixes.AddTail (_T("nntp://")); m_bCheckColorTags = FALSE; UseXmlParser (FALSE); switch (nLanguage) { case SYN_ASP: case SYN_HTML: case SYN_XML: m_bCheckColorTags = TRUE; EnableAutoOutlining(TRUE); UseXmlParser(TRUE); break; case SYN_PASCAL: SetBlockColor(_T("(*"), _T("*)"), FALSE, m_clrComment, -1, FALSE); break; case SYN_AUTOIT: //SetBlockColor(_T("#comments-start"), _T("#comments-end"), FALSE, m_clrComment, -1, FALSE); break; case SYN_D: SetBlockColor(_T("/+"), _T("+/"), FALSE, m_clrComment, -1, FALSE); SetBlockColor(_T("`"), _T("`"), FALSE, m_clrChar, -1, FALSE); break; } RedrawWindow(); UpdateAutoOutlining(); }