示例#1
0
int CFavUrlMenuDlg::GetUrls( CString strPath, CArray<ITEM, ITEM&> &arrItems )
{
	CStringArray arrSubDir;
	int curCnt = 0;

	if(strPath[strPath.GetLength() - 1] != _T('\\'))
		strPath += _T('\\');
	CString strFind = strPath + "*.*";
	WIN32_FIND_DATA	findData;
	HANDLE	hFile = NULL;

	hFile = FindFirstFile(strFind, &findData);
	if (hFile != INVALID_HANDLE_VALUE)
	{
		do 
		{
			if ( strcmp(".", findData.cFileName )==0
				|| strcmp("..", findData.cFileName)==0)
				continue;

			// 略过隐藏文件和系统文件
			if ( (findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
				|| (findData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM))
				continue;

			// 目录
			if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				arrSubDir.Add(findData.cFileName);

			// 文件
			CString strFileName = findData.cFileName;
			strFileName.MakeLower();
			if (strFileName.Right(4) == ".url")
			{
				ITEM item;
				item.type = ITEM_TYPE_URL;
				item.strPath = strPath + strFileName;
				strFileName = strFileName.Left(strFileName.GetLength() - 4);
				item.strName = strFileName;
				arrItems.Add(item);
				curCnt++;
			}
		} while (FindNextFile(hFile, &findData));
	}
	FindClose(hFile);

	INT_PTR nSubDirNum = arrSubDir.GetSize();
	for (INT_PTR i=0; i<nSubDirNum; i++)
	{
		CString strSubDirName = arrSubDir.GetAt(i);
		CArray<ITEM, ITEM&> aItems;
		int n = GetUrls(strPath+strSubDirName, aItems);
		// if (n != 0)	// 不添加空文件夹
		if (1)
		{
			ITEM item;
			item.type = ITEM_TYPE_DIRECTORY;
			item.strName = strSubDirName;
			item.strPath = strPath+strSubDirName;
			arrItems.Add(item);
		}
	}
	return curCnt;
}
示例#2
0
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;
}
示例#3
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;
}
示例#4
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;
}
BOOL checkPhoneIsUnicom(CString phone)
{
	//strcmp(s1, s2)==0
	// 130,131,132,155,156,185,186,145,176
	if (phone.GetLength() < 11){
		return false;
	}
	using namespace std;
	vector<std::string>::iterator result = find(cUrls.phoneHeads.begin(),cUrls.phoneHeads.end(),(LPCTSTR)phone.Left(3));

	if ( result == cUrls.phoneHeads.end( ) ) {
		return false;
	}else{
		return true;
	}
	/*
	if (strcmp(phone.Left(3), "130") == 0
		|| strcmp(phone.Left(3), "131") == 0
		|| strcmp(phone.Left(3), "132") == 0
		|| strcmp(phone.Left(3), "155") == 0
		|| strcmp(phone.Left(3), "156") == 0
		|| strcmp(phone.Left(3), "185") == 0
		|| strcmp(phone.Left(3), "186") == 0
		|| strcmp(phone.Left(3), "145") == 0
		|| strcmp(phone.Left(3), "176") == 0
		){
		return true;
	}
	return false;
	*/
}
示例#6
0
int CFileListIni::Onload(const void* param)
{
	PFILE_LIST_INI_LOAD_PARAM pLoadParam = (PFILE_LIST_INI_LOAD_PARAM)param;
	if (!CPathUtilEx::IsFileExist(pLoadParam->strX86File) && !CPathUtilEx::IsFileExist(pLoadParam->strX64File))
	{
		return Error_File_List_File_Is_Not_Exist;
	}

	//读取X86文件列表
	int nCount = GetPrivateProfileInt(SECTION_FILE_LIST, FILE_LIST_COUNT, 0, pLoadParam->strX86File);
	for (int i=0; i<nCount; i++)
	{
		CString strItem = GetPrivateProfileString(SECTION_FILE_LIST, StringAppendNumber(FILE_LIST_NAME_PREFIX, i), _T(""), pLoadParam->strX86File);
		int nIndex = strItem.Find(_T('>'));
		if (nIndex == -1)  //大于号未找到
		{
			return Error_File_List_Greater_Than_Not_Find;
		}
		else
		{
			CString strSrcFile = strItem.Left(nIndex);
			CString strDestFile = strItem.Mid(nIndex+1);
			if (strSrcFile.IsEmpty())
			{
				return Error_File_List_Source_File_Is_Empty;
			}
			else if (strDestFile.IsEmpty())
			{
				return Error_File_List_Dest_File_Is_Empty;
			}
			else
			{
				FILE_ITEM fileItem;
				fileItem.strName = CPathUtilEx::ExtractFileName(strSrcFile);
				if (fileItem.strName.IsEmpty())
				{
					return Error_File_List_Source_File_Is_Path;
				}
				else
				{
					fileItem.strSrcPath = strSrcFile;
					fileItem.strDestPath = strDestFile;
					m_x86FileList.push_back(fileItem);
				}				
			}
		}
	}

	//读取X64文件列表
	nCount = GetPrivateProfileInt(SECTION_FILE_LIST, FILE_LIST_COUNT, 0, pLoadParam->strX64File);
	for (int i=0; i<nCount; i++)
	{
		CString strItem = GetPrivateProfileString(SECTION_FILE_LIST, StringAppendNumber(FILE_LIST_NAME_PREFIX, i), _T(""), pLoadParam->strX64File);
		int nIndex = strItem.Find(_T('>'));
		if (nIndex == -1)  //大于号未找到
		{
			return Error_File_List_Greater_Than_Not_Find;
		}
		else
		{
			CString strSrcFile = strItem.Left(nIndex);
			CString strDestFile = strItem.Mid(nIndex+1);
			if (strSrcFile.IsEmpty())
			{
				return Error_File_List_Source_File_Is_Empty;
			}
			else if (strDestFile.IsEmpty())
			{
				return Error_File_List_Dest_File_Is_Empty;
			}
			else
			{
				FILE_ITEM fileItem;
				fileItem.strName = CPathUtilEx::ExtractFileName(strSrcFile);
				if (fileItem.strName.IsEmpty())
				{
					return Error_File_List_Source_File_Is_Path;
				}
				else
				{
					fileItem.strSrcPath = strSrcFile;
					fileItem.strDestPath = strDestFile;
					m_x64FileList.push_back(fileItem);
				}				
			}
		}
	}

	return Error_File_List_Success;
}
示例#7
0
void CUDSMainWnd::SendContinuosFrames( unsigned char abByteArr[],mPSTXSELMSGDATA psTxCanMsgUds, UDS_INTERFACE FInterface)
{

    CString Length;
    CString omTempByte;
    CString omByteStrTemp;
    int numberofFrames =0;                      // It will indicate how many multiples frames have been sent
    int c_numberOfTaken = numberOfTaken+2;      // The consecutive Messages will contain one byte more that the FirstFrame

    int i = aux_Finterface + c_numberOfTaken/2;         // aux_Finterface it's used to indicate that i must be bigger if we're in extended Addressing
    if (TotalLength*2<c_numberOfTaken)          // It only enters here once, at the end when the last message of the multiple frames has to be sent when
    {
        i = TotalLength+aux_Finterface;         // the number of frames that has to be sent is less than c_numberOfTaken
    }
    while (DatatoSend.GetLength())                          // While there is remaining data that has to be sent
    {
        omByteStrTemp = DatatoSend.Left(c_numberOfTaken);   //I take the part of the message that is going to be sent in the current Frame
        //while(FWait_SendingFrame){}                           // Wait if something is being sent in this moment

        while (omByteStrTemp.GetLength())
        {
            omTempByte = omByteStrTemp.Right(NO_OF_CHAR_IN_BYTE);
            abByteArr[i--] = (BYTE)_tcstol(omTempByte, L'\0', 16);              // It fills the array
            omByteStrTemp = omByteStrTemp.Left(omByteStrTemp.GetLength() - NO_OF_CHAR_IN_BYTE);
        }
        psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;                  // Consecutive Frames can always have 8 bytes
        abByteArr[initialByte]= ConsecutiveFrame;                   // Put the initial Byte of the consecutive frames in a long request
        SendSimpleDiagnosticMessage();                              // Send the current Message

        DatatoSend = DatatoSend.Right(((UINT)TotalLength*2)-c_numberOfTaken);        // DatatoSend will contain the rest of the bytes that hasn't been sent yet.
        TotalLength = (((UINT)TotalLength*2)-c_numberOfTaken)/2;
        ConsecutiveFrame++;
        if (ConsecutiveFrame == 0x30)
        {
            ConsecutiveFrame=0x20;    // Requirement from the ISO TP
        }
        numberofFrames++;

        if (numberofFrames == BSizE)        // It enters here when I've reached the quantity of Blocks settled by the ECU in the flow Control
        {
            FWaitFlow = TRUE;               // Now it has to wait for the Flow control again
            numberofFrames = 0;
            c_dDiffTime =0;
            return ;                        // Now it has to wait for another FlowControl
        }
        else
        {
            for(c_dDiffTime =0,c_unPreviousTime =-1 ; c_dDiffTime <=STMin; CalculateDiffTime()) {}      // Wait for the STMin Time settled by the ECU in the flow Control
        }
        c_unPreviousTime = -1;              //ReStart the variables for the timmings
        c_dDiffTime = 0;

        i = aux_Finterface + c_numberOfTaken/2;             // it must be a bigger number in the case of extended addressing-> aux_Finterface to control this.
        if (TotalLength*2<c_numberOfTaken)                  // It only enters here once, at the end when the last message of the multiple frames has to be sent when
        {
            i = TotalLength+aux_Finterface;                 // the number of frames that has to be sent is less than c_numberOfTaken
        }
    }
    m_omSendButton.EnableWindow(TRUE);      // It only enters here when it has sent all the msg
    // In the case that this function cannot be completed there is a timer as default to activate the SEND button
}
void CTemplateWizardDialog::Render()
{
	// Enable and disable the proper buttons.
	GreyButtons();

	// Set the new title.
	CString title;
	GetWindowText(title);
	int parenPos = title.Find(" (", 0);
	if (parenPos != -1)
		title = title.Left(parenPos);
	CString newTitle;
	if (m_curPage == -1)
	{
		newTitle = title;
	}
	else
	{
		newTitle.Format("%s (Page %d of %d)", title, m_curPage + 1, m_code.GetPageCount());
	}
	SetWindowText(newTitle);

	// Get the module name and strip the module filename from it, leaving the
	// module path.
	TCHAR moduleName[_MAX_PATH];
	moduleName[0] = 0;
	::GetModuleFileName(AfxGetInstanceHandle(), (TCHAR*)&moduleName, _MAX_PATH);
	TCHAR* ptr = _tcsrchr(moduleName, '\\');
	if (ptr)
	{
		ptr++;
		*ptr = 0;
	}

	///////////////////////////////////////////////////////////////////////////
	// Render the page.
	const CString& pageStr = (m_curPage == -1) ? m_page : m_code.GetPage(m_curPage);

	CRect clientRect;
	GetClientRect(clientRect);

	int curPos = 0;
//	while (true)
//	{
		// Grab the text.
		CString staticStr = pageStr;

//	}

	// See if it is a special case of a URL.
	bool isURL = false;
	CString leftStaticStr = staticStr.Left(7);
	if (leftStaticStr == "http://"  ||  leftStaticStr == "file://")
	{
		isURL = true;
	}

	CString strURL;
	if (!isURL)
	{
		m_htmlFile.SetLength(0);
		if (strnicmp(staticStr, "<html>", 6) != 0)
		{
			WriteString("<html><head>");
			WriteString("</head><body>");
			WriteString(staticStr);
			WriteString("</body></html>");
		}
		else
		{
			WriteString(staticStr);
		}

		// Generate a unique temporary name.
		char* asciiTempName = _tempnam(NULL, "WW200_");
		m_asciiFilename = CString(asciiTempName);
		free(asciiTempName);

		DWORD size = (DWORD)m_htmlFile.GetLength();
		BYTE* mem = m_htmlFile.Detach();
		CFile asciiFile;
		asciiFile.Open(m_asciiFilename, CFile::modeCreate | CFile::modeWrite);
		asciiFile.Write(mem, size);
		asciiFile.Close();
		free(mem);

//	CComBSTR bstrURL = "about:blank";
//	m_pBrowserApp->Navigate(bstrURL, NULL, NULL, NULL, NULL);

		strURL = m_asciiFilename;
	}
	else
	{
		m_asciiFilename.Empty();
		strURL = pageStr;
		strURL = "http://workspacewhiz.com";
	}

	m_pBrowserApp->Navigate2(COleVariant(strURL), NULL, NULL, NULL, NULL);
}
示例#9
0
文件: HTTPSock.cpp 项目: tanuki/znc
bool CHTTPSock::PrintFile(const CString& sFileName, CString sContentType) {
	CString sFilePath = sFileName;

	if (!m_sDocRoot.empty()) {
		sFilePath.TrimLeft("/");

		sFilePath = CDir::CheckPathPrefix(m_sDocRoot, sFilePath, m_sDocRoot);

		if (sFilePath.empty()) {
			PrintErrorPage(403, "Forbidden", "You don't have permission to access that file on this server.");
			DEBUG("THIS FILE:     [" << sFilePath << "] does not live in ...");
			DEBUG("DOCUMENT ROOT: [" << m_sDocRoot << "]");
			return false;
		}
	}

	CFile File(sFilePath);

	if (!File.Open()) {
		PrintNotFound();
		return false;
	}

	if (sContentType.empty()) {
		if (sFileName.Right(5).Equals(".html") || sFileName.Right(4).Equals(".htm")) {
			sContentType = "text/html; charset=utf-8";
		} else if (sFileName.Right(4).Equals(".css")) {
			sContentType = "text/css; charset=utf-8";
		} else if (sFileName.Right(3).Equals(".js")) {
			sContentType = "application/x-javascript; charset=utf-8";
		} else if (sFileName.Right(4).Equals(".jpg")) {
			sContentType = "image/jpeg";
		} else if (sFileName.Right(4).Equals(".gif")) {
			sContentType = "image/gif";
		} else if (sFileName.Right(4).Equals(".ico")) {
			sContentType = "image/x-icon";
		} else if (sFileName.Right(4).Equals(".png")) {
			sContentType = "image/png";
		} else if (sFileName.Right(4).Equals(".bmp")) {
			sContentType = "image/bmp";
		} else {
			sContentType = "text/plain; charset=utf-8";
		}
	}

	const time_t iMTime = File.GetMTime();
	bool bNotModified = false;
	CString sETag;

	if (iMTime > 0 && !m_bHTTP10Client) {
		sETag = "-" + CString(iMTime); // lighttpd style ETag

		AddHeader("Last-Modified", GetDate(iMTime));
		AddHeader("ETag", "\"" + sETag + "\"");
		AddHeader("Cache-Control", "public");

		if (!m_sIfNoneMatch.empty()) {
			m_sIfNoneMatch.Trim("\\\"'");
			bNotModified = (m_sIfNoneMatch.Equals(sETag, true));
		}
	}

	if (bNotModified) {
		PrintHeader(0, sContentType, 304, "Not Modified");
	} else {
		off_t iSize = File.GetSize();

		// Don't try to send files over 16 MiB, because it might block
		// the whole process and use huge amounts of memory.
		if (iSize > 16 * 1024 * 1024) {
			DEBUG("- Abort: File is over 16 MiB big: " << iSize);
			PrintErrorPage(500, "Internal Server Error", "File too big");
			return true;
		}

#ifdef HAVE_ZLIB
		bool bGzip = m_bAcceptGzip && (sContentType.Left(5).Equals("text/") || sFileName.Right(3).Equals(".js"));

		if (bGzip) {
			DEBUG("- Sending gzip-compressed.");
			AddHeader("Content-Encoding", "gzip");
			PrintHeader(0, sContentType); // we do not know the compressed data's length
			WriteFileGzipped(File);
		} else
#endif
		{
			PrintHeader(iSize, sContentType);
			WriteFileUncompressed(File);
		}
	}

	DEBUG("- ETag: [" << sETag << "] / If-None-Match [" << m_sIfNoneMatch << "]");

	Close(Csock::CLT_AFTERWRITE);

	return true;
}
示例#10
0
CString CGetEnvPath::GetEnvVariable(LPCTSTR pszName)
{
    CString strResult;
	WCHAR wcsTemp[MAX_PATH] = {0}; 
    
    TCHAR szBuffer[MAX_PATH] = { 0 };
    TCHAR szLongPathBuffer[MAX_PATH] = { 0 };

    if ( CString("systemdrive").CompareNoCase(pszName) == 0 )
    {
        //UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);
        //strResult = GetDrive(_T(""));
        UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);

        if (uResult > 3 && szBuffer[1] == TEXT(':') && szBuffer[2] == TEXT('\\'))
        {
            szBuffer[2] = TEXT('\0');
            strResult = szBuffer;
            goto Exit0;         
        }
    }
    else if ( CString("program").CompareNoCase(pszName) == 0 )
    {
        //UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);
        //strResult = GetDrive(_T(""));
        UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);

        if (uResult > 3 && szBuffer[1] == TEXT(':') && szBuffer[2] == TEXT('\\'))
        {
            szBuffer[3] = TEXT('\0');
            strResult = szBuffer;
            strResult += L"program files";
            goto Exit0;         
        }
    }
    else if ( CString("boot").CompareNoCase(pszName) == 0 )
    {
        //UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);
        //strResult = GetDrive(_T(""));
        UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);

        if (uResult > 3 && szBuffer[1] == TEXT(':') && szBuffer[2] == TEXT('\\'))
        {
            szBuffer[3] = TEXT('\0');
            strResult = szBuffer;
            strResult += L"boot";
            goto Exit0;         
        }
    }
    else if ( CString("recovery").CompareNoCase(pszName) == 0 )
    {
        //UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);
        //strResult = GetDrive(_T(""));
        UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);

        if (uResult > 3 && szBuffer[1] == TEXT(':') && szBuffer[2] == TEXT('\\'))
        {
            szBuffer[3] = TEXT('\0');
            strResult = szBuffer;
            strResult += L"recovery";
            goto Exit0;         
        }
    }
    else if ( CString("systemroot").CompareNoCase(pszName) == 0 )
    {
       
        UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);

        if (uResult > 0)
        {
            strResult = szBuffer;
            goto Exit0;         
        }
    }
    else if(CString("windir").CompareNoCase(pszName) == 0)
    {
        UINT uResult = GetWindowsDirectory(szBuffer, MAX_PATH);

        if(szBuffer[wcslen(szBuffer)-1] == _T('\\'))
            szBuffer[wcslen(szBuffer)-1] = _T('\0');

        strResult = szBuffer;
        goto Exit0;
    }
    else if ( CString("systemrecycled").CompareNoCase(pszName) == 0 )
    {
        SYSTEM_VERSION     m_eSysVer;
        KAEGetSystemVersion(&m_eSysVer);
        CString StrSuffix;
        if(m_eSysVer == enumSystem_Win_7)
        {
            StrSuffix = _T("\\$RECYCLE.BIN");
        }
        else
            StrSuffix = _T("\\Recycled");
        strResult = GetDrive(StrSuffix);

        goto Exit0;
    }
	else if ( CString("minidump").CompareNoCase(pszName) == 0 )
	{
		DWORD len = sizeof(szLongPathBuffer);
		GetRegistryValue(HKEY_LOCAL_MACHINE,
			L"SYSTEM\\CurrentControlSet\\Control\\CrashControl",
			L"MinidumpDir",
			NULL,
			(LPBYTE)szLongPathBuffer,
			&len
			);
		if(wcslen(szLongPathBuffer) == 0)
			strResult = L"%minidump%";
		else
		{
			int nFirstPos  = 0; 
			int nSecondPos = 0;
			BOOL bFind = FALSE;
			bFind = FindEnvironmentPos(szLongPathBuffer, nFirstPos, nSecondPos);
			if(bFind)
			{
				CString strLeft       ;
				CString strRight      ;
				CString strEnvName    ;
				CString strEnvVariable;
				
				strResult = szLongPathBuffer;
				strLeft    = strResult.Left(nFirstPos);
				strRight   = strResult.Mid (nSecondPos + 1);
				strEnvName = strResult.Mid(nFirstPos + 1, nSecondPos - nFirstPos - 1);
				TCHAR szTempBuf[MAX_PATH];
				DWORD dwResult = GetEnvironmentVariable(strEnvName.GetBuffer(), szTempBuf, MAX_PATH);
				if (dwResult > 0)
					strEnvVariable = szTempBuf;

				strResult = CombinationPath(strLeft, strEnvVariable, strRight);

			}
			else
				strResult = szLongPathBuffer;

			goto Exit0;

		}
	}
	else if ( CString("memdump").CompareNoCase(pszName) == 0 )
	{
		DWORD len = sizeof(szLongPathBuffer);
		GetRegistryValue(HKEY_LOCAL_MACHINE,
			L"SYSTEM\\CurrentControlSet\\Control\\CrashControl",
			L"DumpFile",
			NULL,
			(LPBYTE)szLongPathBuffer,
			&len
			);
		if(wcslen(szLongPathBuffer) == 0)
			strResult = L"%memdump%";
		else
		{
			int nFirstPos  = 0; 
			int nSecondPos = 0;
			BOOL bFind = FALSE;
			bFind = FindEnvironmentPos(szLongPathBuffer, nFirstPos, nSecondPos);
			if(bFind)
			{
				CString strLeft       ;
				CString strRight      ;
				CString strEnvName    ;
				CString strEnvVariable;

				strResult = szLongPathBuffer;
				strLeft    = strResult.Left(nFirstPos);
				strRight   = strResult.Mid (nSecondPos + 1);
				strEnvName = strResult.Mid(nFirstPos + 1, nSecondPos - nFirstPos - 1);
				TCHAR szTempBuf[MAX_PATH];
				DWORD dwResult = GetEnvironmentVariable(strEnvName.GetBuffer(), szTempBuf, MAX_PATH);
				if (dwResult > 0)
					strEnvVariable = szTempBuf;

				strResult = CombinationPath(strLeft, strEnvVariable, L"");
				strResult += strRight;
			}
			else
				strResult = szLongPathBuffer;
			if (GetFileAttributes(strResult.GetBuffer()) != FILE_ATTRIBUTE_DIRECTORY)
			{
				WCHAR szTempBuffer[MAX_PATH] = {0};
				wcscpy_s(szTempBuffer, MAX_PATH - 1, strResult.GetBuffer());
				::PathRemoveFileSpec(szTempBuffer);
				strResult = szTempBuffer;
			}

			goto Exit0;

		}
	}
	else if (CString("archivefiles").CompareNoCase(pszName) == 0)
	{
		DWORD len = sizeof(szLongPathBuffer);
		GetRegistryValue(HKEY_LOCAL_MACHINE,
			L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VolumeCaches\\Windows Error Reporting Archive Files",
			L"Folder",
			NULL,
			(LPBYTE)szLongPathBuffer,
			&len
			);
		if (wcslen(szLongPathBuffer) == 0)
		{
			strResult = L"%archivefiles%";
		}
		else
		{
			int nFirstPos  = 0; 
			int nSecondPos = 0;
			BOOL bFind = FALSE;
			bFind = FindEnvironmentPos(szLongPathBuffer, nFirstPos, nSecondPos);
			if(bFind)
			{
				CString strLeft       ;
				CString strRight      ;
				CString strEnvName    ;
				CString strEnvVariable;

				strResult = szLongPathBuffer;
				strLeft    = strResult.Left(nFirstPos);
				strRight   = strResult.Mid (nSecondPos + 1);
				strEnvName = strResult.Mid(nFirstPos + 1, nSecondPos - nFirstPos - 1);
				TCHAR szTempBuf[MAX_PATH];
				DWORD dwResult = GetEnvironmentVariable(strEnvName.GetBuffer(), szTempBuf, MAX_PATH);
				if (dwResult > 0)
					strEnvVariable = szTempBuf;

				strResult = CombinationPath(strLeft, strEnvVariable, L"");
				strResult += strRight;
			}
			else
			{
				strResult = szLongPathBuffer;
			}
			goto Exit0;

		}
	}
	else if (CString("queuefiles").CompareNoCase(pszName) == 0)
	{
		DWORD len = sizeof(szLongPathBuffer);
		GetRegistryValue(HKEY_LOCAL_MACHINE,
			L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VolumeCaches\\Windows Error Reporting Queue Files",
			L"Folder",
			NULL,
			(LPBYTE)szLongPathBuffer,
			&len
			);
		if (wcslen(szLongPathBuffer) == 0)
		{
			strResult = L"%queuefiles%";
		}
		else
		{
			int nFirstPos  = 0; 
			int nSecondPos = 0;
			BOOL bFind = FALSE;
			bFind = FindEnvironmentPos(szLongPathBuffer, nFirstPos, nSecondPos);
			if(bFind)
			{
				CString strLeft       ;
				CString strRight      ;
				CString strEnvName    ;
				CString strEnvVariable;

				strResult = szLongPathBuffer;
				strLeft    = strResult.Left(nFirstPos);
				strRight   = strResult.Mid (nSecondPos + 1);
				strEnvName = strResult.Mid(nFirstPos + 1, nSecondPos - nFirstPos - 1);
				TCHAR szTempBuf[MAX_PATH];
				DWORD dwResult = GetEnvironmentVariable(strEnvName.GetBuffer(), szTempBuf, MAX_PATH);
				if (dwResult > 0)
					strEnvVariable = szTempBuf;

				strResult = CombinationPath(strLeft, strEnvVariable, L"");
				strResult += strRight;
			}
			else
			{
				strResult = szLongPathBuffer;
			}
			goto Exit0;

		}
	}
	else if (CString("systemarchivefiles").CompareNoCase(pszName) == 0)
	{
		DWORD len = sizeof(szLongPathBuffer);
		GetRegistryValue(HKEY_LOCAL_MACHINE,
			L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VolumeCaches\\Windows Error Reporting System Archive Files",
			L"Folder",
			NULL,
			(LPBYTE)szLongPathBuffer,
			&len
			);
		if (wcslen(szLongPathBuffer) == 0)
		{
			strResult = L"%systemarchivefiles%";
		}
		else
		{
			int nFirstPos  = 0; 
			int nSecondPos = 0;
			BOOL bFind = FALSE;
			bFind = FindEnvironmentPos(szLongPathBuffer, nFirstPos, nSecondPos);
			if(bFind)
			{
				CString strLeft       ;
				CString strRight      ;
				CString strEnvName    ;
				CString strEnvVariable;

				strResult = szLongPathBuffer;
				strLeft    = strResult.Left(nFirstPos);
				strRight   = strResult.Mid (nSecondPos + 1);
				strEnvName = strResult.Mid(nFirstPos + 1, nSecondPos - nFirstPos - 1);
				TCHAR szTempBuf[MAX_PATH];
				DWORD dwResult = GetEnvironmentVariable(strEnvName.GetBuffer(), szTempBuf, MAX_PATH);
				if (dwResult > 0)
					strEnvVariable = szTempBuf;

				strResult = CombinationPath(strLeft, strEnvVariable, L"");
				strResult += strRight;
			}
			else
			{
				strResult = szLongPathBuffer;
			}
			goto Exit0;

		}
	}
	else if (CString("systemqueuefiles").CompareNoCase(pszName) == 0)
	{
		DWORD len = sizeof(szLongPathBuffer);
		GetRegistryValue(HKEY_LOCAL_MACHINE,
			L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VolumeCaches\\Windows Error Reporting System Queue Files",
			L"Folder",
			NULL,
			(LPBYTE)szLongPathBuffer,
			&len
			);
		if (wcslen(szLongPathBuffer) == 0)
		{
			strResult = L"%systemqueuefiles%";
		}
		else
		{
			int nFirstPos  = 0; 
			int nSecondPos = 0;
			BOOL bFind = FALSE;
			bFind = FindEnvironmentPos(szLongPathBuffer, nFirstPos, nSecondPos);
			if(bFind)
			{
				CString strLeft       ;
				CString strRight      ;
				CString strEnvName    ;
				CString strEnvVariable;

				strResult = szLongPathBuffer;
				strLeft    = strResult.Left(nFirstPos);
				strRight   = strResult.Mid (nSecondPos + 1);
				strEnvName = strResult.Mid(nFirstPos + 1, nSecondPos - nFirstPos - 1);
				TCHAR szTempBuf[MAX_PATH];
				DWORD dwResult = GetEnvironmentVariable(strEnvName.GetBuffer(), szTempBuf, MAX_PATH);
				if (dwResult > 0)
					strEnvVariable = szTempBuf;

				strResult = CombinationPath(strLeft, strEnvVariable, L"");
				strResult += strRight;
			}
			else
			{
				strResult = szLongPathBuffer;
			}
			goto Exit0;

		}
	}
    else if ( CString("tudou").CompareNoCase(pszName) == 0 )
    {
         DWORD len = sizeof(szLongPathBuffer);
         GetRegistryValue(HKEY_LOCAL_MACHINE,
             L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\飞速土豆",
             L"UninstallString",
             NULL,
             (LPBYTE)szLongPathBuffer,
             &len
             );
         if(wcslen(szLongPathBuffer) == 0)
            strResult = L"%tudou%";
         else
         {
             ::PathRemoveFileSpec(szLongPathBuffer);
             ::PathAppend(szLongPathBuffer,L"tudouva.ini");
             IniEditor IniEdit;
             IniEdit.SetFile(szLongPathBuffer);
             std::wstring tmpPath = IniEdit.ReadString(L"public",L"savedirectory");
             if(tmpPath.length() <= 3)
                 strResult = L"%tudou%";
             else 
                 strResult = tmpPath.c_str();

         }

        goto Exit0;
    }else if ( CString("qvod").CompareNoCase(pszName) == 0 )
    {
        DWORD len = sizeof(szBuffer);
        GetRegistryValue(HKEY_LOCAL_MACHINE,
            L"SOFTWARE\\QvodPlayer\\Insert",
            L"Insertpath",
            NULL,
            (LPBYTE)szLongPathBuffer,
            &len
            );
        if(wcslen(szLongPathBuffer) == 0)
            strResult = L"%qvod%";
        else
        {
            //::PathRemoveFileSpec(szLongPathBuffer);
            ::PathAppend(szLongPathBuffer,L"QvodPlayer.xml");
            TiXmlDocument xmlDoc;
            const TiXmlElement *pXmlQvodPlayer = NULL;
            const TiXmlElement *pXmlGeneral = NULL;
            strResult = L"%qvod%";
            if (!xmlDoc.LoadFile(UnicodeToAnsi(szLongPathBuffer).c_str(), TIXML_ENCODING_UTF8))
                goto Exit0;
            pXmlQvodPlayer = xmlDoc.FirstChildElement("QvodPlayer");
            if (!pXmlQvodPlayer)
                goto Exit0;
            pXmlGeneral = pXmlQvodPlayer->FirstChildElement("General");
            if (pXmlGeneral)
            {
                const char* szTmp = pXmlGeneral->Attribute("Defaultsavepath");
                if(!szTmp)
                    strResult = L"%qvod%";
                else 
                    strResult = Utf8ToUnicode(szTmp).c_str();
            }

        }

        goto Exit0;
    }
    else if ( CString("xunleikankan").CompareNoCase(pszName) == 0 )
    {
        DWORD len = sizeof(szBuffer);
        GetRegistryValue(HKEY_LOCAL_MACHINE,
            L"SOFTWARE\\Thunder network\\Xmp",
            L"storepath",
            NULL,
            (LPBYTE)szBuffer,
            &len
            );
        if(wcslen(szBuffer) == 0)
            strResult = L"%xunleikankan%";
        else
        {
//            wcscat(szBuffer,L"\\VODCache");
            strResult =szBuffer;
        }

        goto Exit0;
    }
    else if ( CString("youku").CompareNoCase(pszName) == 0 )
    {
        DWORD len = sizeof(szBuffer);
        GetRegistryValue(HKEY_CURRENT_USER,
            L"SOFTWARE\\youku\\iKuAcc",
            L"CachePath",
            NULL,
            (LPBYTE)szBuffer,
            &len
            );
        if(wcslen(szBuffer) == 0)
            strResult = L"%youku%";
        else
        {
            strResult =szBuffer;
            if(strResult.Find(L"\\Desktop")!=-1)
                strResult = L"%youku%";
        }

        goto Exit0;
    }
    else if ( CString("ku6").CompareNoCase(pszName) == 0 )
    {
        DWORD len = sizeof(szLongPathBuffer);
        GetRegistryValue(HKEY_LOCAL_MACHINE,
            L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Ku6SpeedUpper",
            L"UninstallString",
            NULL,
            (LPBYTE)szLongPathBuffer,
            &len
            );
        if(wcslen(szLongPathBuffer) == 0)
        {
            CString StrSuffix = _T("\\kvideo_cache");;
            strResult = GetDrive(StrSuffix);
        }
        else
        {
            ::PathRemoveFileSpec(szLongPathBuffer);
            ::PathAppend(szLongPathBuffer,L"Ku6SpeedUpper.ini");
            IniEditor IniEdit;
            IniEdit.SetFile(szLongPathBuffer);
            std::wstring tmpPath = IniEdit.ReadString(L"Settings",L"BufPath");
            if(tmpPath.length() > 0)
                strResult = tmpPath.c_str();
            else
            {
                CString StrSuffix = _T("\\kvideo_cache");;
                strResult = GetDrive(StrSuffix);
                
            }
        }
        goto Exit0;
    }
    else if ( CString("ppstream").CompareNoCase(pszName) == 0 )
    {
        CString strTmp = GetFolderPath(L"CSIDL_APPDATA");
        strTmp += L"\\ppstream\\psnetwork.ini";
        if(!::PathFileExists(strTmp.GetBuffer()))
        {
            strTmp = L"";
            GetWindowsDirectory(szLongPathBuffer,MAX_PATH);
            strTmp = szLongPathBuffer;
            strTmp +=  L"\\psnetwork.ini";
        }
        IniEditor IniEdit;
        IniEdit.SetFile(strTmp.GetBuffer());
        std::wstring tmpPath = IniEdit.ReadString(L"vodnet",L"pgfpath");
        if(tmpPath.length()>0)
          ::PathRemoveFileSpec((LPWSTR)tmpPath.c_str());
        else
        {
            tmpPath = IniEdit.ReadString(L"vodnet",L"pgfpath1");
            if(tmpPath.length()>0)
                tmpPath.erase(tmpPath.length()-1);
        }
        strResult = tmpPath.c_str();
        goto Exit0;
    }
    else if ( CString("pptv").CompareNoCase(pszName) == 0 )
    {
        CString strTmp = GetFolderPath(L"CSIDL_COMMON_APPDATA");
        strTmp += L"\\PPLive\\Core\\config.ini";
        IniEditor IniEdit;
        IniEdit.SetFile(strTmp.GetBuffer());
        std::wstring tmpPath = IniEdit.ReadString(L"peer",L"cachepath");
        std::string utf8str = KUTF16_To_ANSI(tmpPath.c_str());
        tmpPath = Utf8ToUnicode(utf8str.c_str());
        if(tmpPath.length() == 0)
            strResult = L"%pptv%";
        else
            strResult = tmpPath.c_str();
        goto Exit0;
    }
    else if ( CString("fengxing").CompareNoCase(pszName) == 0 )
    {
        CString strTmp = GetFolderPath(L"CSIDL_PERSONAL");
        int a = strTmp.ReverseFind(L'\\');
        strTmp = strTmp.Mid(0,strTmp.ReverseFind(L'\\'));
        strTmp += L"\\funshion.ini";
        IniEditor IniEdit;
        IniEdit.SetFile(strTmp.GetBuffer());
        std::wstring tmpPath = IniEdit.ReadString(L"FILE_PATH",L"MEDIA_PATH");
        if(tmpPath.length() == 0)
            strResult = L"%fengxing%";
        else
            strResult = tmpPath.c_str();
        goto Exit0;
    }
    else if ( CString("qqlive").CompareNoCase(pszName) == 0 )
    {
       CString strTmp = GetFolderPath(L"CSIDL_APPDATA");
       strTmp += L"\\Tencent\\QQLive\\user.ini";
       IniEditor IniEdit;
       IniEdit.SetFile(strTmp.GetBuffer());
       std::wstring tmpPath = IniEdit.ReadString(L"Cache",L"Directory");
       if(tmpPath.length()>0)
       {
           tmpPath.erase(tmpPath.length()-1);
           strResult = tmpPath.c_str();
       }
       else strResult = L"%qqlive%";
       
       goto Exit0;
    }
	else if ( CString("firefox").CompareNoCase(pszName) == 0 )
	{
		WCHAR szPath[MAX_PATH] = {0};
		SHGetSpecialFolderPath(NULL, szPath, CSIDL_APPDATA, FALSE);
		std::wstring strPath;
		std::wstring strTemp;
		strPath = szPath;
		HANDLE hFile = INVALID_HANDLE_VALUE;
		if (strPath.rfind(L'\\') != strPath.size())
		{
			strPath += L"\\";
		}
		strPath += L"Mozilla\\Firefox\\profiles.ini";
		IniEditor inif;
		inif.SetFile(strPath.c_str());
		strTemp = inif.ReadString(L"Profile0", L"Path");
		if(strTemp.find(L"//") != -1)
		{
			strTemp.replace(strTemp.find(L"//"), 1, L"\\");
		}

		ZeroMemory(szPath, MAX_PATH);
		SHGetSpecialFolderPath(NULL, szPath, CSIDL_LOCAL_APPDATA, FALSE);
		strPath = szPath;
		if (strPath.rfind(L'\\') != strPath.size())
		{
			strPath += L"\\";
		}
		strPath += L"Mozilla\\Firefox\\";
		strPath += strTemp;
		strPath += L"\\cache";

		strResult = strPath.c_str();
		goto Exit0;
	}
    else if ( CString("sogou").CompareNoCase(pszName) == 0 )
    {
        std::wstring strPath;
        std::wstring strTemp;
        WCHAR szPath[MAX_PATH] = {0};
        SHGetSpecialFolderPath(NULL, szPath, CSIDL_APPDATA, FALSE);
        strTemp = szPath;
        if ( strTemp.rfind(L'\\') != strTemp.size())
        {
            strTemp += L"\\";
        }
        strTemp += L"SogouExplorer\\CommCfg.xml";

        strResult = L"%sogou%";
        TiXmlDocument xmlDoc;
        const TiXmlElement *pXmlSogou = NULL;
        const TiXmlElement *pXmlGeneral = NULL;
        if (!xmlDoc.LoadFile(UnicodeToAnsi(strTemp.c_str()).c_str(), TIXML_ENCODING_UTF8))
            goto Exit0;
        pXmlSogou = xmlDoc.FirstChildElement("main");
        if (!pXmlSogou)
            goto Exit0;
        pXmlGeneral = pXmlSogou->FirstChildElement("Item");
        if (pXmlGeneral && pXmlGeneral->Attribute("videoacccachepath"))
        {
            const char* szTmp = pXmlGeneral->Attribute("videoacccachepath");
            if(!szTmp)
                strResult = L"%sogou%";
            else 
                strResult = Utf8ToUnicode(szTmp).c_str();
        }
        // 过滤根目录
        if (strResult.GetLength() <= 3)
            strResult = L"%sogou%";
        goto Exit0;
    }
    else if (CString("usertemp").CompareNoCase(pszName) == 0)
    {
        TCHAR szBuffer[MAX_PATH] = { 0 };
        CString strPath;
        CString strEnvName = L"%TEMP%";
        CString strEnvPath;

        ExpandEnvironmentStrings(strEnvName, strEnvPath.GetBuffer(MAX_PATH), MAX_PATH);
        strEnvPath.ReleaseBuffer();
        
        StandardPath(strEnvPath);
    
        UINT uResult = GetSystemDirectory(szBuffer, MAX_PATH);

        if (uResult < 3 || szBuffer[1] != TEXT(':') || szBuffer[2] != TEXT('\\'))
        {
            goto Exit0;     
        }
        szBuffer[3] = TEXT('\0');
        strPath += szBuffer;
        memset(szBuffer, 0, sizeof(szBuffer));
        DWORD MaxSize = sizeof(szBuffer);
        GetUserName(szBuffer, &MaxSize);

        if (KGetWinVersion() >= 4) 
        {
            strPath += L"Users\\"; 
            strPath += szBuffer; 
            strPath += L"\\AppData\\Local\\Temp\\";
        }
        else
        {
            strPath += L"Documents and Settings\\"; 
            strPath += szBuffer; 
            strPath += L"\\Local Settings\\Temp\\";
        }
        //
        if (strPath.CompareNoCase(strEnvPath) == 0 
            || strPath.Find(strEnvPath) != -1
            || strEnvPath.Find(strPath) != -1)
        {
            strResult = L"";
        }
        else
        {
            strResult = strPath;
        }
        goto Exit0;
    }
    else if (CString("wintemp").CompareNoCase(pszName) == 0)
    {
        DWORD len = sizeof(szLongPathBuffer);
        GetRegistryValue(HKEY_LOCAL_MACHINE,
            L"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",
            L"TEMP",
            NULL,
            (LPBYTE)szLongPathBuffer,
            &len
            );
        if (wcslen(szLongPathBuffer) == 0)
        {
            strResult = L"";
        }
        else
        {
            if (CString("%SystemRoot%\\TEMP").CompareNoCase(szLongPathBuffer) == 0)
            {
                strResult = L"";
            }
            else
            {
                //解析环境变量
                CString strWinPath = szLongPathBuffer;

                int nFirstPos  = 0; 
                int nSecondPos = 0;
                BOOL bFind = FALSE;

                bFind = FindEnvironmentPos(strWinPath, nFirstPos, nSecondPos);
                
                if (bFind)
                {
                    CString strEnvName;
                    CString strEnvPath;
                    CString strLeft;
                    CString strRight;
                    strLeft = strWinPath.Left(nFirstPos);
                    strEnvName = strWinPath.Mid(nFirstPos, nSecondPos - nFirstPos + 1);
                    strRight = strWinPath.Mid(nSecondPos + 1);

                    ExpandEnvironmentStrings(strEnvName, strEnvPath.GetBuffer(MAX_PATH), MAX_PATH);
                    strEnvPath.ReleaseBuffer();
                    strResult += strLeft;
                    strResult += strEnvPath;
                    strResult += strRight;

                    UINT uResult = GetWindowsDirectory(szBuffer, MAX_PATH);

                    if(szBuffer[wcslen(szBuffer)-1] == _T('\\'))
                        szBuffer[wcslen(szBuffer)-1] = _T('\0');

                    CString strNormal = szBuffer;

                    strNormal += L"\\Temp\\";

                    StandardPath(strResult);

                    // 根目录跳过 和 子目录过滤,同时过滤 
                    if (strResult.GetLength() <= 3 
                        || strResult.Find(strNormal) != -1
                        || strNormal.Find(strResult) != -1)
                    {
                        strResult = L"";
                    }

                }
                else
                {
                    strResult = szLongPathBuffer;
                }
            }
        }
        goto Exit0;
    }
    else if (CString("office").CompareNoCase(pszName) == 0)
    {
        CString strDriverName;
        std::vector<CString> vecDrive;
        std::vector<CString>::iterator ite;

        TCHAR   szDriverName[500]; 

        DWORD nLength = GetLogicalDriveStrings(sizeof(szDriverName), szDriverName); 

        for (int i = 0; i < (int)nLength; i++) 
        { 
            if (szDriverName[i] != L'\0')
            {
                strDriverName += szDriverName[i]; 
            }
            else 
            { 
                strDriverName = strDriverName.Left(strDriverName.GetLength() - 1); 
                vecDrive.push_back(strDriverName); 
                strDriverName = ""; 
            } 
        }

        if (vecDrive.size() <= 0)
            goto Exit0;

        // 枚举盘符
        for (ite = vecDrive.begin(); ite != vecDrive.end(); ++ite)
        {
            CString strPath = (*ite) + _T("\\MSOCache");
            BOOL bRet = PathFileExists(strPath);

            if (bRet) 
            {
                strResult = strPath;
                break;
            }
        }
        goto Exit0;
    }
    else if (CString("qqmusic").CompareNoCase(pszName) == 0)
    {
        WCHAR szPath[MAX_PATH] = {0};
        std::wstring strPath;
        std::wstring strTemp;

        SHGetSpecialFolderPath(NULL, szPath, CSIDL_APPDATA, FALSE);
        strPath = szPath;

        if (strPath.rfind(L'\\') != strPath.size())
        {
            strPath += L"\\";
        }
        strPath += L"Tencent\\QQMusic\\CachePath.ini";
        IniEditor inif;
        inif.SetFile(strPath.c_str());
        strTemp = inif.ReadString(L"Cache", L"Path");
        if(strTemp.find(L"//") != -1)
        {
            strTemp.replace(strTemp.find(L"//"), 1, L"\\");
        }

        strResult += strTemp.c_str();

        if (strResult.IsEmpty())
            goto Exit0;

        if (strResult[strResult.GetLength() - 1] != _T('\\'))
            strResult += _T('\\');

        strResult += L"musiccache";

        goto Exit0;
    }
    else if (CString("kuwo").CompareNoCase(pszName) == 0)
    {
        WCHAR szPath[MAX_PATH] = {0};
        std::wstring strPath;
        std::wstring strTemp;

        SHGetSpecialFolderPath(NULL, szPath, CSIDL_COMMON_APPDATA, FALSE);
        strPath = szPath;

        if (strPath.rfind(L'\\') != strPath.size())
        {
            strPath += L"\\";
        }
        strPath += L"kuwo\\conf\\user\\config.ini";
        IniEditor inif;

        inif.SetFile(strPath.c_str());
        strTemp = inif.ReadString(L"Setting", L"temppath");
        if(strTemp.find(L"//") != -1)
        {
            strTemp.replace(strTemp.find(L"//"), 1, L"\\");
        }

        strResult = strTemp.c_str();

        goto Exit0;
    }
    else if (CString("ttplayer").CompareNoCase(pszName) == 0)
    {
        DWORD len = sizeof(szLongPathBuffer);
        TCHAR szDefault[MAX_PATH * 2] = { 0 };
        SHGetSpecialFolderPath(NULL, szDefault, CSIDL_APPDATA, FALSE);
        PathAppend(szDefault, L"TTPlayer\\cache");

        GetRegistryValue(HKEY_LOCAL_MACHINE,
            L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\TTPlayer",
            L"AppPath",
            NULL,
            (LPBYTE)szLongPathBuffer,
            &len
            );
        if(wcslen(szLongPathBuffer) == 0)
        {
            strResult = L"%ttplayer%";
        }
        else
        {
            ::PathRemoveFileSpec(szLongPathBuffer);
            ::PathAppend(szLongPathBuffer,L"TTPlayer.xml");
            TiXmlDocument xmlDoc;
            const TiXmlElement *pXmlTTPlayer = NULL;
            const TiXmlElement *pXmlGeneral = NULL;
            if (!xmlDoc.LoadFile(UnicodeToAnsi(szLongPathBuffer).c_str(), TIXML_ENCODING_UTF8))
                goto Exit0;

            pXmlTTPlayer = xmlDoc.FirstChildElement("ttplayer");
            if (!pXmlTTPlayer)
                goto Exit0;

            pXmlGeneral = pXmlTTPlayer->FirstChildElement("Network");
            if (pXmlGeneral)
            {
                const char* szTmp = pXmlGeneral->Attribute("CacheFolder");
                if(!szTmp)
                    strResult = L"%ttplayer%";
                else 
                    strResult = Utf8ToUnicode(szTmp).c_str();
            }
            
        }

        if (strResult.Find(szDefault) != -1 || strResult.GetLength() <= 3)
            strResult = L"%ttplayer%";

        goto Exit0;
    }
    else if (CString("ksafe").CompareNoCase(pszName) == 0)
    {
//         WCHAR szPath[MAX_PATH] = { 0 };
//         WCHAR szCmdline[MAX_PATH * 2] = { 0 };
//         ::GetModuleFileName(NULL, szPath, MAX_PATH);
// 
//         ::PathRemoveFileSpec(szPath);
//         std::wstring strIniPath = szPath;
//         std::wstring strTemp;
// 
//         strIniPath += L"\\cfg\\vulfix.ini";
// 
// //         IniEditor inif;
// // 
// //         inif.SetFile(strIniPath.c_str());
// //         strTemp = inif.ReadString(L"Main", L"downpath");
// //         if(strTemp.find(L"//") != -1)
// //         {
// //             strTemp.replace(strTemp.find(L"//"), 1, L"\\");
// //         }
// 
//         if (strTemp.length() == 0)
//         {
//             strResult = szPath;
//             strResult += L"\\hotfix";
//         }
//         else
//         {
//             strResult = strTemp.c_str();
//         }
        goto Exit0;
    }
    DWORD dwResult = GetEnvironmentVariable(pszName, szBuffer, MAX_PATH);
    if (dwResult > 0)
    {
        dwResult = 0;

        LPSTR pFileName = NULL;

        if (m_pfnGetLongPathName != NULL) 
            dwResult = m_pfnGetLongPathName(szBuffer, szLongPathBuffer, MAX_PATH);

        strResult = dwResult ? szLongPathBuffer : szBuffer;
    }
Exit0:
   
    return strResult;
}
示例#11
0
bool ExtractLatLon(CString str, double& dLat, double& dLon)
{
	CString strCoord1;
	CString strCoord2;

	int nPos = str.Find(",");

	if (nPos == -1) {
		return false;
	}

	strCoord1 = str.Left(nPos);
	strCoord2 = str.Mid(nPos+1);

	if (strCoord1.FindOneOf("nNsS") > 0) {

		// DM:  48�.834'N, 3�.787'W
		// DMS: 48�'50.0"N, 3�'47.2"W
		// Deg: 48.23056癗,  3.34645癢
		// Deg: 48.23056, -3.34645
		dLat = atof(strCoord1);
		if (strCoord1.Find("�") && strCoord1.Find("'")) {
			double dSeconds = 0.0;
			if (strCoord1.Find("\"")) {
				int nSecondPos = strCoord1.Find("'")+1;
				dSeconds = atof(strCoord1.Mid(nSecondPos));
			}
			int nMinutePos = strCoord1.Find("�")+1;
			double dMinutes = atof(strCoord1.Mid(nMinutePos));
			double dFraction = ((dMinutes * 60.0) + dSeconds) / 3600.0;
			dLat = dLat + dFraction;
		}
		if (strCoord1.FindOneOf("sS") > 0) {
			dLat = -dLat;
		}

	} else if (strCoord2.FindOneOf("nNsS") > 0) {
		dLat = atof(strCoord2);
		if (strCoord2.Find("�") && strCoord2.Find("'")) {
			double dSeconds = 0.0;
			if (strCoord2.Find("\"")) {
				int nSecondPos = strCoord2.Find("'")+1;
				dSeconds = atof(strCoord2.Mid(nSecondPos));
			}
			int nMinutePos = strCoord2.Find("�")+1;
			double dMinutes = atof(strCoord1.Mid(nMinutePos));
			double dFraction = ((dMinutes * 60.0) + dSeconds) / 3600.0;
			dLat = dLat + dFraction;
		}
		if (strCoord2.FindOneOf("sS") > 0) {
			dLat = -dLat;
		}
	} else {
		dLat = atof(strCoord1);
	}

	if (strCoord1.FindOneOf("eEwW") > 0) {
		dLon = atof(strCoord1);
		if (strCoord1.Find("�") && strCoord1.Find("'")) {
			double dSeconds = 0.0;
			if (strCoord1.Find("\"")) {
				int nSecondPos = strCoord1.Find("'")+1;
				dSeconds = atof(strCoord1.Mid(nSecondPos));
			}
			int nMinutePos = strCoord1.Find("�")+1;
			double dMinutes = atof(strCoord1.Mid(nMinutePos));
			double dFraction = ((dMinutes * 60.0) + dSeconds) / 3600.0;
			dLon = dLon + dFraction;
		}
		if (strCoord1.FindOneOf("wW") > 0) {
			dLon = -dLon;
		}
	} else if (strCoord2.FindOneOf("eEwW") > 0) {
		dLon = atof(strCoord2);
		if (strCoord2.Find("�") && strCoord2.Find("'")) {
			double dSeconds = 0.0;
			if (strCoord2.Find("\"")) {
				int nSecondPos = strCoord2.Find("'")+1;
				dSeconds = atof(strCoord2.Mid(nSecondPos));
			}
			int nMinutePos = strCoord2.Find("�")+1;
			double dMinutes = atof(strCoord2.Mid(nMinutePos));
			double dFraction = ((dMinutes * 60.0) + dSeconds) / 3600.0;
			dLon = dLon + dFraction;
		}
		if (strCoord2.FindOneOf("wW") > 0) {
			dLon = -dLon;
		}
	} else {
		dLon = atof(strCoord2);
	}

	return true;
}
示例#12
0
/////////////////////////////////////////////////////////////////////////////
// get which map they want
/////////////////////////////////////////////////////////////////////////////
void CNetworkServerDialog::OnMapButton() 
{
	int i;
	CString str;
	CMapDatabaseDialog dlg;

	if(IDOK == dlg.DoModal())
	{
		m_iMap = dlg.getMap();

		//update all of the players readiness
		for(i = 0; i < (int) GAME->m_players.size(); i++)
		{
			//skip self
			if(i == GAME->m_iIndex)
			{
				continue;
			}

			VIEW->clientReady(GAME->m_players[i].m_player.getID(), FALSE);
		}

		//set the team text
		if(TRUE == GAME->m_bTeam)
		{
			str = "This is a team game.\n\n";
		}
		//set the ladder text
		if(TRUE == GAME->m_bLadder)
		{
			//get rid of the extra newline
			str = str.Left(str.GetLength() - 1);

			//add the ladder text
			str += "This is a ladder game.\n\n";
		}

		//create info string (which loads the map)
		str += MAPS->getMapInfo(m_iMap);

		//set variant qualities
		VARIANTS->m_iStockRoads = MAP->m_iStockRoads;
		VARIANTS->m_iStockShips = MAP->m_iStockShips;
		VARIANTS->m_iStockCities = MAP->m_iStockCities;
		VARIANTS->m_iStockSettlements = MAP->m_iStockSettlements;
		VARIANTS->m_iAllowedCards = MAP->m_iAllowedCards;
		VARIANTS->m_iPoints = MAP->m_iPoints;

		//reset bit string
		VARIANTS->m_iVariants &= ~(VARIANT_ALTER_ROADS | VARIANT_ALTER_CITIES | VARIANT_ALTER_SETTLEMENTS | VARIANT_ALTER_ALLOWED_CARDS);

		//set settings
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_TRADE_ZERO, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_TRADE_ZERO;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_EQUAL_ODDS, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_EQUAL_ODDS;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_TRADE_BUILD, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_TRADE_AFTER_BUILD;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_NO_7, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_NO_7_FIRST_ROUND;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_SHOW_CARDS, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_SHOW_ALL_CARDS;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_ROUND_UP, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_ROUND_LOST_UP;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_HIDE_CHIPS, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_HIDE_CHIPS;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_SPECIAL, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_SPECIAL_BUILD;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_TOUR_START, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_TOURNAMENT_START;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_NO_TRADE, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_NO_TRADING;
		if(TRUE == GetPrivateProfileInt(INI_VARIANT, INI_VAR_LIMIT_TRADE, 0, INI_FILE)) VARIANTS->m_iVariants |= VARIANT_LIMIT_TRADING;

		//no 7's rounds
		VARIANTS->m_nNoSevens = GetPrivateProfileInt(INI_VARIANT, INI_VAR_NO_SEVENS, 1, INI_FILE);

		//trade offers limit
		VARIANTS->m_nTradeOffers = GetPrivateProfileInt(INI_VARIANT, INI_VAR_LIMIT_NUM, 3, INI_FILE);

		//set the allowed cards if the special build phase is turned on
		if(IS_VARIANT(VARIANT_SPECIAL_BUILD) && (9 == MAP->m_iAllowedCards))
		{
			//set it
			VARIANTS->m_iAllowedCards = 7;
			VARIANTS->m_iVariants |= VARIANT_ALTER_ALLOWED_CARDS;
		}

		//desert/volcanoes/jungles
		VARIANTS->m_iVariants |=  GetPrivateProfileInt(INI_VARIANT, INI_VAR_DESERTS, 0, INI_FILE);

		//must load sea chips as well if using jungles or deserts
		if(IS_VARIANT(VARIANT_USE_JUNGLE) || IS_VARIANT(VARIANT_USE_VOLCANO) || IS_VARIANT(VARIANT_USE_VOLCANO_GOLD))
		{
			MAP->m_iChipsUsed |= MAP_USES_SEA_CHIPS;
		}

		//add variant string
		str += VARIANTS->getVariantString();

		//tell all
		VIEW->setInfoString(str);

		//handle ladder restrictions
		handleLadder();

		//now we can choose variants
		m_VariantsButton.EnableWindow();

		//enable the connector window
		if(FALSE == CONNECTOR->getConnector())
		{
			m_ConnectorButton.EnableWindow();
		}
		//otherwise, update the data
		else
		{
			CONNECTOR->postServer(CONNECTOR_UPDATE);
		}
	}
}
示例#13
0
/////////////////////////////////////////////////////////////////////////////
// initial start settings
/////////////////////////////////////////////////////////////////////////////
void CNetworkServerDialog::startReload()
{
	int i;
	CString str;

	//set map
	m_iMap = GAME->m_uiMapID;

	//set the team text
	if(TRUE == GAME->m_bTeam)
	{
		str = "This is a team game.\n\n";
	}
	//set the ladder text
	if(TRUE == GAME->m_bLadder)
	{
		//get rid of the extra newline
		str = str.Left(str.GetLength() - 1);

		//add the ladder text
		str += "This is a ladder game.\n\n";
	}

	//create info string
	str += MAPS->getMapInfo(m_iMap);

	//add variant string
	str += VARIANTS->getVariantString();

	//set map text
	VIEW->setInfoString(str);

	//disable map button
	m_MapButton.EnableWindow(FALSE);

	//boot player button is disabled
	m_BootButton.EnableWindow(FALSE);

	//enable the connector button for restarts
	m_ConnectorButton.EnableWindow();

	//set button text
	m_OKButton.SetWindowText("Continue!");

	//add players to the control
	for(i = 0; i < (int) GAME->m_players.size(); i++)
	{
		m_PlayerList.addPlayer(&(GAME->m_players[i].m_player), GAME->m_players[i].m_iColor);

		//add AI's as joined already
		if(TRUE == GAME->m_players[i].m_player.getAI())
		{
			//tell the list
			m_PlayerList.updateJoin(GAME->m_players[i].m_player.getID(), TRUE);

			//set their flag as joined
			GAME->m_players[i].m_bJoined = TRUE;
		}
	}

	//set the server player as joined
	m_PlayerList.updateJoin(GAME->m_uiPlayerID, TRUE);

	//set their flag as joined
	GAME->m_players[GAME->m_iIndex].m_bJoined = TRUE;

	//set title text
	SetWindowText("Restart a network game");

	//with AI, see if we can continue yet
	checkForContinue();
}
示例#14
0
int CDbfFile::DBFSetColumn(CStringArray* psDBFColNameList)
{
    DBFHandle	hDBF;
	INT			i;
	INT			j;
	INT			k;
	INT			iStringLength;
	INT			iNumField;
	//CString		szPolyId;
	CString		szAttItem;
	CFileFind	DBFFile;
	
	if (_szDBFName.IsEmpty())
	{
		_szDBFName = _szFileName.Left(_szFileName.Find('.'));
		_szDBFName.Insert(_szFileName.GetLength(), ".dbf");
	}

	if ((DBFFile.FindFile(_szDBFName)) && (_eMode == KEEP))
	{
		printf("DBF file already exist");
		return 1;
	}
	else if ((DBFFile.FindFile(_szDBFName) && (_eMode == OVERWRITE)) ||
			(!DBFFile.FindFile(_szDBFName)))
	{
		hDBF = DBFCreate();
		if( hDBF == NULL )
		{
	  		printf( "DBFCreate(%s) failed.\n", _szDBFName );
			return 1;
		}
    
/*		if (_szFileName.Find('\\') > 0)
		{
			szPolyId = _szFileName.Right(_szFileName.GetLength()-_szFileName.ReverseFind('\\')-1);
			szPolyId = szPolyId.Left(8) + "_";
		}
		else
			szPolyId = _szFileName.Left(8) + "_";

		if( DBFAddField( hDBF, szPolyId, FTDouble, 11, 0) == -1 )
		{
			printf( "DBFAddField(%s,FTDouble,8,0) failed.\n", szPolyId);
			return 1;
		}
		if (szPolyId.GetLength() > 8)
			szPolyId = szPolyId + "i";
		else
			szPolyId = szPolyId + "id";
		if( DBFAddField( hDBF, szPolyId, FTDouble, 11, 0) == -1 )
		{
			printf( "DBFAddField(%s,FTDouble,8,0) failed.\n", szPolyId);
			return 1;
		} */
/* -------------------------------------------------------------------- */
/*	Loop over the field definitions adding new fields.	       	*/
/* -------------------------------------------------------------------- */
		iNumField = psDBFColNameList->GetSize();
		for( i = 0; i < iNumField; i++ )
		{
			szAttItem = psDBFColNameList->GetAt(i);
			if( strcmp(szAttItem.Left(2),"-s") == 0 )
			{
				szAttItem.Delete(0, 3);
				iStringLength = szAttItem.GetLength();
				k = szAttItem.Find(' ');
				ASSERT (k > 0);
				if( DBFAddField( hDBF, szAttItem.Left(k), FTString,
											atoi(szAttItem.Right(iStringLength-k-1)), 0 ) == -1 )
				{
					printf( "DBFAddField(%s,FTString,%d,0) failed.\n",
							psDBFColNameList->GetAt(i+1), atoi(psDBFColNameList->GetAt(i)) );
					return 1;
				}
			}
			else if( strcmp(szAttItem.Left(2),"-n") == 0 )
			{
				szAttItem.Delete(0, 3);
				iStringLength = szAttItem.GetLength();
				j = szAttItem.Find(' ');
				ASSERT (j > 0);
				k = szAttItem.ReverseFind(' ');
				ASSERT (k > 0);
				if( DBFAddField( hDBF, szAttItem.Left(j), FTDouble, atoi(szAttItem.Mid(j+1, k-j-1)), 
											atoi(szAttItem.Right(iStringLength-k-1)) ) == -1 )
				{
					printf( "DBFAddField(%s,FTDouble,%d,%d) failed.\n",
							psDBFColNameList->GetAt(i+1), atoi(psDBFColNameList->GetAt(i)), atoi(psDBFColNameList->GetAt(i+3)) );
					return 1;
				}
			}
			else
			{
				if(strcmp(szAttItem.Left(2),"-l") == 0)
				{

					szAttItem.Delete(0, 3);
					iStringLength = szAttItem.GetLength();
					k = szAttItem.Find(' ');
					ASSERT (k > 0);
					if( DBFAddField( hDBF, szAttItem.Left(k), FTLogical,
												atoi(szAttItem.Right(iStringLength-k-1)), 0 ) == -1 )
					{
						printf( "DBFAddField(%s,FTString,%d,0) failed.\n",
								psDBFColNameList->GetAt(i+1), atoi(psDBFColNameList->GetAt(i)) );
						return 1;
					}
				}
				else
				{
					printf( "Field definition incomplete, or unrecognised:%s\n", psDBFColNameList->GetAt(i) );
					exit( 3 );
				}
			}
		}
		DBFClose( hDBF );
	}

	return 0;

}
示例#15
0
int CChitemDlg::store_variable(CString varname, int storeflags, int opcode, int trigger, int block)
{
  CString tmp;
  loc_entry dummyloc;
  CPoint dummypoint;
  int cnt;
  int i;
  int sf;

  sf=storeflags&0xff;
  if((trigger&0xff)==SCANNING)
  {
    if(member_array(sf, scanned_types)==-1) return 0;
  }
  tmp=resolve_scriptelement(opcode, trigger, block);
  
  switch(sf)
  {
  case NO_CHECK:
    return 0;
  case CHECK_GAME:
    if(varname.GetLength()>32)
    {
      log("Bad string constant: '%s' (%s)",varname,tmp);
      return 1;
    }
    return 0;
  case CHECK_NUM:
    if(chkflg&NORESCHK) return 0;
    cnt=varname.GetLength();
    if(cnt&3)
    {
      log("Bad spellnumber list, crippled number: '%s' (%s)",varname,tmp);
      return 1; //spell numbers are 4 digits
    }
    if(cnt>32 || cnt<1)
    {
      log("Bad spellnumber list, length: '%s' (%s)",varname,tmp);
      return 1;
    }
    while(cnt--)
    {
      if(!isdigit(varname.GetAt(cnt)) )
      {
        log("Bad spellnumber list, not numeric: '%s' (%s)",varname,tmp);
        return 1;
      }
    }
    return 0;
  case IS_VAR:
    if(chkflg&NOVARCHK) return 0;
    if(!varname.GetLength()) return 0;
    log("Unexpected variable: '%s' (%s)",varname,tmp);
    return 1;
  case CHECK_SRC:
    if(chkflg&NORESCHK) return 0;
    if(strings.Lookup(varname, dummyloc) ) return 0;
    log("Missing strref source: '%s' (%s)", varname, tmp);
    return 1;
  case CHECK_MOVIE:
    if(chkflg&NORESCHK) return 0;
    if(movies.Lookup(varname, dummyloc) ) return 0;
    if(wbms.Lookup(varname, dummyloc) ) return 0;
    log("Missing movie: '%s' (%s)", varname, tmp);
    return 1;
  case CHECK_SOUND2:
    if(varname.IsEmpty()) return 0; // may be empty (iwd2 playsoundeffect)
  case CHECK_SOUND:
    if(chkflg&NORESCHK) return 0;
    if(sounds.Lookup(varname, dummyloc) ) return 0;
    log("Missing sound: '%s' (%s)", varname, tmp);
    return 1;
  case CHECK_DSOUND:
    if(chkflg&NORESCHK) return 0;
    i=varname.Find(':');
    if(i>8 || i<0)
    {
      log("Invalid sound resource: '%s' (%s)",varname, tmp);
      return 1;
    }
    varname2=varname.Left(i);
    varname=varname.Mid(i+1);
    if(varname.GetLength() && !sounds.Lookup(varname, dummyloc) )
    {
      log("Missing sound: '%s' (%s)", varname, tmp);
      return 1;
    }
    if(varname2.GetLength() && !sounds.Lookup(varname2, dummyloc) )
    {
      log("Missing sound: '%s' (%s)", varname2, tmp);
      return 1;
    }
    return 0;
  case CHECK_PAL:
    if(chkflg&NORESCHK) return 0;
    if(bitmaps.Lookup(varname, dummyloc) ) return 0;
    log("Missing palette: '%s' (%s)", varname, tmp);
    return 1;
  case CHECK_ITEM2:
    if(varname.IsEmpty()) return 0; // may be empty (useitemslot)
    //fallthrough
  case CHECK_ITEM:
    if(chkflg&NOITEMCH) return 0;
    if(items.Lookup(varname, dummyloc) ) return 0;
    log("Missing item: '%s' (%s)", varname, tmp);
    return 1;
  case CHECK_MOS2:
    if(varname.IsEmpty()) return 0; // may be empty (spellres actions are polymorph)
    //fallthrough
  case CHECK_MOS:
    return 0;
  case CHECK_2DA2:
    if(varname.IsEmpty()) return 0; // may be empty (incrementchapter)
    //fallthrough    
  case CHECK_2DA:
    if(darefs.Lookup(varname, dummyloc) ) return 0;
    log("Missing 2da: '%s' (%s)",varname, tmp);
    return 1;
  case CHECK_CRE:
    if(chkflg&NOCRECHK) return 0;
    if(creatures.Lookup(varname, dummyloc) ) return 0;
    log("Missing creature: '%s' (%s)",varname, tmp);
    return 1;
  case CHECK_STORE:
    if(chkflg&NOSTORCH) return 0;
    if(stores.Lookup(varname, dummyloc) ) return 0;
    log("Missing store: '%s' (%s)",varname, tmp);
    return 1;
  case CHECK_VVC2:
    if(varname.IsEmpty()) return 0; // may be empty (vvc for creature summoning)
    //fallthrough
  case CHECK_VVC:
    if(chkflg&NORESCHK) return 0;
    if(vvcs.Lookup(varname, dummyloc) ) return 0;
    if(icons.Lookup(varname, dummyloc) ) return 0;
    log("Missing visual effect (vvc or bam): '%s' (%s)",varname, tmp);
    return 1;
  case CHECK_SPL2:
    if(varname.IsEmpty()) return 0; // may be empty (spellres actions are polymorph)
    //fallthrough
  case CHECK_SPL:
    if(chkflg&NOSPLCHK) return 0;
    if(spells.Lookup(varname, dummyloc) ) return 0;
    log("Missing spell: '%s' (%s)",varname, tmp);
    return 1;
  case CHECK_BCS2:
    if(varname.IsEmpty()) return 0; // may be empty
    if(varname=="NONE") return 0;   // apparently used this way
    //fallthrough
  case CHECK_BCS:
    if(chkflg&NOSCRIPT) return 0;
    if(scripts.Lookup(varname, dummyloc)) return 0;
    log("Missing script: '%s' (%s)", varname, tmp);
    return 1;
  case CHECK_DLG2:
    if(varname.IsEmpty()) return 0; // may be empty
    if(varname=="NONE") return 0;
    //fallthrough
  case CHECK_DLG:
    if(chkflg&NODLGCHK) return 0;
    if(dialogs.Lookup(varname, dummyloc)) return 0;
    log("Missing dialog: '%s' (%s)", varname, tmp);
    return 1;
  case CHECK_DEAD2:
    if(storeflags&INANIMATE) return 0;
    //fallthrough
  case ADD_DEAD2:
    if(varname.IsEmpty()) return 0; // may be empty
    //fallthrough
  case ADD_DEAD:
    //check for death variables
    if(chkflg&NODVARCH) return 0;
    if(pst_compatible_var())
    {
      varname="KAPUTZ"+varname+"_dead";
    }
    else
    {
//      varname="GLOBALsprite_is_dead"+varname;
      varname="GLOBALSPRITE_IS_DEAD"+varname;
    }
    break;
  case CHECK_SCOPE:    
    if(areas.Lookup(varname, dummyloc))
    {
      varname2=varname; //storing area
      return 0;
    }
    if(varname!="LOCALS" && varname!="GLOBAL" && varname !="MYAREA")
    {
      log("Invalid scope: %s (%s)",varname, tmp);
      return 1;
    }
    varname2=varname;
    return 0;
  case CHECK_AREA2:
    if(varname.IsEmpty()) return 0; // may be empty (spellres actions are polymorph)
  case CHECK_AREA:
    if(areas.Lookup(varname, dummyloc))
    {
      varname2=varname; //storing area
      return 0;
    }
    varname2.Empty();
    log("Missing area: '%s' (%s)", varname, tmp);
    return 1;
  case VALID_TAG:
    /// no idea yet
    return 0;
  case ENTRY_POINT:
    if(varname2.IsEmpty())
    {
      log("Missing area! (%s)", tmp);
      return 1;
    }
    if(!entries.Lookup(varname2+"/"+varname, dummypoint))
    {
      log("Invalid entrance '%s' for area '%s' (%s)",varname,varname2,tmp);
      return 1;
    }
    /*
    if(CheckDestination(varname2,varname) )
    {
      log("Invalid entrance '%s' for area '%s' (%s)",varname,varname2,tmp);
      return 1;
    }
    */
    return 0;
  case CHECK_XPLIST:
    varname.MakeUpper();
    if(xplist.Find(varname) ) return 0;
    log("Missing xplist.2da entry: '%s' (%s)", varname, tmp);
    return 1;
  case ADD_GLOBAL:
    varname="GLOBAL"+varname;
    break;
  case ADD_LOCAL:
    varname="LOCALS"+varname;
    break;
  case ADD_VAR:
    break;
  case ADD_VAR2: //merge variables 
    if((varname.GetLength()>6) && (varname[6]==':'))
    {
      varname.Delete(6); //removing .
      break; //break for variable
    }
    break;
  case ADD_VAR3:
    varname=varname2+varname;
    break;
  default:
    log("Internal error for %s (cmd:%d)",tmp, storeflags);
    return -1;
  }
  if(!varname.GetLength() )
  {
    log("Empty variable name: (%s)",tmp);
    return 1;
  }
  if(varname.GetLength()<7)
  {
    log("Crippled variable name: %s (%s)", varname, tmp);
    return 1;
  }
  if(varname.FindOneOf("()")!=-1 )
  {
    log("Crippled variable name: %s (%s)", varname, tmp);
    return 1;
  }
  varname.MakeUpper();
  /*
  for(i=0;i<6;i++)
  {
    varname.SetAt(i,(char) toupper(varname[i]) );
  }
  */
  if(varname.Left(6)!="GLOBAL" && !pst_compatible_var() )
  {
    for(i=0;i<6;i++)
    {
      varname.SetAt(i,"LOCALS"[i]);
    }
  }

  switch(trigger&0xff)
  {
  case SCANNING:
    if(!variables[varname])
    {
      log("New variable: %s",varname);
    }
    variables[varname]++;
    break;
  case CHECKING:
    if(chkflg&NOVARCHK) return 0;
    cnt=0;
    variables.Lookup(varname,cnt);
    switch( cnt )    
    {
    case 0:
      log("Incorrect variable: %s (%s)",varname, tmp);
      return 1;
    case 1:
      log("Suspicious variable: %s (%s)",varname, tmp);
      return 0;
    }
  }
  return 0;
}
void CSettingsSaver::ImportOldSettings(CPartFile* file)
{
	SettingsList daten;
	CString datafilepath;
	datafilepath.Format(_T("%s\\%s\\%s.sivka"), file->GetTempPath(), _T("Extra Lists"), file->GetPartMetFileName());

	CString strLine;
	CStdioFile f;
	if (!f.Open(datafilepath, CFile::modeReadWrite | CFile::typeText))
		return;
	while(f.ReadString(strLine))
	{
		if (strLine.GetAt(0) == _T('#'))
			continue;
		int pos = strLine.Find(_T('\n'));
		if (pos == -1)
			continue;
		CString strData = strLine.Left(pos);
		CSettingsData* newdata = new CSettingsData(_tstol(strData));
		daten.AddTail(newdata);
	}
	f.Close();

	POSITION pos = daten.GetHeadPosition();
	if(!pos)
		return;

	if( ((CSettingsData*)daten.GetAt(pos))->dwData == 0 || ((CSettingsData*)daten.GetAt(pos))->dwData == 1)
	{
		file->SetEnableAutoDropNNS((((CSettingsData*)daten.GetAt(pos))->dwData)!=0);
	}
	else
		file->SetEnableAutoDropNNS(thePrefs.GetEnableAutoDropNNSDefault());

	daten.GetNext(pos);
	if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 0 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 60000)
		file->SetAutoNNS_Timer(((CSettingsData*)daten.GetAt(pos))->dwData);
	else
		file->SetAutoNNS_Timer(thePrefs.GetAutoNNS_TimerDefault());

	daten.GetNext(pos);
	if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 50 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 100)
		file->SetMaxRemoveNNSLimit((uint16)((CSettingsData*)daten.GetAt(pos))->dwData);
	else
		file->SetMaxRemoveNNSLimit(thePrefs.GetMaxRemoveNNSLimitDefault());

	daten.GetNext(pos);
	if( ((CSettingsData*)daten.GetAt(pos))->dwData == 0 || ((CSettingsData*)daten.GetAt(pos))->dwData == 1)
	{
		file->SetEnableAutoDropFQS((((CSettingsData*)daten.GetAt(pos))->dwData)!=0);
	}
	else
		file->SetEnableAutoDropFQS(thePrefs.GetEnableAutoDropFQSDefault());

	daten.GetNext(pos);
	if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 0 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 60000)
		file->SetAutoFQS_Timer(((CSettingsData*)daten.GetAt(pos))->dwData);
	else
		file->SetAutoFQS_Timer(thePrefs.GetAutoFQS_TimerDefault());

	daten.GetNext(pos);
	if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 50 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 100)
		file->SetMaxRemoveFQSLimit((uint16)((CSettingsData*)daten.GetAt(pos))->dwData);
	else
		file->SetMaxRemoveFQSLimit(thePrefs.GetMaxRemoveFQSLimitDefault());

	daten.GetNext(pos);
	if( ((CSettingsData*)daten.GetAt(pos))->dwData == 0 || ((CSettingsData*)daten.GetAt(pos))->dwData == 1)
	{
		file->SetEnableAutoDropQRS((((CSettingsData*)daten.GetAt(pos))->dwData)!=0);
	}
	else
		file->SetEnableAutoDropQRS(thePrefs.GetEnableAutoDropQRSDefault());

	daten.GetNext(pos);
	if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 0 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 60000)
		file->SetAutoHQRS_Timer(((CSettingsData*)daten.GetAt(pos))->dwData);
	else
		file->SetAutoHQRS_Timer(thePrefs.GetAutoHQRS_TimerDefault());

	daten.GetNext(pos);
	if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 1000 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 10000)
		file->SetMaxRemoveQRS((uint16)((CSettingsData*)daten.GetAt(pos))->dwData);
	else
		file->SetMaxRemoveQRS(thePrefs.GetMaxRemoveQRSDefault());

	daten.GetNext(pos);
	if( ((CSettingsData*)daten.GetAt(pos))->dwData >= 50 && ((CSettingsData*)daten.GetAt(pos))->dwData <= 100)
		file->SetMaxRemoveQRSLimit((uint16)((CSettingsData*)daten.GetAt(pos))->dwData);
	else
		file->SetMaxRemoveQRSLimit(thePrefs.GetMaxRemoveQRSLimitDefault());

	if(daten.GetCount() > 10) // emulate StulleMule <= v2.2 files
	{
		// ==> Global Source Limit (customize for files) - Stulle
		daten.GetNext(pos);
		if( ((CSettingsData*)daten.GetAt(pos))->dwData == 0 || ((CSettingsData*)daten.GetAt(pos))->dwData == 1)
		{
			file->SetGlobalHL((((CSettingsData*)daten.GetAt(pos))->dwData)!=0);
		}
		else
			file->SetGlobalHL(thePrefs.GetGlobalHlDefault());
		// <== Global Source Limit (customize for files) - Stulle
	}
	else
		file->SetGlobalHL(thePrefs.GetGlobalHlDefault());

	while (!daten.IsEmpty()) 
		delete daten.RemoveHead();

	if (_tremove(datafilepath)) if (errno != ENOENT)
		AddLogLine(true, _T("Failed to delete %s, you will need to do this manually"), datafilepath);
}
示例#17
0
void GetSubFileNames(CString fn, CAtlArray<CString>& paths, CAtlArray<SubFile>& ret)
{
	ret.RemoveAll();

	int extlistnum = _countof(ext);
	int extsubnum = _countof(ext[0]);

	fn.Replace('\\', '/');

	bool fWeb = false;
	{
		//		int i = fn.Find(_T("://"));
		int i = fn.Find(_T("http://"));
		if (i > 0) {
			fn = _T("http") + fn.Mid(i);
			fWeb = true;
		}
	}

	int	l = fn.GetLength(), l2 = l;
	l2 = fn.ReverseFind('.');
	l = fn.ReverseFind('/') + 1;
	if (l2 < l) {
		l2 = l;
	}

	CString orgpath = fn.Left(l);
	CString title = fn.Mid(l, l2-l);
	CString filename = title + _T(".nooneexpectsthespanishinquisition");

	if (!fWeb) {
		// struct _tfinddata_t file, file2;
		// long hFile, hFile2 = 0;

		WIN32_FIND_DATA wfd, wfd2;
		HANDLE hFile, hFile2;

		for (size_t k = 0; k < paths.GetCount(); k++) {
			CString path = paths[k];
			path.Replace('\\', '/');

			l = path.GetLength();
			if (l > 0 && path[l-1] != '/') {
				path += '/';
			}

			if (path.Find(':') == -1 && path.Find(_T("\\\\")) != 0) {
				path = orgpath + path;
			}

			path.Replace(_T("/./"), _T("/"));
			path.Replace('/', '\\');

			// CAtlList<CString> sl;

			bool fEmpty = true;

			if ((hFile = FindFirstFile(path + title + _T("*"), &wfd)) != INVALID_HANDLE_VALUE) {
				do {
					if (filename.CompareNoCase(wfd.cFileName) != 0) {
						fEmpty = false;
						// sl.AddTail(path + file.name);
					}
				} while (FindNextFile(hFile, &wfd));

				FindClose(hFile);
			}

			// TODO: use 'sl' in the next step to find files (already a nice speedup as it is now...)
			if (fEmpty) {
				continue;
			}

			for (ptrdiff_t j = 0; j < extlistnum; j++) {
				for (ptrdiff_t i = 0; i < extsubnum; i++) {
					if ((hFile = FindFirstFile(path + title + ext[j][i], &wfd)) != INVALID_HANDLE_VALUE) {
						do {
							CString fn = path + wfd.cFileName;

							hFile2 = INVALID_HANDLE_VALUE;

							if (j == 0 || (hFile2 = FindFirstFile(fn.Left(fn.ReverseFind('.')) + _T(".avi"), &wfd2)) == INVALID_HANDLE_VALUE) {
								SubFile f;
								f.fn = fn;
								ret.Add(f);
							}

							if (hFile2 != INVALID_HANDLE_VALUE) {
								FindClose(hFile2);
							}
						} while (FindNextFile(hFile, &wfd));

						FindClose(hFile);
					}
				}
			}
		}
	} else if (l > 7) {
		CWebTextFile wtf; // :)
		if (wtf.Open(orgpath + title + WEBSUBEXT)) {
			CString fn;
			while (wtf.ReadString(fn) && fn.Find(_T("://")) >= 0) {
				SubFile f;
				f.fn = fn;
				ret.Add(f);
			}
		}
	}

	// sort files, this way the user can define the order (movie.00.English.srt, movie.01.Hungarian.srt, etc)

	qsort(ret.GetData(), ret.GetCount(), sizeof(SubFile), SubFileCompare);
}
示例#18
0
// This function returns the full path of the next selected file.
//
// Parameters:
//		[IN]	pos
//				A reference to a POSITION value returned by a previous GetNextPathName 
//				or GetStartPosition function call. 
//				NULL if the end of the list has been reached.
//
// Return value:
//			A CString object containing the full path of the file.
//
// Note:	this function has been copied exactly from the MFC
//			implementation of the CFileDialog class.
//
CString CFileDialogST::GetNextPathName(POSITION& pos) const
{
	BOOL bExplorer = m_ofn.Flags & OFN_EXPLORER;
	TCHAR chDelimiter;
	if (bExplorer)
		chDelimiter = '\0';
	else
		chDelimiter = ' ';

	LPTSTR lpsz = (LPTSTR)pos;
	if (lpsz == m_ofn.lpstrFile) // first time
	{
		if ((m_ofn.Flags & OFN_ALLOWMULTISELECT) == 0)
		{
			pos = NULL;
			return m_ofn.lpstrFile;
		}

		// find char pos after first Delimiter
		while(*lpsz != chDelimiter && *lpsz != '\0')
			lpsz = _tcsinc(lpsz);
		lpsz = _tcsinc(lpsz);

		// if single selection then return only selection
		if (*lpsz == 0)
		{
			pos = NULL;
			return m_ofn.lpstrFile;
		}
	}

	CString strPath = m_ofn.lpstrFile;
	if (!bExplorer)
	{
		LPTSTR lpszPath = m_ofn.lpstrFile;
		while(*lpszPath != chDelimiter)
			lpszPath = _tcsinc(lpszPath);
		strPath = strPath.Left((int)(lpszPath - m_ofn.lpstrFile));
	}

	LPTSTR lpszFileName = lpsz;
	CString strFileName = lpsz;

	// find char pos at next Delimiter
	while(*lpsz != chDelimiter && *lpsz != '\0')
		lpsz = _tcsinc(lpsz);

	if (!bExplorer && *lpsz == '\0')
		pos = NULL;
	else
	{
		if (!bExplorer)
			strFileName = strFileName.Left((int)(lpsz - lpszFileName));

		lpsz = _tcsinc(lpsz);
		if (*lpsz == '\0') // if double terminated then done
			pos = NULL;
		else
			pos = (POSITION)lpsz;
	}

	// only add '\\' if it is needed
	if (!strPath.IsEmpty())
	{
		// check for last back-slash or forward slash (handles DBCS)
		LPCTSTR lpsz = _tcsrchr(strPath, '\\');
		if (lpsz == NULL)
			lpsz = _tcsrchr(strPath, '/');
		// if it is also the last character, then we don't need an extra
		if (lpsz != NULL &&
			(lpsz - (LPCTSTR)strPath) == strPath.GetLength()-1)
		{
			ASSERT(*lpsz == '\\' || *lpsz == '/');
			return strPath + strFileName;
		}
	}
	return strPath + '\\' + strFileName;
} // End of GetNextPathName
示例#19
0
CMsgBox::CMsgBox(CString text, UINT nType /*=1*/, int cancelButton /*=0*/, 
				 CWnd* pParent /*=NULL*/, BOOL *lpBdontShow /*= NULL*/, BOOL bShowVscroll /*= FALSE*/)
	: CDialog(CMsgBox::IDD, pParent), m_cancelButton(cancelButton)
{

	//{{AFX_DATA_INIT(CMsgBox)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	m_InitRect = CRect(0,0,0,0);

	// the string provided should be delimited by tabs, with button labels
    // first, followed by the prompt string.  First, extract the button labels
    m_numButtons = 0;
	m_DontShowAgain = 0;
	m_ShowVscroll = bShowVscroll;
	m_lpDontShowAgain = lpBdontShow;
    for(int nextTab = text.Find(_T('\t')); nextTab != -1; nextTab = text.Find(_T('\t')))
    {
        switch(m_numButtons)
        {
        case 0:
            m_Button1 = text.Left(nextTab);
            m_numButtons++;
            break;
        case 1:
            m_Button2 = text.Left(nextTab);
            m_numButtons++;
            break;
        case 2:
            m_Button3 = text.Left(nextTab);
            m_numButtons++;
            break;
        default:
            ASSERT(0);
            // too many buttons specified - ignore them
        }
        text = text.Mid(nextTab+1);
    }

    // what's left in string 'labels' now is just the prompt string

	if (text.GetLength() < 150)
		 text = "\n" + text;
    m_Text = text;

    switch(nType & MB_DEFMASK)
    {
    case MB_DEFBUTTON2:
        m_DefButton = IDC_BUTTON2;
        break;
    case MB_DEFBUTTON3:
		m_DefButton = IDC_BUTTON3;
        break;
    default:
		m_DefButton = m_numButtons == 1 ? IDC_BUTTON2 : IDC_BUTTON1;
    }

    int nIDCaption = 0;
    switch(nType & MB_ICONMASK)
    {
    case MB_ICONHAND:
        m_Icon = IDI_HAND;
        nIDCaption = IDS_ERROR;
        break;
    case MB_ICONQUESTION:
        m_Icon = IDI_QUESTION;
        break;
    case MB_ICONEXCLAMATION:
        m_Icon = IDI_EXCLAMATION;
        nIDCaption = IDS_WARNING;
        break;
    case MB_ICONASTERISK:
        m_Icon = IDI_ASTERISK;
        break;
    default:
        m_Icon = 0;
    }

    m_Caption = TheApp()->m_pszAppName;
    if(nIDCaption)
        m_Caption += _T(" ") + LoadStringResource(nIDCaption);
}
示例#20
0
bool CSubtitleDlDlg::Parse()
{
    // Parse raw list
    ISDb::movie m;
    ISDb::subtitle sub;

    CAtlList<CStringA> sl;
    Explode(m_pTA->raw_list, sl, '\n');
    CString str;

    POSITION pos = sl.GetHeadPosition();
    while (pos) {
        str = sl.GetNext(pos);

        CStringA param = str.Left(max(0, str.Find('=')));
        CStringA value = str.Mid(str.Find('=') + 1);

        if (param == "ticket") {
            m_pTA->ticket = value;
        } else if (param == "movie") {
            m.reset();
            Explode(value.Trim(" |"), m.titles, '|');
        } else if (param == "subtitle") {
            sub.reset();
            sub.id = atoi(value);
        } else if (param == "name") {
            sub.name = value;
        } else if (param == "discs") {
            sub.discs = atoi(value);
        } else if (param == "disc_no") {
            sub.disc_no = atoi(value);
        } else if (param == "format") {
            sub.format = value;
        } else if (param == "iso639_2") {
            sub.iso639_2 = value;
        } else if (param == "language") {
            sub.language = value;
        } else if (param == "nick") {
            sub.nick = value;
        } else if (param == "email") {
            sub.email = value;
        } else if (param.IsEmpty() && value == "endsubtitle") {
            m.subs.AddTail(sub);
        } else if (param.IsEmpty() && value == "endmovie") {
            m_pTA->raw_movies.AddTail(m);
        } else if (param.IsEmpty() && value == "end") {
            break;
        }
    }

    // Parse movies
    pos = m_pTA->raw_movies.GetHeadPosition();
    while (pos) {
        ISDb::movie& raw_movie = m_pTA->raw_movies.GetNext(pos);
        isdb_movie_parsed p;

        CStringA titlesA = Implode(raw_movie.titles, '|');
        titlesA.Replace("|", ", ");
        p.titles = UTF8To16(titlesA);
        p.checked = false;

        POSITION pos2 = raw_movie.subs.GetHeadPosition();
        while (pos2) {
            const ISDb::subtitle& s = raw_movie.subs.GetNext(pos2);
            p.name = UTF8To16(s.name);
            p.language = s.language;
            p.format = s.format;
            p.disc.Format(_T("%d/%d"), s.disc_no, s.discs);
            p.ptr = reinterpret_cast<DWORD_PTR>(&s);

            m_parsed_movies.Add(p);
        }
    }

    bool ret = true;
    if (m_parsed_movies.IsEmpty()) {
        ret = false;
    }

    return ret;
}
示例#21
0
void CUDSMainWnd::PrepareDiagnosticMessage(CString omByteStr,mPSTXSELMSGDATA psTxCanMsgUds, unsigned char abByteArr[], UINT ByteArrLen)
{
    memset(abByteArr, 0, ByteArrLen);               // Initialize the array to zero
    omByteStr.Replace(" ","");
    int i_counter =0;
    UINT LengthStr = omByteStr.GetLength();
    UINT Result;
    if ( LengthStr%2 != 0)
    {
        CString LastString = "0" + omByteStr.Right(1);
        omByteStr= omByteStr.Left(omByteStr.GetLength() - 1);
        omByteStr = omByteStr+ LastString;

    }
    Result = LengthStr / 2 + LengthStr % 2;
    TotalLength = Result;
    m_omSendButton.EnableWindow(FALSE);  //I have to disable the sendButton everytime that I press SEND
    // If it's a long request I need it
    // If it's a long response I've to restart it  and receive all the bytes
    // If it's a simple response: the response could take more time or it could be a 0x78 resp

    m_nTimer = SetTimer(ID_TIMER_SEND_BUTTON,P2_Time , NULL);               // Time to wait to enable the send button again

    switch (fInterface)
    {
        case INTERFACE_NORMAL_11:
        {
            psTxCanMsgUds->m_psTxMsg->m_ucEXTENDED= FALSE;
            ByteArrLen = ByteArrLen-1;
            if (Result>7)                            // Long Request
            {
                int f =SendFirstFrame(omByteStr,abByteArr,psTxCanMsgUds,fInterface );

            }
            else                                     // Short request
            {
                i_counter = (int) Result;
                abByteArr[0] = Result;
                Result++;                            // Result must be increased to make the size array bigger
                CString omTempByte;
                while (omByteStr.GetLength())
                {
                    omTempByte = omByteStr.Right(NO_OF_CHAR_IN_BYTE);
                    abByteArr[i_counter--] = (BYTE)_tcstol(omTempByte, L'\0', 16);
                    omByteStr = omByteStr.Left(omByteStr.GetLength() - NO_OF_CHAR_IN_BYTE);
                }

                if(fMsgSize)
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;
                }
                else
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = Result;
                }
                SendSimpleDiagnosticMessage();
            }
        }
        break;
        case INTERFACE_EXTENDED_11:
        {
            psTxCanMsgUds->m_psTxMsg->m_ucEXTENDED= FALSE;
            ByteArrLen = ByteArrLen-2;
            abByteArr[0] = TargetAddress;
            if (Result>6)                                                           // Long Request - The limit of a simple request for extended is 6 because the byte that contains the TA.
            {
                m_omSendButton.EnableWindow(FALSE);
                m_nTimer = SetTimer(ID_TIMER_SEND_BUTTON, P2_Time , NULL);          // Start Timer to wait to enable by default the send button again

                int f =SendFirstFrame(omByteStr,abByteArr,psTxCanMsgUds,fInterface);

            }
            else                                             // Short request
            {
                i_counter = Result+1;
                abByteArr[1] = Result;
                Result = Result+2;
                CString omTempByte;
                while (omByteStr.GetLength())               // Take all the bytes that will be parte of the simple message
                {
                    omTempByte = omByteStr.Right(NO_OF_CHAR_IN_BYTE);
                    abByteArr[i_counter--] = (BYTE)_tcstol(omTempByte, L'\0', 16);
                    omByteStr = omByteStr.Left(omByteStr.GetLength() - NO_OF_CHAR_IN_BYTE);
                }
                if(fMsgSize)
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;
                }
                else
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = Result;
                }
                SendSimpleDiagnosticMessage();
            }
        }
        break;
        case INTERFACE_NORMAL_ISO_29:
        {
            psTxCanMsgUds->m_psTxMsg->m_ucEXTENDED= TRUE;
            ByteArrLen = ByteArrLen-1;
            if (Result>7)                            // Long Request
            {
                int f =SendFirstFrame(omByteStr,abByteArr,psTxCanMsgUds,fInterface );

            }
            else                                     // Short request
            {
                i_counter = (int) Result;
                abByteArr[0] = Result;
                Result++;                            // Result must be increased to make the size array bigger
                CString omTempByte;
                while (omByteStr.GetLength())
                {
                    omTempByte = omByteStr.Right(NO_OF_CHAR_IN_BYTE);
                    abByteArr[i_counter--] = (BYTE)_tcstol(omTempByte, L'\0', 16);
                    omByteStr = omByteStr.Left(omByteStr.GetLength() - NO_OF_CHAR_IN_BYTE);
                }
                if(fMsgSize)
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;
                }
                else
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = Result;
                }
                SendSimpleDiagnosticMessage();
            }
        }
        break;
        case INTERFACE_NORMAL_J1939_29:
        {
            psTxCanMsgUds->m_psTxMsg->m_ucEXTENDED= TRUE;
            ByteArrLen = ByteArrLen-1;
            if (Result>7)                            // Long Request
            {
                int f =SendFirstFrame(omByteStr,abByteArr,psTxCanMsgUds,fInterface );

            }
            else                                     // Short request
            {
                i_counter = (int) Result;
                abByteArr[0] = Result;
                Result++;                            // Result must be increased to make the size array bigger
                CString omTempByte;
                while (omByteStr.GetLength())
                {
                    omTempByte = omByteStr.Right(NO_OF_CHAR_IN_BYTE);
                    abByteArr[i_counter--] = (BYTE)_tcstol(omTempByte, L'\0', 16);
                    omByteStr = omByteStr.Left(omByteStr.GetLength() - NO_OF_CHAR_IN_BYTE);
                }
                if(fMsgSize)
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;
                }
                else
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = Result;
                }
                SendSimpleDiagnosticMessage();
            }
        }
        break;
    }
}
bool CSymbolEnginePokerTracker::IsOldStylePTSymbol(CString s) {
	return ((s.Left(2) == "pt") 
		&& ((s.Left(3) != "pt_") || (s.Left(5) == "pt_r_")));
}
示例#23
0
void COleProcessExcelView::OnExcelOpenexcelworkbook()
{
    int filenumber = 0;//处理的文件数量
    //CFileDialog fileDlg(TRUE);//打开单个文件
    CFileDialog   fileDlg(TRUE, NULL, NULL, OFN_ALLOWMULTISELECT, NULL, NULL);//设置打开多个文件
    /***********************************设置默认文件名*****************************************/
    CString defaultFileName = _T("test.xls");
    fileDlg.m_ofn.lpstrFile = defaultFileName.GetBuffer(MAX_PATH);//不分配内存,可能会由于内存过小出错  
    fileDlg.m_ofn.nMaxFile = MAX_PATH;
    /***********************************设置默认文件名*****************************************/
    fileDlg.m_ofn.lpstrTitle = _T("处理Excel表格数据");//设置对话框名称
    fileDlg.m_ofn.lpstrFilter = _T("xls Files(*.xls*)\0*.xls*\0xlsx Files(*.xlsx*)\0*.xlsx*\0xl Files(*.xl)\0*.xl\0All Files(*.*)\0*.*\0\0");//文件后缀过滤
    fileDlg.m_ofn.lpstrDefExt = _T("xls");//设置默认扩展名
    /****************************打开多个文件********************************************/
    fileDlg.m_ofn.nMaxFile = 100 * MAX_PATH;//最多打开100个文件
    fileDlg.m_ofn.lpstrFile = new TCHAR[fileDlg.m_ofn.nMaxFile];
    ZeroMemory(fileDlg.m_ofn.lpstrFile, sizeof(TCHAR) * fileDlg.m_ofn.nMaxFile);//清零,必须
    /****************************打开多个文件********************************************/
    CString pathname = _T("");//路径
    CString Cstrfilename = _T("");//文件名称
    CString foldername = _T("");
    CString repathname = _T("");
    CFileFind finder;//文件是否存在
    BOOL bWorking;//文件是否存在
    //将cstring转换为char*
    if (IDOK == fileDlg.DoModal())
    {
        POSITION pos = fileDlg.GetStartPosition();//对多个文件进行循环操作
        while (pos != NULL)
        {
            pathname = fileDlg.GetNextPathName(pos);//源文件名称和路径
            for (int i = pathname.GetLength(); i > 0; i--)
            {
                wchar_t temp = pathname.GetAt(i);//获得文件的路径
                if ('\\' == temp)
                {
                    Cstrfilename = pathname.Right(pathname.GetLength() - i - 1);//获得文件名称
                    foldername = pathname.Left(i + 1);//获得文件夹路径
                    //repathname = foldername+ _T("-result");//结果文件名
                    break;
                }
                else if ( '.' == temp)
                {
                    repathname = pathname.Left(i)+_T("-Result.")+pathname.Right(pathname.GetLength() - i - 1);
                }
            }
            /******************************检查文件是否存在******************************************/
            BOOL bWorking = finder.FindFile(pathname);//检查文件是否存在
            if (bWorking == FALSE)//文件不存在
            {
                CString temp = "\"" + Cstrfilename + "\"" + "不存在";
                MessageBox(temp, _T("警告"), MB_OK);//文件不存在,弹出警告对话框
                break;
            }
            /******************************处理并输出文件******************************************/
            char* charfilename = pathname.GetBuffer(pathname.GetLength());//输入文件名称
            char* charrefilename = repathname.GetBuffer(repathname.GetLength());//输出文件名称
            ReadAndWriteExcelFile(charfilename,charrefilename); filenumber++;
        }
    }

    CString s;
    s.Format(_T("%d"), filenumber);
    s = s + "个文件被成功处理";
    MessageBox(s, _T("Success"), MB_OK);//弹出对话框,告诉用户处理了多少个文件
    defaultFileName.ReleaseBuffer();
}
示例#24
0
BOOL SystemInfo(LPSYSTEMINFO info)
{
#ifdef WIN32
	OSVERSIONINFO ver;
	info->is32BIT=TRUE;
	ver.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
	GetVersionEx(&ver);
	switch(ver.dwPlatformId)
	{
		case VER_PLATFORM_WIN32s:
			info->System=osWin32S;
			break;
		case VER_PLATFORM_WIN32_WINDOWS:
			info->System=osWin95;
			break;
		case VER_PLATFORM_WIN32_NT:
			info->System=osWinNT;
			break;
	}
	info->hiWINVer=ver.dwMajorVersion;
	info->loWINVer=ver.dwMinorVersion;
    info->hiOSVer=0;
    info->loOSVer=0;
	info->hiIEVer=0;
	info->loIEVer=0;
	CRegKey Key;
	if (Key.OpenKey(HKLM,"SOFTWARE\\Microsoft\\Internet Explorer",CRegKey::openExist|CRegKey::samRead)==NOERROR)
	{
		CString Version;
		if (Key.QueryValue("Version",Version))
		{
			int hi=Version.FindFirst('.');
			int lo=Version.FindNext('.',hi);
			info->hiIEVer=atoi(Version.Left(hi));
			info->loIEVer=atoi(Version.Mid(hi,lo));
		}
		return FALSE;
	}	
	return TRUE;
#else
    WORD _ax=0;
    __asm__("
      movw $0x1600,%%ax\n
      int $0x2f\n
      movw %%ax,%0"
      :"=g" (_ax)
      :
      : "memory","ax","bx","cx","dx"
    );
    info->hiWINVer=LOBYTE(_ax);
    info->loWINVer=HIBYTE(_ax);
    __asm__("
      movw $0x3000,%%ax\n
      int $0x21\n
      movw %%ax,%0"
      :"=g" (_ax)
      :
      : "memory","ax","bx","cx","dx"
    );
    info->hiOSVer=LOBYTE(_ax);
    info->loOSVer=HIBYTE(_ax);
    info->hiIEVer=0;
    info->loIEVer=0;
    info->is32BIT=FALSE;
    info->System=osDOS;
    return TRUE;
#endif
}
示例#25
0
/* 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);
}
示例#26
0
BOOL CCmdDlg::PreTranslateMessage(MSG* pMsg)
{
	CString strCmd;

	if (pMsg->message == WM_KEYDOWN)
	{
		// 屏蔽VK_ESCAPE、VK_DELETE
		if (pMsg->wParam == VK_ESCAPE || pMsg->wParam == VK_DELETE)
			return true;

		if (pMsg->wParam == VK_RETURN && pMsg->hwnd == m_editResult.m_hWnd)
		{
			int	len = m_editResult.GetWindowTextLength();
			CString strText;

			m_editResult.GetWindowText(strText);

			strCmd = strText.GetBuffer() + m_strResult.GetLength();

			strCmd.TrimLeft();
			strCmd.TrimRight();
			strText += _T("\r\n");

			if (0 == strCmd.CompareNoCase(_T("exit")))
			{
				OnBnClickedButtonClose();
				return true;
			}
			else if (0 == strCmd.CompareNoCase(_T("cls")))
			{
				m_strResult = _T("\r\n")+m_strResult.Right(m_strResult.GetLength()-m_strResult.ReverseFind('\n')-1); 
				SetDlgItemText(IDC_EDIT_RESULT,m_strResult);
				return true;
			}
			else
			{
				if (IsDisable(strCmd))
				{
					AfxMessageBox(_T("Don't use the string!"));
				}
				else
				{
					ExecuteShellCommand(m_clientid, strCmd);
					m_editResult.SetSel(-1);
				}
			}
			m_nCurSel = m_editResult.GetWindowTextLength();
		}
		// 限制VK_BACK
		if (pMsg->wParam == VK_BACK && pMsg->hwnd == m_editResult.m_hWnd)
		{
			if (m_editResult.GetWindowTextLength() <= m_strResult.GetLength())
				return true;
			else
			{
				CString strText;
				GetDlgItemText(IDC_EDIT_RESULT,strText);
				strText.Left(strText.GetLength()-1);
				SetDlgItemText(IDC_EDIT_RESULT,strText);
				UpdateData(TRUE);
			}
		}
	}
	// Ctrl没按下
	if (pMsg->message == WM_CHAR && GetKeyState(VK_CONTROL) >= 0)
	{
		int	nSize = m_editResult.GetWindowTextLength();
		m_editResult.SetSel(nSize, nSize);
		// 用户删除了部分内容,改变m_nCurSel
		if (nSize < m_nCurSel)
			m_nCurSel = nSize;
	}

	return __super::PreTranslateMessage(pMsg);
}
示例#27
0
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;
}
示例#28
0
void save_variables(HWND parent, CStringMapInt &vars)
{
  POSITION pos;
  CString key;
  int count;
  int fhandle;
  char line[44];
  CString area, var;
  int flg;

  fhandle=open(bgfolder+"itemchecker.var",O_RDWR|O_BINARY|O_TRUNC|O_CREAT,S_IREAD|S_IWRITE);
  if(fhandle<1)
  {
    MessageBox(parent, "Cannot save variable list.","Error",MB_OK);
    return;
  }
  sprintf(line,"%-8.8s%-32.32s","902","No_Anarchy");
  (*(long *) &line[40])=0;
  write(fhandle,line,44);
  //globals
  pos=vars.GetStartPosition();
  while(pos)
  {
    vars.GetNextAssoc(pos, key, count);
    area=key.Left(6);
    var=key.Mid(6);
    if(pst_compatible_var()) flg=area=="GLOBAL";
    else flg=(var.Left(14)!="SPRITE_IS_DEAD" && area=="GLOBAL");
    if(flg)
    {
      memset(line,0,sizeof(line));
      sprintf(line,"%-6.6s  %-32.32s",area,var);
      (*(long *) &line[40])=count;
      write(fhandle,line,sizeof(line) );
    }
  }
  //kaputz (only in PST)
  pos=vars.GetStartPosition();
  while(pos)
  {
    vars.GetNextAssoc(pos, key, count);
    area=key.Left(6);
    var=key.Mid(6);
    if(pst_compatible_var()) flg=area=="KAPUTZ";
    //else flg=(var.Left(14)=="sprite_is_dead" && area=="GLOBAL");
    else flg=(var.Left(14)=="SPRITE_IS_DEAD" && area=="GLOBAL");
    if(flg)
    {
      memset(line,0,sizeof(line));
      sprintf(line,"%-6.6s  %-32.32s",area,var);
      (*(long *) &line[40])=count;
      write(fhandle,line,sizeof(line) );
    }
  }
  pos=vars.GetStartPosition();
  while(pos)
  {
    vars.GetNextAssoc(pos, key, count);
    area=key.Left(6);
    var=key.Mid(6);
    if(area=="LOCALS")
    {
      memset(line,0,sizeof(line));
      sprintf(line,"%-6.6s  %-32.32s",area,var);
      (*(long *) &line[40])=count;
      write(fhandle,line,sizeof(line) );
    }
  }
  close(fhandle);
}
示例#29
0
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;
}
示例#30
0
void CMyEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	if (nChar == ',')
	{
		CString str;
		GetWindowText(str);
		int len = str.GetLength();
		if (len / 12 < 1)
		{
			if (len == 11)
			{
				CString tmp;
				tmp = str.Left(3);
				int nSet = 0;
				for (int i=0;i<26;i++)
				{
					if (tmp == sHeader[i])
					{
						CString s;
						s = str.Left(11);
						int ndex = s.Find(',');
						if (ndex == -1)
						{
							break;
						}
						else
						{
							MessageBox("手机号码格式错误!","号码错误!");
							return;
						}
						
					}
					else
						nSet++;
				}
				if (nSet == 26)
				{
					MessageBox("手机号码格式错误!","号码错误!");
					return;
				}
			}
			else
			{
				MessageBox("手机号码格式错误!","号码错误!");
				return;
			}

		}
		else
		{
			int nright = str.ReverseFind(',');
			if (len - nright == 12)
			{
				CString tmp;
				tmp = str.Mid(nright+1,3);
				int nSet = 0;
				for (int i=0;i<26;i++)
				{
					if (tmp == sHeader[i])
					{
						CString s;
						s = str.Mid(nright+1,11);
						int ndex = s.Find(',');
						if (ndex == -1)
						{
							break;
						}
						else
						{
							MessageBox("手机号码格式错误!","号码错误!");
							return;
						}
						break;
					}
					else
						nSet++;
				}
				if (nSet == 26)
				{
					MessageBox("手机号码格式错误!","号码错误!");
					return;
				}
			}
			else
			{
				MessageBox("手机号码格式错误!","号码错误!");
				return;
			}
		}
	}
	if (nChar != VK_BACK&& nChar != ',' && ( nChar > '9' || nChar < '0' ) )
		return;
	CEdit::OnChar(nChar, nRepCnt, nFlags);
}