Пример #1
0
BOOL CStdioFileEx::ReadString(CString& rString)
{
	const int	nMAX_LINE_CHARS = 4096;
	BOOL			bReadData = FALSE;
	LPTSTR		lpsz;
	int			nLen = 0;
	wchar_t*		pszUnicodeString = NULL;
	char	*		pszMultiByteString= NULL;
	int			nChars = 0;

	try
	{
		// If at position 0, discard byte-order mark before reading
		if (!m_pStream || (GetPosition() == 0 && m_bIsUnicodeText))
		{
			wchar_t	cDummy;
	//		Read(&cDummy, sizeof(_TCHAR));
			Read(&cDummy, sizeof(wchar_t));
		}

// If compiled for Unicode
#ifdef _UNICODE
		if (m_bIsUnicodeText)
		{
			// Do standard stuff - Unicode to Unicode. Seems to work OK.
			bReadData = CStdioFile::ReadString(rString);
		}
		else
		{
			pszUnicodeString	= new wchar_t[nMAX_LINE_CHARS]; 
			pszMultiByteString= new char[nMAX_LINE_CHARS]; 

			// Initialise to something safe
			memset(pszUnicodeString, 0, sizeof(wchar_t) * nMAX_LINE_CHARS);
			memset(pszMultiByteString, 0, sizeof(char) * nMAX_LINE_CHARS);
			
			// Read the string
			bReadData = (NULL != fgets(pszMultiByteString, nMAX_LINE_CHARS, m_pStream));

			if (bReadData)
			{
				// Convert multibyte to Unicode, using the specified code page
				nChars = GetUnicodeStringFromMultiByteString(pszMultiByteString, pszUnicodeString, nMAX_LINE_CHARS, m_nFileCodePage);

				if (nChars > 0)
				{
					rString = (CString)pszUnicodeString;
				}
			}
		}
#else

		if (!m_bIsUnicodeText)
		{
			// Do standard stuff -- read ANSI in ANSI
			bReadData = CStdioFile::ReadString(rString);

			// Get the current code page
			UINT nLocaleCodePage = GetCurrentLocaleCodePage();

			// If we got it OK...
			if (nLocaleCodePage > 0)
			{
				// if file code page does not match the system code page, we need to do a double conversion!
				if (nLocaleCodePage != (UINT)m_nFileCodePage)
				{
					int nStringBufferChars = rString.GetLength() + 1;

					pszUnicodeString	= new wchar_t[nStringBufferChars]; 

					// Initialise to something safe
					memset(pszUnicodeString, 0, sizeof(wchar_t) * nStringBufferChars);
					
					// Convert to Unicode using the file code page
					nChars = GetUnicodeStringFromMultiByteString(rString, pszUnicodeString, nStringBufferChars, m_nFileCodePage);

					// Convert back to multibyte using the system code page
					// (This doesn't really confer huge advantages except to avoid "mangling" of non-convertible special
					// characters. So, if a file in the E.European code page is displayed on a system using the 
					// western European code page, special accented characters which the system cannot display will be
					// replaced by the default character (a hash or something), rather than being incorrectly mapped to
					// other, western European accented characters).
					if (nChars > 0)
					{
						// Calculate how much we need for the MB buffer (it might be larger)
						nStringBufferChars = GetRequiredMultiByteLengthForUnicodeString(pszUnicodeString,nLocaleCodePage);
						pszMultiByteString= new char[nStringBufferChars];  

						nChars = GetMultiByteStringFromUnicodeString(pszUnicodeString, pszMultiByteString, nStringBufferChars, nLocaleCodePage);
						rString = (CString)pszMultiByteString;
					}
				}
			}
		}
		else
		{
			pszUnicodeString	= new wchar_t[nMAX_LINE_CHARS]; 

			// Initialise to something safe
			memset(pszUnicodeString, 0, sizeof(wchar_t) * nMAX_LINE_CHARS);
			
			// Read as Unicode, convert to ANSI

			// Bug fix by Dennis Jeryd 06/07/2003: initialise bReadData
			bReadData = (NULL != fgetws(pszUnicodeString, nMAX_LINE_CHARS, m_pStream));

			if (bReadData)
			{
				// Calculate how much we need for the multibyte string
				int nRequiredMBBuffer = GetRequiredMultiByteLengthForUnicodeString(pszUnicodeString,m_nFileCodePage);
				pszMultiByteString= new char[nRequiredMBBuffer];  

				nChars = GetMultiByteStringFromUnicodeString(pszUnicodeString, pszMultiByteString, nRequiredMBBuffer, m_nFileCodePage);

				if (nChars > 0)
				{
					rString = (CString)pszMultiByteString;
				}
			}

		}
#endif

		// Then remove end-of-line character if in Unicode text mode
		if (bReadData)
		{
			// Copied from FileTxt.cpp but adapted to Unicode and then adapted for end-of-line being just '\r'. 
			nLen = rString.GetLength();
			if (nLen > 1 && rString.Mid(nLen-2) == sNEWLINE)
			{
				rString.GetBufferSetLength(nLen-2);
			}
			else
			{
				lpsz = rString.GetBuffer(0);
				if (nLen != 0 && (lpsz[nLen-1] == _T('\r') || lpsz[nLen-1] == _T('\n')))
				{
					rString.GetBufferSetLength(nLen-1);
				}
			}
		}
	}
	// Ensure we always delete in case of exception
	catch(...)
	{
		if (pszUnicodeString)	delete [] pszUnicodeString;

		if (pszMultiByteString) delete [] pszMultiByteString;

		throw;
	}

	if (pszUnicodeString)		delete [] pszUnicodeString;

	if (pszMultiByteString)		delete [] pszMultiByteString;

	return bReadData;
}
Пример #2
0
void COptionsSpeedLimitPage::ShowSpeedLimit(CListBox &listBox, SPEEDLIMITSLIST &list)
{
	listBox.ResetContent();

	for (unsigned int i = 0; i < list.size(); i++)
	{
		CString str;
		
		str.Format(_T( "%dkB/s"), list[i].m_Speed);

		CString help;
		
		if (list[i].m_DateCheck)
		{
			CTime t(list[i].m_Date.y, list[i].m_Date.m, list[i].m_Date.d, 0, 0, 0);
			help += t.Format(_T("%x"));
		}
		
		if (list[i].m_FromCheck)
		{
			if (help.GetLength() > 0)
				help += _T( "; ");
			
			CTime t(2003, 1, 1, list[i].m_FromTime.h, list[i].m_FromTime.m, list[i].m_FromTime.s);
			help += _T("F:") + t.Format( _T("%X"));
		}
		
		if (list[i].m_ToCheck)
		{
			if (help.GetLength() > 0)
				help += _T( "; ");
			
			CTime t(2003, 1, 1, list[i].m_ToTime.h, list[i].m_ToTime.m, list[i].m_ToTime.s);
			help += _T("T:") + t.Format( _T("%X"));
		}
		
		for (int j = 0; j < 7; j++)
			if (!(list[i].m_Day & (1<<j)))
			{
				if (help.GetLength() > 0)
					help += _T( "; ");
				
				bool was = false;
				for ( int k = 0; k < 7; k++)
				{
					if ((list[i].m_Day & (1<<k)))
					{
						if (was)
							help += _T(", ");
						
						was = true;
						
						CTime time(2001, 1, k + 1, 0, 0, 0);
						
						help += time.Format(_T("%a"));
					}
				}
				
				break;
			}
		
		str += _T(" [") + help + _T("]");
		
		listBox.AddString(str);
	}
}
Пример #3
0
void CRedirectHTTPS_Thread::StartRedirect()
{	m_sServerSocket=INVALID_SOCKET; m_iConnections=0;
	int iErr=1; bool bFinished=false; while(!bFinished && g_pMainCtrl->m_bRunning) {
		url uURL; char szBuffer[MAX_PATH]; bool bGet=false;

		// Receive the proxy request
		if(!m_sClientSocket.RecvLineIRC(szBuffer, MAX_PATH)) { bFinished=true; break; }
		CString sBuffer(szBuffer);
		// Fail if there is no url
		// if(!sBuffer.Token(1, " ").Compare("")) { bFinished=true; break; }

		if(!sBuffer.Compare("")) { bFinished=true; break; }

		if(!sBuffer.Token(0, " ").CompareNoCase("GET")) { // GET method
			bGet=true;
			// Parse the url
			if(!ParseURL(sBuffer.Token(1, " ").CStr(), &uURL)) { bFinished=true; break; }
			// Fail if the protocol isnt http
			if(uURL.sProto.Compare("http")) { bFinished=true; break; }
		} else if(!sBuffer.Token(0, " ").CompareNoCase("CONNECT")) { // CONNECT method
			bGet=false;
			// Parse the host
			uURL.sProto.Assign("connect");
			uURL.sReq.Assign("");
			uURL.sHost.Assign(sBuffer.Token(1, " ").Token(0, ":"));
			if(!sBuffer.Token(1, " ").Token(1, ":").CStr()) { bFinished=true; break; }
			uURL.iPort=atoi(sBuffer.Token(1, " ").Token(1, ":").CStr());
			if(!uURL.iPort) uURL.iPort=80; }

		// Get the rest of the request
		CString sMethod(sBuffer.Token(0, " ")); if(!sMethod.Compare("")) { bFinished=true; break; }
		CString sHTTPSVer(sBuffer.Token(2, " ")); if(!sHTTPSVer.Compare("")) { bFinished=true; break; }
		CString sOldHost(uURL.sHost);

#ifdef DBGCONSOLE
		if(bGet)
			g_pMainCtrl->m_cConsDbg.Log(5, "CRedirectHTTPS(0x%8.8Xh): %s %s %s...\n", m_pRedirHTTPS, sMethod.CStr(), uURL.sReq.CStr(), sHTTPSVer.CStr());
		else
			g_pMainCtrl->m_cConsDbg.Log(5, "CRedirectHTTPS(0x%8.8Xh): %s %s:%d %s...\n", m_pRedirHTTPS, sMethod.CStr(), uURL.sHost.CStr(), uURL.iPort, sHTTPSVer.CStr());
#endif

		char szBuf[4096]; strcpy(szBuf, "bla");
		if(bGet) {
			if(!m_sClientSocket.Recv(szBuf, sizeof(szBuf)))
			{	m_sClientSocket.Disconnect(); return; }
		} else {
			while(strcmp(szBuf, "")) // Loop while headers arent finished
				if(!m_sClientSocket.RecvLineIRC(szBuf, 4096)) { bFinished=true; break; }
			if(bFinished) break; }

		CString sReqBuf;
		if(bGet)
			sReqBuf.Format("%s %s %s\r\n%s", sMethod.CStr(), uURL.sReq.CStr(), sHTTPSVer.CStr(), szBuf);
		else
			sReqBuf.Format("HTTP/1.0 200 Connection established\r\n\r\n");

		m_sServerSocket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(!m_sServerSocket.IsConnected())
		{	m_sClientSocket.Disconnect(); return; }

		// Connect to the server
		if(!m_sServerSocket.Connect(uURL.sHost.CStr(), uURL.iPort)) // Connect failed, exit
		{	
#ifdef DBGCONSOLE
			g_pMainCtrl->m_cConsDbg.Log(5, "CRedirectHTTPS(0x%8.8Xh): Cannot connect to %s:%d (%s)...\n", m_pRedirHTTPS, uURL.sHost.CStr(), uURL.iPort, uURL.sReq.CStr());
#endif
			m_sClientSocket.Disconnect(); m_sServerSocket.Disconnect(); return; }

		if(bGet) {
			if(!m_sServerSocket.Write(sReqBuf.CStr(), sReqBuf.GetLength()))
			{	m_sClientSocket.Disconnect(); m_sServerSocket.Disconnect(); return; }
		} else {
			if(!m_sClientSocket.Write(sReqBuf.CStr(), sReqBuf.GetLength()))
			{	m_sClientSocket.Disconnect(); m_sServerSocket.Disconnect(); return; }
		}

		int iLen; fd_set fd;
		SET_SOCK_BLOCK(m_sClientSocket.GetSocket(), 0);
		SET_SOCK_BLOCK(m_sServerSocket.GetSocket(), 0);

		if(bGet) {
			while(true)
			{	memset(szBuffer, 0, sizeof(szBuffer));
				if(!m_sClientSocket.RecvLineIRC(szBuffer, sizeof(szBuffer))) { Sleep(10); break; }
				if(strcmp(szBuffer, "")) {
					sBuffer.Assign(szBuffer);
					if(!sBuffer.Token(0, " ").Compare("GET"))
					{	// Fail if there is no url
						if(!sBuffer.Token(1, " ").Compare("")) { bFinished=true; break; }
						// Parse the url
						if(!ParseURL(sBuffer.Token(1, " ").CStr(), &uURL)) break;
						// Fail if the protocol isnt http
						if(uURL.sProto.Compare("http")) { bFinished=true; break; }
						// Get the rest of the request
						CString sMethod(sBuffer.Token(0, " ")); if(!sMethod.Compare("")) { bFinished=true; break; }
						CString sHTTPSVer(sBuffer.Token(2, " ")); if(!sHTTPSVer.Compare("")) { bFinished=true; break; }
						sBuffer.Format("%s %s %s\r\n", sMethod.CStr(), uURL.sReq.CStr(), sHTTPSVer.CStr());
						if(uURL.sHost.Compare(sOldHost))
						{	m_sServerSocket.Disconnect();

							if(!m_sServerSocket.Connect(uURL.sHost.CStr(), uURL.iPort)) // Connect failed, exit
							{	
#ifdef DBGCONSOLE
								g_pMainCtrl->m_cConsDbg.Log(5, "CRedirectHTTPS(0x%8.8Xh): Cannot connect to %s:%d (%s)...\n", m_pRedirHTTPS, uURL.sHost.CStr(), uURL.iPort, uURL.sReq.CStr());
#endif
								m_sClientSocket.Disconnect(); m_sServerSocket.Disconnect(); return; }
							
							sOldHost.Assign(uURL.sHost); }
					}
					else
					{	sBuffer.Append("\r\n"); }
				if(!m_sServerSocket.Write(sBuffer.CStr(), sBuffer.GetLength())) break; }

				m_sServerSocket.Recv(szBuf, sizeof(szBuf), &iLen);
				if(!iLen) break; if(iLen<0 && ERRNO!=EWOULDBLOCK) { Sleep(10); break; }
				m_sClientSocket.Write(szBuf, iLen);
			}
		} else {
			while(true) {
				m_sClientSocket.Recv(szBuf, sizeof(szBuf), &iLen);
				if(!iLen) break; if(iLen<0 && ERRNO!=EWOULDBLOCK) { Sleep(10); break; }
				m_sServerSocket.Write(szBuf, iLen);

				m_sServerSocket.Recv(szBuf, sizeof(szBuf), &iLen);
				if(!iLen) break; if(iLen<0 && ERRNO!=EWOULDBLOCK) { Sleep(10); break; }
				m_sClientSocket.Write(szBuf, iLen);
			}
		}

		m_sClientSocket.Disconnect(); m_sServerSocket.Disconnect();
		bFinished=true;
	}
}
Пример #4
0
void CIrcWnd::ParseChangeMode(const CString& sChannel, const CString& sChanger, CString sCommands, const CString& sParams)
{
	CString sCommandsOrig = sCommands;
	CString sParamsOrig = sParams;
	try
	{
		if( sCommands.GetLength() >= 2 )
		{
			CString sDir;
			int iParamIndex = 0;
			while( !sCommands.IsEmpty() )
			{
				if (sCommands[0] == _T('+') || sCommands[0] == _T('-'))
				{
					sDir = sCommands.Left(1);
					sCommands = sCommands.Right(sCommands.GetLength()-1);
				}
				if( !sCommands.IsEmpty() && !sDir.IsEmpty() )
				{
					CString sCommand = sCommands.Left(1);
					sCommands = sCommands.Right(sCommands.GetLength()-1);

					if(m_wndNicks.m_sUserModeSettings.Find(sCommand) != -1 )
					{
						//This is a user mode change and must have a param!
						CString sParam = sParams.Tokenize(_T(" "), iParamIndex);
						m_wndNicks.ChangeNickMode( sChannel, sParam, sDir + sCommand);
					}
					if(m_wndChanSel.m_sChannelModeSettingsTypeA.Find(sCommand) != -1)
					{
						//We do not use these messages yet.. But we can display them for the user to see
						//These modes always have a param and will add or remove a user from some type of list.
						CString sParam = sParams.Tokenize(_T(" "), iParamIndex);
						m_wndChanSel.ChangeChanMode( sChannel, sParam, sDir, sCommand);
					}
					if(m_wndChanSel.m_sChannelModeSettingsTypeB.Find(sCommand) != -1)
					{
						//We do not use these messages yet.. But we can display them for the user to see
						//These modes will always have a param..
						CString sParam = sParams.Tokenize(_T(" "), iParamIndex);
						m_wndChanSel.ChangeChanMode( sChannel, sParam, sDir, sCommand);
					}
					if(m_wndChanSel.m_sChannelModeSettingsTypeC.Find(sCommand) != -1 )
					{
						//We do not use these messages yet.. But we can display them for the user to see
						//These modes will only have a param if your setting it!
						CString sParam;
						if (sDir == _T("+"))
							sParam = sParams.Tokenize(_T(" "), iParamIndex);
						m_wndChanSel.ChangeChanMode( sChannel, sParam, sDir, sCommand);
					}
					if(m_wndChanSel.m_sChannelModeSettingsTypeD.Find(sCommand) != -1 )
					{
						//We do not use these messages yet.. But we can display them for the user to see
						//These modes will never have a param for it!
						CString sParam;
						m_wndChanSel.ChangeChanMode( sChannel, sParam, sDir, sCommand);
					}
				}
			}
			if (!thePrefs.GetIRCIgnoreMiscMessages())
				AddInfoMessageF(sChannel, GetResString(IDS_IRC_SETSMODE), sChanger, sCommandsOrig, sParamsOrig);
		}
	}
	catch(...)
	{
		AddInfoMessage(sChannel, GetResString(IDS_IRC_NOTSUPPORTED));
		ASSERT(0);
	}
}
Пример #5
0
void CTabNFC::OnTimer(UINT nIDEvent) 
{
	char intro[NFC_HEADER_LEN+4], intro2[NFC_HEADER_LEN+4];

	if (nIDEvent == 3) {
		NfcMakeAtest();
		return;
		}
	if (nIDEvent != m_iNFCTimerID)	return;

	portSetScanMode();
	int nn = portScan(intro, NFC_HEADER_LEN);
	if (nn == -1) {
		KillTimer(m_iNFCTimerID);
		return;
		}
	if (! nn)	return;
	char *p;
	if (! (p = strchr(intro, '[')))
		return;
	p += 1;
	int xlen;
	xlen = p - &intro[0];
	strcpy(intro2, p);
	strcpy(intro, intro2);
#if ! LOG_AND_DELAY
	portSetFastMode();
#endif
	nn = portRead(intro2, xlen);
	if (nn == -1) {
		KillTimer(m_iNFCTimerID);
		return;
		}
	strcat(intro, intro2);
	// Suspend timer
#if ! LOG_AND_DELAY
	portSetXFastMode();
#endif
	char data[2*NFC_TOTBUF_LEN+64], pfbbuf[4];
	int iintro, len, more, toFile = 0, isFile, isTest, noMore, pfb, pfb0, n;
	int retry = NFC_RETRY, tot = 0, size = 0, val;
	CString fname = m_sNFCDirName;
	if (fname.GetLength())
		fname += "\\";
	ofstream out;
	pfbbuf[2] = 0;
	p = intro;
//char msg[256];

//	logAdd("000", 0, 0);
int iter = 0;
	while (1) {
iter++;
#if USE_PFB
		pfbbuf[0] = *p++;
		pfbbuf[1] = *p++;
		sscanf(pfbbuf, "%X", &pfb);
#endif
		sscanf(p, "%X", &iintro);
		len = iintro & NFC_LEN_MASK;
		isTest = iintro & NFC_TEST_MASK;
		isFile = iintro & NFC_FILE_MASK;
		more = iintro & NFC_MORE_MASK;
		len++;	// Get closing brace ]
//if (iter > 2) portWrite("0", 9);
//sprintf(msg, "..001 len=%d, more = %d", len, more);
//logAdd(msg, 0, 0);
		retry--;
		if ((! (n = portRead(data, len)) ||
			 (n != len && n != (len+4)))
#if USE_PFB
			&& pfb != pfb0
#endif
						) {
#if RS232_ONLY
			portWrite(INITIATOR_NAK, 9, 0);
#else
			portWrite(TARGET_NAK, 0, 0);
//logAdd(TARGET_NAK, 0, 0);
#endif
			if (retry)
				goto skip2;
			else
				break;
			}
#if USE_PFB
		if (pfb == pfb0)
			goto skip;
#endif
//if (iter > 1) portWrite("0", 9);
if (iter > 1)
iter++;
//data[len] = 0;
//sprintf(msg, "..002 data=%s", data);
//logAdd(msg, 0, 0);
		hex2data(data, &len);
//data[len] = 0;
//sprintf(msg, "..002+ data=%s", data);
//logAdd(msg, 0, 0);
		if (! strncmp(data, NFC_FILE, strlen(NFC_FILE))) {
			data[len] = 0;
			logAdd(data, 0, 0);
			p = data;
			p += strlen(NFC_FILE);
			char *sep;
			if ((sep = strchr(p, ';'))) {
				*sep = 0;
				sep++;
				sscanf(sep, "%d", &size);
				}
			fname += p;
			out.open(fname, ios_base::binary);
			toFile = 1;
#if ! LOG_AND_DELAY
			portNoLogging();
#endif
			// show progress slider
			if (size) {
				GetDlgItem(IDC_NFC_FILE_PROG)->ShowWindow(SW_SHOWNA);
				m_NFCFileProgress.SetPos(0);
				UpdateData(FALSE);	// Set screen values
				}
			}
		else if (toFile) {
//			out << data;
			out.write(data, len);
			tot += len;
			val = (tot + 1) * 100 / size;
			if (size && ! (val % 10)) {
				m_NFCFileProgress.SetPos(val);
				UpdateData(FALSE);	// Set screen values
				}
			}
		else if (isFile) {
			portWrite(TARGET_NAK, 0, 0);
			break;
			}
		else if (isTest) {
#if ! LOG_AND_DELAY
			portNoLogging();
#endif
			}
		else {
			m_sNFCData = data;
			UpdateData(FALSE);	// Set screen values
			}
#if USE_PFB
		pfb0 = pfb;
	  skip:
#endif
//logAdd("..003", 0, 0);
#if RS232_ONLY
		portWrite(INITIATOR_ACK, 9, 0);
#else
		portWrite(TARGET_ACK, 0, 0);
#endif
		if (! more) {
//			logAdd("=======================", 0, 0);
			break;
			}
//if (iter > 1) portWrite("0", 9);
	skip2:
		len = NFC_HEADER_LEN;
//logAdd("..004", 0, 0);
		retry = NFC_RETRY;
		noMore = 0;
		while (1) {
			retry--;
			if (! (n = portRead(intro, len))) {
#if RS232_ONLY
				portWrite(INITIATOR_NAK, 9, 0);
#else
//				portWrite(TARGET_NAK, 0, 0);
#endif
				noMore = 1;
				break;
				}
//logAdd("..005..", 0, 0);
			if ((p = strchr(intro, '[')))
				break;
			if (! retry)
				goto fail;
			}
//logAdd("..005", 0, 0);
		if (noMore)
			break;
//logAdd("..006", 0, 0);
//if (iter > 1) portWrite("0", 9);
		p += 1;
		xlen = p - &intro[0];
//		xlen = NFC_HEADER_LEN - xlen;
		strcpy(intro2, p);
		strcpy(intro, intro2);
//logAdd("..007", 0, 0);
		nn = portRead(intro2, xlen);
//logAdd("..008", 0, 0);
		if (nn == -1)
			break;
		strcat(intro, intro2);
		p = intro;
//if (iter > 1) portWrite("0", 9);
		retry = NFC_RETRY;
		}
//logAdd("..999", 0, 0);
fail:
	if (toFile) {
		out.close();
		logAdd("DONE", 0, 0);
		// hide progress slider
		GetDlgItem(IDC_NFC_FILE_PROG)->ShowWindow(SW_HIDE);
		}
	portSetLogging();
	
	CDialog::OnTimer(nIDEvent);
	portSetReadMode();
}
Пример #6
0
// 消息处理
LRESULT CControlBase::OnMessage(UINT uID, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	if(m_bTaskMsg)
	{
		// 如果设置了任务方式发消息的属性,则添加一个任务消息
		CString strControlName = GetName();
		CString strAction = GetAction();
		CDlgBase* pParentDlg = GetParentDialog();
		DuiSystem::Instance()->AddDuiActionTask(uID, uMsg, wParam, lParam, strControlName, strAction, pParentDlg);
		return 0;
	}

	if(m_strAction.Find(_T("dlg:")) == 0)	// 动作:打开一个对话框,有内存泄漏,改为通过DuiSystem创建和管理
	{
		if(uMsg == MSG_BUTTON_UP)	// 鼠标放开事件才处理
		{
			CString strXmlFile = m_strAction;
			strXmlFile.Delete(0, 4);
			DuiSystem::ShowDuiDialog(strXmlFile, GetParentDialog());
		}
	}else
	if(m_strAction.Find(_T("popup:")) == 0)	// 动作:打开一个Popup对话框
	{
		if(uMsg == MSG_BUTTON_UP)	// 鼠标放开事件才处理
		{
			/*UINT nIDTemplate = 0;
			CDlgBase* pParentDlg = GetParentDialog();
			if(pParentDlg != NULL)
			{
				nIDTemplate = pParentDlg->GetIDTemplate();
			}
			CDlgPopup* pPopup = new CDlgPopup;
			pPopup->SetParent(this);
			CString strXmlFile = m_strAction;
			strXmlFile.Delete(0, 6);
			pPopup->SetXmlFile(_T("xml:") +strXmlFile );
			CRect rc = pControlBase->GetRect();
			rc.OffsetRect(-95, rc.Height());
			ClientToScreen(&rc);
			pPopup->Create(this, rc, WM_SKIN);
			pPopup->ShowWindow(SW_SHOW);*/
		}
	}else
	if(m_strAction.Find(_T("menu:")) == 0)	// 动作:打开一个菜单
	{
		CDuiMenu *pDuiMenu = new CDuiMenu(DuiSystem::GetDefaultFont(), 12);	// 可以考虑改为通过DuiSystem创建和管理
		pDuiMenu->SetAutoClose(FALSE);
		pDuiMenu->SetParent(this);
		CPoint point;
		CRect rc = GetRect();
		// 计算菜单的显示位置
		if(m_posMenu.nCount >= 2)
		{
			// 使用设置的菜单位置
			int nMenuX = PositionItem2Value(m_posMenu.Left, rc.left, rc.right);
			int nMenuY = PositionItem2Value(m_posMenu.Top, rc.top, rc.bottom);
			point.SetPoint(nMenuX, nMenuY);
		}else
		{
			// 如果没有设置位置信息,则默认按照控件底部开始显示,水平方向中间对齐
			point.SetPoint(rc.left + rc.Width() / 2, rc.bottom);
		}
		CDlgBase* pParentDlg = GetParentDialog();
		if(pParentDlg != NULL)
		{
			pParentDlg->ClientToScreen(&point);
		}
		CString strXmlFile = m_strAction;
		strXmlFile.Delete(0, 5);
		pDuiMenu->LoadXmlFile(strXmlFile, pParentDlg, point, WM_DUI_MENU);
		pDuiMenu->ShowWindow(SW_SHOW);
		pDuiMenu->SetAutoClose(TRUE);
	}else
	if(m_strAction.Find(_T("link:")) == 0)	// 动作:打开一个页面链接
	{
		if(uMsg == MSG_BUTTON_UP)	// 鼠标放开事件才处理
		{
			CString strLink = m_strAction;
			strLink.Delete(0, 5);
			if(!strLink.IsEmpty())
			{
				ShellExecute(NULL, TEXT("open"), strLink, NULL,NULL,SW_NORMAL);
			}
		}
	}else
	if(m_strAction.Find(_T("run:")) == 0)	// 动作:执行一个进程
	{
		if(uMsg == MSG_BUTTON_UP)	// 鼠标放开事件才处理
		{
			CString strProcess = m_strAction;
			strProcess.Delete(0, 4);
			strProcess.MakeLower();
			if(!strProcess.IsEmpty())
			{
				strProcess.MakeLower();
				BOOL bForceAdmin = FALSE;
				if(strProcess.Find(_T("admin@")) == 0)
				{
					bForceAdmin = TRUE;
					strProcess.Delete(0, 6);
				}
				BOOL bWaitProcess = FALSE;
				if(strProcess.Find(_T("&")) == (strProcess.GetLength()-1))
				{
					bWaitProcess = TRUE;
					strProcess.Delete(strProcess.GetLength()-1, 1);
				}
				if(strProcess.Find(_T(".exe")) == -1)
				{
					strProcess = DuiSystem::Instance()->GetString(strProcess);
				}
				if(strProcess.Find(_T("{platpath}")) == 0)
				{
					strProcess.Delete(0, 10);
					strProcess = DuiSystem::GetExePath() + strProcess;
				}
				CString strCmdLine = _T("");
				int nPos = strProcess.Find(_T("|"));
				if(nPos != -1)
				{
					strCmdLine = strProcess;
					strCmdLine.Delete(0, nPos+1);
					strProcess = strProcess.Left(nPos);
				}
				DuiSystem::PathCanonicalize(strProcess);	// 路径标准化
				DuiSystem::ExecuteProcess(strProcess, strCmdLine, bForceAdmin, bWaitProcess);
			}
		}
	}else
	if(m_strAction.Find(ACTION_CLOSE_WINDOW) == 0)	// 动作:关闭指定的窗口
	{
		if(uMsg == MSG_BUTTON_UP)	// 鼠标放开事件才处理
		{
			CString strWndName = m_strAction;
			strWndName.Delete(0, 13);
			if(!strWndName.IsEmpty())
			{
				CDlgBase* pDlg = DuiSystem::Instance()->GetDuiDialog(strWndName);
				if(pDlg != NULL)
				{
					//pDlg->DoClose();
					pDlg->PostMessage(WM_QUIT, 0, 0);
				}
			}
		}
	}else
	{
		// 首先判断如果是几个默认按钮,则直接做相应的处理
		CDlgBase* pParentDlg = GetParentDialog();
		if(IsThisObject(BT_OK, NAME_BT_OK))
		{
			if((MSG_BUTTON_UP == uMsg) && (pParentDlg != NULL)) { pParentDlg->DoOK(); }
		}else
		if(IsThisObject(BT_CANCEL, NAME_BT_CANCEL))
		{
			if((MSG_BUTTON_UP == uMsg) && (pParentDlg != NULL)) { pParentDlg->DoCancel(); }
		}else
		if(IsThisObject(BT_YES, NAME_BT_YES))
		{
			if((MSG_BUTTON_UP == uMsg) && (pParentDlg != NULL)) { pParentDlg->DoYes(); }
		}else
		if(IsThisObject(BT_NO, NAME_BT_NO))
		{
			if((MSG_BUTTON_UP == uMsg) && (pParentDlg != NULL)) { pParentDlg->DoNo(); }
		}else
		{
			// 调用控件的DUI事件处理对象
			CallDuiHandler(uMsg, wParam, lParam);
		}
	}

	return 0;
}
void CLookupForm::OnBnClickedButtonSearch()
{
    CString searchText;
    m_editSearch.GetWindowText(searchText);

    if(searchText.GetLength() <= 0) 
		return;
    searchText.MakeLower(); // itemData is also lower
	CString guidSearchText;

	if (!m_isHR) {
		guidSearchText = searchText;
		guidSearchText.Replace(_T("0x"), _T(""));
		const TCHAR delimiters[] = _T(" \t-,{}()=/;ul");			// remove commonly used GUID delimiters and match by remaining hex digits
		for (int n=0; n<sizeof(delimiters)/sizeof(delimiters[0]) - 1; n++) 
			guidSearchText.Remove(delimiters[n]);
	}

    int selItem = -1, selCol = -1;
    const int start = m_listCtrl.GetSelectionMark() + 1;
	CString item_text;

    const int count = m_listCtrl.GetItemCount();
	bool allowWrap = true;
    for(int i=start; ;i++)
    {
		if (i >= count) {			//  beyond end of list
			if (start > 0 && allowWrap) {
				allowWrap = false;
				i = 0;				// restart at beginning
			}
			else
				break;				// started at beginning or already wrapped so stop looping now
		}

        const CStringArray * const arData = (const CStringArray*)m_listCtrl.GetItemData(i);
        for(int j=0; j<arData->GetCount(); j++)
        {
			int find;
			if (!m_isHR && j==1)	// GUID column - strip out hyphens for easier hex matching
			{
				item_text = arData->GetAt(j);
				item_text.Remove(_T('-'));
				find = item_text.Find(guidSearchText);
			} else 
			{
				find = arData->GetAt(j).Find(searchText);
			}
            if(find >= 0)
            {
                selItem = i;
                selCol = j;
                i=count;			// terminate looping without wrapping
				allowWrap = false;
                break;
            }
        }

		if (i == start-1)		// about to hit start for second time round - stop looping
			break;
    }

    if(selItem != -1)
    {
        m_listCtrl.SetItemState(selItem, LVIS_SELECTED, LVIS_SELECTED);
        m_listCtrl.SetSelectionMark(selItem);
        m_listCtrl.EnsureVisible(selItem, FALSE);
        m_listCtrl.SetFocus();
    }
}
Пример #8
0
gbool GUrlCache::GetCacheStats(const char *directory, time_t &oldest,DWORD &spaceInUse, int &filesInUse)
{

    CFileFind finder;

    CString dir = directory;

    // add separator
    int l = dir.GetLength();
    if (l == 0) return FALSE;
    if ( !((dir[l-1] == '\\') || (dir[l-1] == '/'))) dir += '\\';

    dir += "*.*";

    CString path;

    CTime creationTime((time_t)0);
    CTime accessTime((time_t)0);
    CTime writeTime((time_t)0);

    // setup the find structure
    BOOL bWorking = finder.FindFile(dir);


    while (bWorking)  { // for all entrys
        if (stop) break;

        bWorking = finder.FindNextFile();

        path = finder.GetFilePath();

        creationTime = (time_t)0;
        accessTime = (time_t)0;
        writeTime = (time_t)0;

        BOOL ret=finder.GetCreationTime(creationTime);
        finder.GetLastAccessTime(accessTime);
        finder.GetLastWriteTime(writeTime);
        time_t t = creationTime.GetTime();

        if (accessTime.GetTime()>0) t = max(t,accessTime.GetTime());


        if (finder.IsDots( )) {	// ignore . ..

        } else 	if (finder.IsDirectory( )) { // recursively step down
            GetCacheStats(path,oldest,spaceInUse,filesInUse);
        }
        else {

            DWORD length = finder.GetLength();

            TRACE("F %s c %ld a %ld w %ld size %ld \n",(const char *) path, creationTime.GetTime(),accessTime.GetTime(),writeTime.GetTime(),length);
            oldest = min(oldest,t);
            filesInUse++;
            spaceInUse += length;

        }


    }
    finder.Close();


    return TRUE;
}
Пример #9
0
// combine directory + relFilePath to fullpathname
gbool GUrlCache::Combine(const CString &directory,const CString relFilePath,CString &absFilePath)
{
    if (directory.GetLength() == 0) return FALSE;
    absFilePath = directory+relFilePath;
    return TRUE;
}
Пример #10
0
// add files to list
gbool GFileSorter::AddFiles(const char *directory,time_t &maxFileTime,BOOL &stop)
{

    CFileFind finder;

    CString dir = directory;

    // add separator
    int l = dir.GetLength();
    if (l == 0) return FALSE;
    if ( !((dir[l-1] == '\\') || (dir[l-1] == '/'))) dir += '\\';

    dir += "*.*";

    CString path;

    CTime creationTime((time_t)0);
    CTime accessTime((time_t)0);
    CTime writeTime((time_t)0);

    // setup the find structure
    BOOL bWorking = finder.FindFile(dir);


    while (bWorking)  { // for all entrys
        if (stop) break;

        bWorking = finder.FindNextFile();

        path = finder.GetFilePath();

        creationTime = (time_t)0;
        accessTime = (time_t)0;
        writeTime = (time_t)0;

        BOOL ret=finder.GetCreationTime(creationTime);
        finder.GetLastAccessTime(accessTime);
        finder.GetLastWriteTime(writeTime);

        time_t t = creationTime.GetTime();

        if (writeTime.GetTime()>0) t = max(t,writeTime.GetTime()); // HG wg Kristof

        if (accessTime.GetTime()>0) t = max(t,accessTime.GetTime());

        if (finder.IsDots( )) {	// ignore . ..

        } else 	if (finder.IsDirectory( )) { // recursively step down

            t=0; // we want to delete empty directories new 20.10.98
            AddFiles(path,t,stop);

            DWORD length = 0;

            // to do get date of latest
            TRACE("D %s c %ld a %ld w %ld size %ld \n",(const char *) path, creationTime.GetTime(),accessTime.GetTime(),writeTime.GetTime(),length);

            // time is the max of the child time +1
            GFSortEntry *e = new GFSortEntry(path,t+1,length,gtrue);

            if (!e) break;
            if (!Add(e)) break;

            if (t>maxFileTime) maxFileTime = t;


        }
        else {

            DWORD length = finder.GetLength(); // get length 64
            fileSum += length;

            TRACE("F %s c %ld a %ld w %ld size %ld \n",(const char *) path, creationTime.GetTime(),accessTime.GetTime(),writeTime.GetTime(),length);
            GFSortEntry *e = new GFSortEntry(path,t,length);

            if (t>maxFileTime) maxFileTime = t;

            if (!e) break;
            if (!Add(e)) break;
        }


    }
    finder.Close();

    //TRACE("%ld bytes \n",(long)fileSum);

    return TRUE;
}
Пример #11
0
// recursively remove a file branch
gbool GUrlCache::RemoveFiles(const char *directory,time_t olderThan)
{

    CFileFind finder;

    CString dir = directory;

    // add separator
    int l = dir.GetLength();
    if (l == 0) return FALSE;
    if ( !((dir[l-1] == '\\') || (dir[l-1] == '/'))) dir += '\\';

    dir += "*.*";

    CString path;

    CTime creationTime((time_t)0);
    CTime accessTime((time_t)0);
    CTime writeTime((time_t)0);

    // setup the find structure
    BOOL bWorking = finder.FindFile(dir);

    LONGLONG fileSum=0;

    while (bWorking)  { // for all entrys
        if (stop) break;

        bWorking = finder.FindNextFile();

        path = finder.GetFilePath();

        creationTime = (time_t)0;
        accessTime = (time_t)0;
        writeTime = (time_t)0;

        BOOL ret=finder.GetCreationTime(creationTime);
        finder.GetLastAccessTime(accessTime);
        finder.GetLastWriteTime(writeTime);
        time_t t = creationTime.GetTime();

        // if (accessTime.GetTime()>0) t = max(t,accessTime.GetTime());


        if (finder.IsDots( )) {	// ignore . ..

        } else 	if (finder.IsDirectory( )) { // recursively step down
            RemoveFiles(path,olderThan);
            RemoveDirectory(path);
        }
        else {

            DWORD length = finder.GetLength();

            TRACE("F %s c %ld a %ld w %ld size %ld \n",(const char *) path, creationTime.GetTime(),accessTime.GetTime(),writeTime.GetTime(),length);
            if (olderThan >0 ) {

                if (t < olderThan) {
                    if (RemoveFile(path))
                        fileSum += length;
                }


            } else {
                if (RemoveFile(path))
                    fileSum += length;
            }

        }


    }
    finder.Close();

    TRACE("%ld bytes deleted \n",(long) fileSum);

    return TRUE;
}
//***************************************************************************************
static BOOL ExcludeTag (CString& strBuffer, 
						LPCTSTR lpszTag,
						CString& strTag)
{
	const int iBufLen = strBuffer.GetLength ();

	CString strTagStart = _T("<");
	strTagStart += lpszTag;
	strTagStart += _T(">");

	const int iTagStartLen = strTagStart.GetLength ();

	int iStart = -1;

	int iIndexStart = strBuffer.Find (strTagStart);
	if (iIndexStart < 0)
	{
		return FALSE;
	}

	iStart = iIndexStart + iTagStartLen;

	CString strTagEnd = _T("</");
	strTagEnd += lpszTag;
	strTagEnd += _T('>');

	const int iTagEndLen = strTagEnd.GetLength ();

	int iIndexEnd =  -1;
	int nBalanse = 1;
	for (int i = iStart; i < iBufLen - iTagEndLen + 1; i ++)
	{
		if (strBuffer [i] != '<')
		{
			continue;
		}

		if (i < iBufLen - iTagStartLen &&
			_tcsncmp (strBuffer.Mid (i), strTagStart, iTagStartLen) == 0)
		{
			i += iTagStartLen - 1;
			nBalanse ++;
			continue;
		}

		if (_tcsncmp (strBuffer.Mid (i), strTagEnd, iTagEndLen) == 0)
		{
			nBalanse --;
			if (nBalanse == 0)
			{
				iIndexEnd = i;
				break;
			}

			i += iTagEndLen - 1;
		}
	}

	if (iIndexEnd == -1 || iStart > iIndexEnd)
	{
		return FALSE;
	}

	strTag = strBuffer.Mid (iStart, iIndexEnd - iStart);
	strTag.TrimLeft ();
	strTag.TrimRight ();

	strBuffer.Delete (iIndexStart, iIndexEnd + iTagEndLen - iIndexStart);
	return TRUE;
}
//***************************************************************************************
BOOL CBCGPXMLNode::ReadFromBuffer (CString& strBuffer)
{
	m_strValue.Empty ();

	while (!m_lstChildren.IsEmpty ())
	{
		delete m_lstChildren.RemoveHead ();
	}

	if (strBuffer [0] != '<')
	{
		ASSERT(FALSE);
		return FALSE;
	}

	int iTagEnd = strBuffer.Find ('>');
	if (iTagEnd < 0)
	{
		ASSERT(FALSE);
		return FALSE;
	}

	m_strName = strBuffer.Mid (1, iTagEnd - 1);

	CString strTag;
	if (!ExcludeTag (strBuffer, m_strName, strTag))
	{
		ASSERT (FALSE);
		return FALSE;
	}

	if (strTag.IsEmpty ())
	{
		return TRUE;
	}

	if (strTag [0] == '\"')
	{
		ASSERT (strTag [strTag.GetLength () - 1] == '\"');
		m_strValue = strTag.Mid (1, strTag.GetLength () - 2);

		return TRUE;
	}

	if (strTag [0] != '<')
	{
		ASSERT(FALSE);
		return FALSE;
	}

	while (!strTag.IsEmpty ())
	{
		CBCGPXMLNode* pChild = new CBCGPXMLNode;
		if (!pChild->ReadFromBuffer (strTag))
		{
			delete pChild;
			return FALSE;
		}

		AddChild (pChild);
	}

	return TRUE;
}
Пример #14
0
void CRedirectHTTP_Thread::StartRedirect()
{	m_sServerSocket=INVALID_SOCKET; m_iConnections=0;
	int iErr=1; bool bFinished=false; while(!bFinished) {
		url uURL; char szBuffer[MAX_PATH]; bool bGet=false;

		// Receive the proxy request
		if(!recv_line_irc(m_sClientSocket, szBuffer, MAX_PATH, NULL)) { bFinished=true; break; }
		CString sBuffer(szBuffer);
		// Fail if there is no url
		// if(!sBuffer.Token(1, " ").Compare("")) { bFinished=true; break; }

		if(!sBuffer.Compare("")) { bFinished=true; break; }

		if(!sBuffer.Token(0, " ").CompareNoCase("GET")) { // GET method
			bGet=true;
			// Parse the url
			if(!ParseURL(sBuffer.Token(1, " ").CStr(), &uURL)) { bFinished=true; break; }
			// Fail if the protocol isnt http
			if(uURL.sProto.Compare("http")) { bFinished=true; break; }
		} else if(!sBuffer.Token(0, " ").CompareNoCase("CONNECT")) { // CONNECT method
			bGet=false;
			// Parse the host
			uURL.sProto.Assign("connect");
			uURL.sReq.Assign("");
			uURL.sHost.Assign(sBuffer.Token(1, " ").Token(0, ":"));
			if(!sBuffer.Token(1, " ").Token(1, ":").CStr()) { bFinished=true; break; }
			uURL.iPort=atoi(sBuffer.Token(1, " ").Token(1, ":").CStr());
			if(!uURL.iPort) uURL.iPort=80; }

		// Get the rest of the request
		CString sMethod(sBuffer.Token(0, " ")); if(!sMethod.Compare("")) { bFinished=true; break; }
		CString sHTTPVer(sBuffer.Token(2, " ")); if(!sHTTPVer.Compare("")) { bFinished=true; break; }
		CString sOldHost(uURL.sHost);

#ifdef DBGCONSOLE
		if(bGet)
			g_cMainCtrl.m_cConsDbg.Log(5, "CRedirectHTTP(0x%8.8Xh): %s %s %s...\n", m_pRedirHTTP, sMethod.CStr(), uURL.sReq.CStr(), sHTTPVer.CStr());
		else
			g_cMainCtrl.m_cConsDbg.Log(5, "CRedirectHTTP(0x%8.8Xh): %s %s:%d %s...\n", m_pRedirHTTP, sMethod.CStr(), uURL.sHost.CStr(), uURL.iPort, sHTTPVer.CStr());
#endif

		char szBuf[4096]; strcpy(szBuf, "bla");
		if(bGet) {
			if(xRead(m_sClientSocket, szBuf, sizeof(szBuf))<1)
			{	xClose(m_sClientSocket); return; }
		} else {
			while(strcmp(szBuf, "")) // Loop while headers arent finished
				if(!recv_line_irc(m_sClientSocket, szBuf, 4096, NULL)) { bFinished=true; break; }
			if(bFinished) break; }

		CString sReqBuf;
		if(bGet)
			sReqBuf.Format("%s %s %s\r\n%s", sMethod.CStr(), uURL.sReq.CStr(), sHTTPVer.CStr(), szBuf);
		else
			sReqBuf.Format("HTTP/1.0 200 Connection established\r\n\r\n");

		m_sServerSocket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(m_sServerSocket==SOCKET_ERROR || m_sServerSocket==INVALID_SOCKET)
		{	xClose(m_sClientSocket); return; }

		// Fill in sockaddr and resolve the host
		sockaddr_in ssin; memset(&ssin, 0, sizeof(ssin));
		ssin.sin_family=AF_INET; ssin.sin_port=htons(uURL.iPort);
		ssin.sin_addr.s_addr=ResolveAddress(uURL.sHost.CStr());
		if(ssin.sin_addr.s_addr==INADDR_NONE) // The host couldn't be resolved, exit
		{
#ifdef DBGCONSOLE
			g_cMainCtrl.m_cConsDbg.Log(5, "CRedirectHTTP(0x%8.8Xh): %s could not be resolved (%s)...\n", m_pRedirHTTP, uURL.sHost.CStr(), uURL.sReq.CStr());
#endif
			xClose(m_sClientSocket); xClose(m_sServerSocket); return; }

		// Connect to the server
		iErr=connect(m_sServerSocket, (sockaddr*)&ssin, sizeof(sockaddr_in));
		if(iErr==SOCKET_ERROR) // Connect failed, exit
		{	
#ifdef DBGCONSOLE
			g_cMainCtrl.m_cConsDbg.Log(5, "CRedirectHTTP(0x%8.8Xh): Cannot connect to %s:%d (%s)...\n", m_pRedirHTTP, uURL.sHost.CStr(), uURL.iPort, uURL.sReq.CStr());
#endif
			xClose(m_sClientSocket); xClose(m_sServerSocket); return; }

		if(bGet) {
			iErr=xWrite(m_sServerSocket, sReqBuf.CStr(), sReqBuf.GetLength());
			if(!iErr || iErr==SOCKET_ERROR) { xClose(m_sClientSocket); xClose(m_sServerSocket); return; }
		} else {
			iErr=xWrite(m_sClientSocket, sReqBuf.CStr(), sReqBuf.GetLength());
			if(!iErr || iErr==SOCKET_ERROR) { xClose(m_sClientSocket); xClose(m_sServerSocket); return; }
		}

		int iLen; fd_set fd;
		SET_SOCK_BLOCK(m_sClientSocket, 0); SET_SOCK_BLOCK(m_sServerSocket, 0);

		if(bGet) {
			while(true)
			{	memset(szBuffer, 0, sizeof(szBuffer));
				if(!recv_line_irc(m_sClientSocket, szBuffer, sizeof(szBuffer), NULL)) { Sleep(10); break; }
				if(strcmp(szBuffer, "")) {
					sBuffer.Assign(szBuffer);
					if(!sBuffer.Token(0, " ").Compare("GET"))
					{	// Fail if there is no url
						if(!sBuffer.Token(1, " ").Compare("")) { bFinished=true; break; }
						// Parse the url
						if(!ParseURL(sBuffer.Token(1, " ").CStr(), &uURL)) break;
						// Fail if the protocol isnt http
						if(uURL.sProto.Compare("http")) { bFinished=true; break; }
						// Get the rest of the request
						CString sMethod(sBuffer.Token(0, " ")); if(!sMethod.Compare("")) { bFinished=true; break; }
						CString sHTTPVer(sBuffer.Token(2, " ")); if(!sHTTPVer.Compare("")) { bFinished=true; break; }
						sBuffer.Format("%s %s %s\r\n", sMethod.CStr(), uURL.sReq.CStr(), sHTTPVer.CStr());
						if(uURL.sHost.Compare(sOldHost))
						{	xClose(m_sServerSocket);
							m_sServerSocket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
							if(m_sServerSocket==SOCKET_ERROR || m_sServerSocket==INVALID_SOCKET)
							{	xClose(m_sClientSocket); return; }
							
							// Fill in sockaddr and resolve the host
							sockaddr_in ssin; memset(&ssin, 0, sizeof(ssin));
							ssin.sin_family=AF_INET; ssin.sin_port=htons(uURL.iPort);
							ssin.sin_addr.s_addr=ResolveAddress(uURL.sHost.CStr());
							if(ssin.sin_addr.s_addr==INADDR_NONE) // The host couldn't be resolved, exit
							{
#ifdef DBGCONSOLE
								g_cMainCtrl.m_cConsDbg.Log(5, "CRedirectHTTP(0x%8.8Xh): %s could not be resolved (%s)...\n", m_pRedirHTTP, uURL.sHost.CStr(), uURL.sReq.CStr());
#endif
								xClose(m_sClientSocket); xClose(m_sServerSocket); return; }

							// Connect to the server
							iErr=connect(m_sServerSocket, (sockaddr*)&ssin, sizeof(sockaddr_in));
							if(iErr==SOCKET_ERROR) // Connect failed, exit
							{	
#ifdef DBGCONSOLE
								g_cMainCtrl.m_cConsDbg.Log(5, "CRedirectHTTP(0x%8.8Xh): Cannot connect to %s:%d (%s)...\n", m_pRedirHTTP, uURL.sHost.CStr(), uURL.iPort, uURL.sReq.CStr());
#endif
								xClose(m_sClientSocket); xClose(m_sServerSocket); return; }
							
							sOldHost.Assign(uURL.sHost); }
					}
					else
					{	sBuffer.Append("\r\n"); }
				if(xWrite(m_sServerSocket, sBuffer.CStr(), sBuffer.GetLength())<1) break; }

				iLen=xRead(m_sServerSocket, szBuf, sizeof(szBuf));
				if(!iLen) break; if(iLen<0 && ERRNO!=EWOULDBLOCK) { Sleep(10); break; }
				xWrite(m_sClientSocket, szBuf, iLen);
			}
		} else {
			while(true) {
				iLen=xRead(m_sClientSocket, szBuf, sizeof(szBuf));
				if(!iLen) break; if(iLen<0 && ERRNO!=EWOULDBLOCK) { Sleep(10); break; }
				xWrite(m_sServerSocket, szBuf, iLen);

				iLen=xRead(m_sServerSocket, szBuf, sizeof(szBuf));
				if(!iLen) break; if(iLen<0 && ERRNO!=EWOULDBLOCK) { Sleep(10); break; }
				xWrite(m_sClientSocket, szBuf, iLen);
			}
		}

		xClose(m_sClientSocket); xClose(m_sServerSocket);
		bFinished=true;
	}
}
Пример #15
0
void CHSShadeButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) 
{
    ASSERT (lpDrawItemStruct);
    //TRACE("* Captured: %08X\n", ::GetCapture());

    //Check if the button state in not in inconsistent mode...
    POINT mouse_position;
    if ((m_button_down) && (::GetCapture() == m_hWnd) && (::GetCursorPos(&mouse_position)))
	{
		if (::WindowFromPoint(mouse_position) == m_hWnd)
		{
			if ((GetState() & BST_PUSHED) != BST_PUSHED)
			{
				//TRACE("* Inconsistency up detected! Fixing.\n");
				SetState(TRUE);
				return;
			}
		}
		else 
		{
			if ((GetState() & BST_PUSHED) == BST_PUSHED) 
			{
				//TRACE("* Inconsistency up detected! Fixing.\n");
				SetState(FALSE);
				return;
			}
		}
	}
	
    //TRACE("* Drawing: %08x\n", lpDrawItemStruct->itemState);
	CString sCaption;
	TEXTMETRIC tm;

	CDC *pDC = CDC::FromHandle(lpDrawItemStruct->hDC);	// get device context
	RECT r = lpDrawItemStruct->rcItem;					// context rectangle
	int cx = r.right  - r.left ;						// get width
	int cy = r.bottom - r.top  ;						// get height


	GetWindowText(sCaption);							// get button text
	pDC->SetBkMode(TRANSPARENT);
	pDC->SelectObject(GetStockObject(DEFAULT_GUI_FONT)); //get text font
	pDC->GetTextMetrics(&tm);							// get font metrics
	// get top-left corner to draw the text centered on the button
	int tx = (cx-tm.tmAveCharWidth*sCaption.GetLength())/2;
	int ty = (cy-tm.tmHeight)/2;

	// Select the correct skin 
	if (lpDrawItemStruct->itemState & ODS_DISABLED)
	{	
		Draw(pDC->GetSafeHdc(),r);

		// if needed, draw the standard 3D rectangular border
		if (m_Border) pDC->DrawEdge(&r,EDGE_RAISED,BF_RECT);
		// paint the etched button text
		pDC->SetTextColor(GetSysColor(COLOR_3DHILIGHT));
		pDC->DrawText(sCaption,&r,DT_CENTER|DT_SINGLELINE|DT_VCENTER);
		//pDC->ExtTextOut(tx+1,ty+1,ETO_CLIPPED,&r,sCaption,NULL);
		pDC->SetTextColor(GetSysColor(COLOR_GRAYTEXT));
		pDC->DrawText(sCaption,&r,DT_CENTER|DT_SINGLELINE|DT_VCENTER);
		//pDC->ExtTextOut(tx,ty,ETO_CLIPPED,&r,sCaption,NULL);
	} 
	else
	{
		if (lpDrawItemStruct->itemState & ODS_SELECTED)
		{ 	
			Draw(pDC->GetSafeHdc(),r);

			// if needed, draw the standard 3D rectangular border
			if (m_Border)
				pDC->DrawEdge(&r,EDGE_SUNKEN,BF_RECT);
		}
		else 
		{				
				Draw(pDC->GetSafeHdc(),r,m_tracking);

			// if needed, draw the standard 3D rectangular border
				if (m_Border)
				{
					if (lpDrawItemStruct->itemState & ODS_DEFAULT)
					{
						pDC->DrawEdge(&r,EDGE_SUNKEN,BF_RECT);
						r.left   += 1;
						r.top    += 1;
						r.right  -= 1;
						r.bottom -= 1;
						pDC->DrawEdge(&r,EDGE_RAISED,BF_RECT);
					}
					else 
					{
						pDC->DrawEdge(&r,EDGE_RAISED,BF_RECT);
					}
				}
		}

		if ((lpDrawItemStruct->itemState & ODS_FOCUS) /*&& (m_FocusRectMargin > 0)*/)
		{
			Draw(pDC->GetSafeHdc(),r,2);
		}

		// paint the enabled button tex
		{
			pDC->SetTextColor(m_TextColor);
			pDC->DrawText(sCaption,&r,DT_CENTER|DT_SINGLELINE|DT_VCENTER);
			//pDC->ExtTextOut(tx,ty,ETO_CLIPPED,&r,sCaption,NULL);
		}
	}
}
Пример #16
0
// Performs login to MMS service
// Input:	csLogin=String with user's telephone number
//			csPwd=String with user's password
// Returns:	UserId
CString CMMSSender::Login(CString csLogin, CString csPwd)
{
	if(m_pSession)
	{
		m_pSession->Close();
		delete m_pSession;
		m_pSession = NULL;

		DWORD SessionFlags = INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_IGNORE_CERT_CN_INVALID;
		m_pSession = new CInternetSession(NULL,1,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,SessionFlags);

		CString csUserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
		char strUserAgent[255];
		strcpy(strUserAgent,csUserAgent);
		m_pSession->SetOption(INTERNET_OPTION_USER_AGENT,(void*)strUserAgent,strlen(strUserAgent),0);
	}

	CString csData;
	CString csURL;

	CString csCookie;

    CString csHeaders;
	CString csRetHeaders;
	CString csRetData;

    // We try to access http://multimedia.movistar.es/
    csHeaders = "Connection: Keep-Alive\r\n";

	csURL.Format("http://%s/",m_csServer);
	UINT nCode=GetHTTP(csURL,csHeaders,csRetHeaders,csRetData);
	if(nCode == 302)
	{
        //We are redirected
		csCookie = GetCookies(csRetHeaders);
		CString csCookieSession=csCookie;

		// Login data posting
		csData.Format("TM_ACTION=LOGIN&variant=mensajeria&locale=sp-SP&client=html-msie-7-winxp&directMessageView=&uid=&uidl=&folder=&remoteAccountUID=&login=1&TM_LOGIN=%s&TM_PASSWORD=%s",csLogin,csPwd);
		csHeaders = "Content-type: application/x-www-form-urlencoded\r\n"
					"Accept-Encoding: identity\r\n"
					"Connection: Keep-Alive\r\n";

		CString csCookieSessionValue;
		int nPosValue=csCookieSession.Find("=");
		if(nPosValue!=-1)
		{
			csCookieSessionValue=csCookieSession.Mid(nPosValue+1);
			m_csUser = csCookieSessionValue;
		}
		csURL.Format("http://%s/do/dologin;jsessionid=%s",m_csServer,csCookieSessionValue);
		nCode=PostHTTP(csURL,(BYTE*)csData.GetBuffer(0),csData.GetLength(),csHeaders,csRetHeaders,csRetData);

		CString csMoreCookies=GetCookies(csRetHeaders);
		m_csCookie=csCookieSession + "; " + csMoreCookies;

		csHeaders = "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n"
					"Accept-Encoding: identity\r\n"
					"Connection: Keep-Alive\r\n";
		csHeaders += "Cookie: "+m_csCookie+"\r\n";
		csURL.Format("http://%s/do/multimedia/create?l=sp-SP&v=mensajeria",m_csServer);
		nCode=GetHTTP(csURL,csHeaders,csRetHeaders,csRetData);
	}

	m_csLogin = csLogin;

	return m_csUser;
}
Пример #17
0
static void PrintPiecesThread(void* pv)
{
	CFrameWndEx* pFrame = (CFrameWndEx*)pv;
	CView* pView = pFrame->GetActiveView();
	CPrintDialog PD(FALSE, PD_ALLPAGES|PD_USEDEVMODECOPIES|PD_NOPAGENUMS|PD_NOSELECTION, pFrame);

	if (theApp.DoPrintDialog(&PD) != IDOK)
		return; 

	if (PD.m_pd.hDC == NULL)
		return;

	Project* project = lcGetActiveProject();
	ObjArray<lcPiecesUsedEntry> PiecesUsed;

	project->GetPiecesUsed(PiecesUsed);
	PiecesUsed.Sort(PiecesUsedSortFunc, NULL);

	// gather file to print to if print-to-file selected
	CString strOutput;
	if (PD.m_pd.Flags & PD_PRINTTOFILE)
	{
		CString strDef(MAKEINTRESOURCE(AFX_IDS_PRINTDEFAULTEXT));
		CString strPrintDef(MAKEINTRESOURCE(AFX_IDS_PRINTDEFAULT));
		CString strFilter(MAKEINTRESOURCE(AFX_IDS_PRINTFILTER));
		CString strCaption(MAKEINTRESOURCE(AFX_IDS_PRINTCAPTION));
		CFileDialog dlg(FALSE, strDef, strPrintDef,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, strFilter);
		dlg.m_ofn.lpstrTitle = strCaption;
		if (dlg.DoModal() != IDOK)
			return;
		strOutput = dlg.GetPathName();
	}

	CString DocName;
	char* Ext = strrchr(project->m_strTitle, '.');
	DocName.Format("LeoCAD - %.*s BOM", Ext ? Ext - project->m_strTitle : strlen(project->m_strTitle), project->m_strTitle);
	DOCINFO docInfo;
	memset(&docInfo, 0, sizeof(DOCINFO));
	docInfo.cbSize = sizeof(DOCINFO);
	docInfo.lpszDocName = DocName;
	CString strPortName;

	int nFormatID;
	if (strOutput.IsEmpty())
	{
		docInfo.lpszOutput = NULL;
		strPortName = PD.GetPortName();
		nFormatID = AFX_IDS_PRINTONPORT;
	}
	else
	{
		docInfo.lpszOutput = strOutput;
		AfxGetFileTitle(strOutput, strPortName.GetBuffer(_MAX_PATH), _MAX_PATH);
		nFormatID = AFX_IDS_PRINTTOFILE;
	}

	SetAbortProc(PD.m_pd.hDC, _AfxAbortProc);
	pFrame->EnableWindow(FALSE);
	CPrintingDialog dlgPrintStatus(NULL);

	CString strTemp;
	dlgPrintStatus.SetDlgItemText(AFX_IDC_PRINT_DOCNAME, DocName);
	dlgPrintStatus.SetDlgItemText(AFX_IDC_PRINT_PRINTERNAME, PD.GetDeviceName());
	AfxFormatString1(strTemp, nFormatID, strPortName);
	dlgPrintStatus.SetDlgItemText(AFX_IDC_PRINT_PORTNAME, strTemp);
	dlgPrintStatus.ShowWindow(SW_SHOW);
	dlgPrintStatus.UpdateWindow();

	if (StartDoc(PD.m_pd.hDC, &docInfo) == SP_ERROR)
	{
		pFrame->EnableWindow(TRUE);
		dlgPrintStatus.DestroyWindow();
		AfxMessageBox(AFX_IDP_FAILED_TO_START_PRINT);
		return;
	}

	int ResX = GetDeviceCaps(PD.m_pd.hDC, LOGPIXELSX);
	int ResY = GetDeviceCaps(PD.m_pd.hDC, LOGPIXELSY);

	CRect RectDraw(0, 0, GetDeviceCaps(PD.m_pd.hDC, HORZRES), GetDeviceCaps(PD.m_pd.hDC, VERTRES));
	DPtoLP(PD.m_pd.hDC, (LPPOINT)(RECT*)&RectDraw, 2);
	RectDraw.DeflateRect((int)(ResX*(float)theApp.GetProfileInt("Default","Margin Left", 50)/100.0f),
	                     (int)(ResY*(float)theApp.GetProfileInt("Default","Margin Top", 50)/100.0f),
	                     (int)(ResX*(float)theApp.GetProfileInt("Default","Margin Right", 50)/100.0f),
	                     (int)(ResY*(float)theApp.GetProfileInt("Default","Margin Bottom", 50)/100.0f));

	CRect HeaderRect = RectDraw;
 	HeaderRect.top -= (int)(ResY*theApp.GetProfileInt("Default", "Margin Top", 50) / 200.0f);
	HeaderRect.bottom += (int)(ResY*theApp.GetProfileInt("Default", "Margin Bottom", 50) / 200.0f);

	int RowsPerPage = AfxGetApp()->GetProfileInt("Default", "Catalog Rows", 10);
	int ColsPerPage = AfxGetApp()->GetProfileInt("Default", "Catalog Columns", 3);
	int PicHeight = RectDraw.Height() / RowsPerPage;
	int PicWidth = RectDraw.Width() / ColsPerPage;
	int TotalRows = (PiecesUsed.GetSize() + ColsPerPage - 1) / ColsPerPage;
	int TotalPages = (TotalRows + RowsPerPage - 1) / RowsPerPage;
	int RowHeight = RectDraw.Height() / RowsPerPage;
	int ColWidth = RectDraw.Width() / ColsPerPage;

	PD.m_pd.nMinPage = 1;
	PD.m_pd.nMaxPage = TotalPages + 1;

	UINT EndPage = PD.m_pd.nToPage;
	UINT StartPage = PD.m_pd.nFromPage;
	if (PD.PrintAll())
	{
		EndPage = PD.m_pd.nMaxPage;
		StartPage = PD.m_pd.nMinPage;
	}

	lcClamp(EndPage, PD.m_pd.nMinPage, PD.m_pd.nMaxPage);
	lcClamp(StartPage, PD.m_pd.nMinPage, PD.m_pd.nMaxPage);
	int StepPage = (EndPage >= StartPage) ? 1 : -1;

	VERIFY(strTemp.LoadString(AFX_IDS_PRINTPAGENUM));

	// begin page printing loop
	BOOL bError = FALSE;

	// Creating Compatible Memory Device Context
	CDC *pMemDC = new CDC;
	if (!pMemDC->CreateCompatibleDC(pView->GetDC()))
		return;

	BITMAPINFO bi;
	ZeroMemory(&bi, sizeof(BITMAPINFO));
	bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	bi.bmiHeader.biWidth = PicWidth;
	bi.bmiHeader.biHeight = PicHeight;
	bi.bmiHeader.biPlanes = 1;
	bi.bmiHeader.biBitCount = 24;
	bi.bmiHeader.biCompression = BI_RGB;
	bi.bmiHeader.biSizeImage = PicWidth * PicHeight * 3;
	bi.bmiHeader.biXPelsPerMeter = 2925;
	bi.bmiHeader.biYPelsPerMeter = 2925;
	bi.bmiHeader.biClrUsed = 0;
	bi.bmiHeader.biClrImportant = 0;
	
	LPBITMAPINFOHEADER lpbi[1];

	HBITMAP hBm, hBmOld;
    hBm = CreateDIBSection(pView->GetDC()->GetSafeHdc(), &bi, DIB_RGB_COLORS, (void **)&lpbi, NULL, (DWORD)0);
	if (!hBm)
		return;
	hBmOld = (HBITMAP)::SelectObject(pMemDC->GetSafeHdc(), hBm);

	PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_BITMAP | PFD_SUPPORT_OPENGL | PFD_SUPPORT_GDI,
			PFD_TYPE_RGBA, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 };
	int pixelformat = ChoosePixelFormat(pMemDC->m_hDC, &pfd);
	DescribePixelFormat(pMemDC->m_hDC, pixelformat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
	SetPixelFormat(pMemDC->m_hDC, pixelformat, &pfd);
	HGLRC hmemrc = wglCreateContext(pMemDC->GetSafeHdc());
	wglMakeCurrent(pMemDC->GetSafeHdc(), hmemrc);

	GL_DisableVertexBufferObject();
	float Aspect = (float)PicWidth/(float)PicHeight;

	glViewport(0, 0, PicWidth, PicHeight);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_POLYGON_OFFSET_FILL);
	glPolygonOffset(0.5f, 0.1f);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glClearColor(1, 1, 1, 1); 

	LOGFONT lf;
	memset(&lf, 0, sizeof(LOGFONT));
	lf.lfHeight = -MulDiv(12, ResY, 72);
	lf.lfWeight = FW_REGULAR;
	lf.lfCharSet = DEFAULT_CHARSET;
	lf.lfQuality = PROOF_QUALITY;
	strcpy (lf.lfFaceName , "Arial");

	HFONT HeaderFont = CreateFontIndirect(&lf);
	HFONT OldFont = (HFONT)SelectObject(PD.m_pd.hDC, HeaderFont);
	SetBkMode(PD.m_pd.hDC, TRANSPARENT);
	SetTextColor(PD.m_pd.hDC, 0x000000);
	SetTextAlign(PD.m_pd.hDC, TA_CENTER|TA_NOUPDATECP);

	DWORD PrintOptions = AfxGetApp()->GetProfileInt("Settings", "Print", PRINT_NUMBERS | PRINT_BORDER/*|PRINT_NAMES*/);
	bool DrawNames = 1;//(PrintOptions & PRINT_NAMES) != 0;
	bool Horizontal = 1;//(PrintOptions & PRINT_HORIZONTAL) != 0;

	pMemDC->SetTextColor(0x000000);
	pMemDC->SetBkMode(TRANSPARENT);
//	lf.lfHeight = -MulDiv(40, GetDeviceCaps(pMemDC->m_hDC, LOGPIXELSY), 72);
//	lf.lfWeight = FW_BOLD;
	HFONT CatalogFont = CreateFontIndirect(&lf);
	lf.lfHeight = -MulDiv(80, GetDeviceCaps(pMemDC->m_hDC, LOGPIXELSY), 72);
	HFONT CountFont = CreateFontIndirect(&lf);
	HFONT OldMemFont = (HFONT)SelectObject(pMemDC->m_hDC, CatalogFont);
	HPEN hpOld = (HPEN)SelectObject(pMemDC->m_hDC, GetStockObject(BLACK_PEN));

	for (UINT CurPage = StartPage; CurPage != EndPage; CurPage += StepPage)
	{
		TCHAR szBuf[80];
		wsprintf(szBuf, strTemp, CurPage);
		dlgPrintStatus.SetDlgItemText(AFX_IDC_PRINT_PAGENUM, szBuf);
		if (::StartPage(PD.m_pd.hDC) < 0)
		{
			bError = TRUE;
			break;
		}

		// Draw header and footer.
		SelectObject(PD.m_pd.hDC, HeaderFont);

		CString Header;
		UINT Align;

		FormatHeader(Header, Align, AfxGetApp()->GetProfileString("Default", "Catalog Header", ""), project->m_strTitle, project->m_strAuthor, project->m_strDescription, CurPage, TotalPages);
		Align |= DT_TOP|DT_SINGLELINE;

		DrawText(PD.m_pd.hDC, (LPCTSTR)Header, Header.GetLength(), HeaderRect, Align);

		FormatHeader(Header, Align, AfxGetApp()->GetProfileString("Default", "Catalog Footer", "Page &P"), project->m_strTitle, project->m_strAuthor, project->m_strDescription, CurPage, TotalPages);
		Align |= DT_BOTTOM|DT_SINGLELINE;

		DrawText(PD.m_pd.hDC, (LPCTSTR)Header, Header.GetLength(), HeaderRect, Align);

		int StartPiece = (CurPage - 1) * RowsPerPage * ColsPerPage;
		int EndPiece = lcMin(StartPiece + RowsPerPage * ColsPerPage, PiecesUsed.GetSize());

		for (int CurPiece = StartPiece; CurPiece < EndPiece; CurPiece++)
		{
			FillRect(pMemDC->m_hDC, CRect(0, PicHeight, PicWidth, 0), (HBRUSH)GetStockObject(WHITE_BRUSH));
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			PieceInfo* pInfo = PiecesUsed[CurPiece].Info;
			pInfo->ZoomExtents(30.0f, Aspect);

			pInfo->RenderPiece(PiecesUsed[CurPiece].ColorIndex);
			glFinish();

			// Draw description text at the bottom.
			CRect TextRect(0, 0, PicWidth, PicHeight);
	
			if (DrawNames)
			{
				SelectObject(pMemDC->m_hDC, CatalogFont);
				pMemDC->DrawText(pInfo->m_strDescription, strlen(pInfo->m_strDescription), TextRect, DT_CALCRECT | DT_WORDBREAK);

				TextRect.OffsetRect(0, PicHeight - TextRect.Height() - 5);
				pMemDC->DrawText(pInfo->m_strDescription, strlen(pInfo->m_strDescription), TextRect, DT_WORDBREAK);
			}

			// Draw count.
			SelectObject(pMemDC->m_hDC, CountFont);
			TextRect = CRect(0, 0, PicWidth, TextRect.top);
			TextRect.DeflateRect(5, 5);

			char CountStr[16];
			sprintf(CountStr, "%dx", PiecesUsed[CurPiece].Count);
			pMemDC->DrawText(CountStr, strlen(CountStr), TextRect, DT_BOTTOM | DT_LEFT | DT_SINGLELINE);

			LPBITMAPINFOHEADER lpbi[1];
			lpbi[0] = (LPBITMAPINFOHEADER)GlobalLock(MakeDib(hBm, 24));
			BITMAPINFO bi;
			ZeroMemory(&bi, sizeof(BITMAPINFO));
			memcpy (&bi.bmiHeader, lpbi[0], sizeof(BITMAPINFOHEADER));
			SetStretchBltMode(PD.m_pd.hDC, COLORONCOLOR);

			int CurRow, CurCol;

			if (Horizontal)
			{
				CurRow = (CurPiece - StartPiece) / ColsPerPage;
				CurCol = (CurPiece - StartPiece) % ColsPerPage;
			}
			else
			{
				CurRow = (CurPiece - StartPiece) % RowsPerPage;
				CurCol = (CurPiece - StartPiece) / RowsPerPage;
			}
			
			int Left = RectDraw.left + ColWidth * CurCol + (ColWidth - PicWidth) / 2;
			int Top = RectDraw.top + RowHeight * CurRow + (RowHeight - PicHeight) / 2;

			StretchDIBits(PD.m_pd.hDC, Left, Top, PicWidth, PicHeight, 0, 0, PicWidth, PicHeight, 
			              (LPBYTE)lpbi[0] + lpbi[0]->biSize + lpbi[0]->biClrUsed * sizeof(RGBQUAD), &bi, DIB_RGB_COLORS, SRCCOPY);
			if (lpbi[0])
				GlobalFreePtr(lpbi[0]);
		}

		if (::EndPage(PD.m_pd.hDC) < 0 || !_AfxAbortProc(PD.m_pd.hDC, 0))
		{
			bError = TRUE;
			break;
		}
	}

	SelectObject(pMemDC->m_hDC, hpOld);
	SelectObject(PD.m_pd.hDC, OldFont);
	DeleteObject(HeaderFont);
	SelectObject(pMemDC->m_hDC, OldMemFont);
	DeleteObject(CatalogFont);
	DeleteObject(CountFont);

	GL_EnableVertexBufferObject();
	wglMakeCurrent(NULL, NULL);
	wglDeleteContext(hmemrc);
	SelectObject(pMemDC->GetSafeHdc(), hBmOld);
	DeleteObject(hBm);
	delete pMemDC;

	if (!bError)
		EndDoc(PD.m_pd.hDC);
	else
		AbortDoc(PD.m_pd.hDC);

	pFrame->EnableWindow();
	dlgPrintStatus.DestroyWindow();

	if (PD.m_pd.hDC != NULL)
    {
		::DeleteDC(PD.m_pd.hDC);
		PD.m_pd.hDC = NULL;
    }
}
Пример #18
0
// Inserts a video object in MMS message
// Input:	csObjPath=String with file path
void CMMSSender::InsertVideo(CString csObjPath)
{
	CMapStringToString mssContentType;
	mssContentType.SetAt("avi","video/avi");
	mssContentType.SetAt("asf","video/x-ms-asf");
	mssContentType.SetAt("mpg","video/mpeg");
	mssContentType.SetAt("mpeg","video/mpeg");
	mssContentType.SetAt("wmv","video/x-ms-wmv");

	CString csContentType;
	int nPosPunto=csObjPath.ReverseFind('.');
	if(nPosPunto!=-1)
	{
		CString csExtension=csObjPath.Mid(nPosPunto+1);
		mssContentType.Lookup(csExtension,csContentType);

		if(csContentType.IsEmpty())
			return;
	}

	CString csData;
	CString csURL;

	CString csCookie;

	CString csHeaders;
	CString csRetHeaders;
	CString csRetData;

	BYTE* pbtFile=(BYTE*)malloc(OBJ_BUFFER_SIZE);
	memset(pbtFile,0,OBJ_BUFFER_SIZE);

	BYTE* pbtContents=(BYTE*)malloc(OBJ_BUFFER_SIZE);
	memset(pbtContents,0,OBJ_BUFFER_SIZE);
	int nPosicionDatos=0;

	CString csSeparator="---------------------------7d77df567a4b9";

	// Object data generation
	CString csFilenamePart;
	csFilenamePart.Format("--%s\r\nContent-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n",csSeparator,csObjPath,csContentType);
	memcpy(&pbtContents[nPosicionDatos],csFilenamePart.GetBuffer(0),csFilenamePart.GetLength());
	nPosicionDatos+=csFilenamePart.GetLength();

	CFile fl;
	BOOL bRes=fl.Open(csObjPath,CFile::modeRead);
	if(bRes)
	{
		int nLeidos=fl.Read(pbtFile,OBJ_BUFFER_SIZE);
		fl.Close();

		memcpy(&pbtContents[nPosicionDatos],pbtFile,nLeidos);
		nPosicionDatos+=nLeidos;
	}

	CString csFinal;
	csFinal.Format("\r\n--%s--\r\n",csSeparator);
	memcpy(&pbtContents[nPosicionDatos],csFinal.GetBuffer(0),csFinal.GetLength());
	nPosicionDatos+=csFinal.GetLength();

    CString csContentType2;
	csContentType2.Format("multipart/form-data; boundary=%s",csSeparator);
	csHeaders = "Accept-Encoding: gzip, deflate\r\n"
				"Accept-Language: es\r\n"
				"Accept: */*\r\n"
				"Connection: Keep-Alive\r\n";
	csHeaders += "Content-type: "+csContentType2+"\r\n";
	csHeaders += "Cookie: "+m_csCookie+"\r\n";
	csURL.Format("http://%s/do/multimedia/uploadEnd",m_csServer);
	UINT nCode=PostHTTP(csURL,pbtContents,nPosicionDatos,csHeaders,csRetHeaders,csRetData);

	free(pbtFile);
	free(pbtContents);
}
Пример #19
0
void CCardView::OnCardServer()
{
	// Some configurations do not support online greetings ("card server").
	if (!GetConfiguration()->SupportsCardServer())
	{
		return;
	}

	// Get our document.
	CPmwDoc* pDoc = GetDocument();

	if(GetGlobalContentManager()->CheckAccountStatus())
	{
		CString strID = GetGlobalContentManager()->GetAccountID();
		if(strID != "")
		{
			// Put up the card server dialog.

			CCardServerDialog Dialog(this);

			Dialog.m_ctTime = CTime::GetCurrentTime();
			if (Dialog.DoModal() == IDOK)
			{
				// Put up the disclaimer dialog.
				CCardServerDisclaimer Disclaimer(this);

				if (Disclaimer.DoModal() == IDOK)
				{
					// Create the directory we want to use as our FTP source.
					CString csDir = pDoc->GetPathManager()->ExpandPath("[[U]]\\NETCARD");

					if (!Util::MakeDirectory(csDir))
					{
						// Not able to make the directory.
						// LPCSTR pFormat = "Can't create the directory\n%s";
						LPCSTR pFormat = GET_PMWAPP()->GetResourceStringPointer(IDS_ErrCreateDirectory);
						CString csMessage;
						csMessage.Format(pFormat, (LPCSTR)csDir);
						AfxMessageBox(csMessage);
						return;
					}

					// Construct the text file.
					CString csTextFile;
					Util::ConstructPath(csTextFile, csDir, "INFO.INI");

					CFile cfText;
					CString csVersion;
					CString csPPN;
					TRY
					{
						CFileException e;
						//if (!cfText.Open(csTextFile,
						//					  CFile::modeCreate
						//							| CFile::modeWrite,
						//					  &e))
						//{
						//	AfxThrowFileException(e.m_cause, e.m_lOsError);
						//}

						//do the time stuff 
						
						//time zone difference from PST
						struct _timeb tstruct;
						_ftime( &tstruct );
						int timecorrection = PacificTimeCorrection(tstruct.timezone);
						
						//get date of delivery - include current time
						struct tm when;   
						CString strDate;
						CTime testtime = CTime::GetCurrentTime();
						when = *testtime.GetLocalTm(NULL);

						SYSTEMTIME sysTime = *Dialog.GetTime();
						
						if((when.tm_mday != sysTime.wDay) || (when.tm_mon != (sysTime.wMonth - 1)))
						{
							when.tm_mday = sysTime.wDay;
							when.tm_mon = sysTime.wMonth - 1;

							ConvertToPST(&when, timecorrection);

							CString str_ampm = "AM";
						  
							if( when.tm_hour > 12 )        /* Set up extension. */
									 str_ampm = "PM";
							if( when.tm_hour > 12 )        /* Convert from 24-hour */
									 when.tm_hour -= 12;    /*   to 12-hour clock.  */
							if( when.tm_hour == 0 )        /*Set hour to 12 if midnight. */
									 when.tm_hour = 12;
							
							strDate.Format("%d/%d/%d %d:%d:%d%s", 
													(int)((int)when.tm_mon + 1),when.tm_mday,when.tm_year,when.tm_hour,when.tm_min,when.tm_sec,str_ampm);   
						}
						else
						{
							strDate = "";
						}
						
						CString strPSTCorrection;
						strPSTCorrection.Format("%d", timecorrection);   

						// Construct the version string.
						CString csEol = "\r\n";
						csVersion = GetConfiguration()->ReplacementText('T');
						csVersion += ' ';
						csVersion += GET_PMWAPP()->GetVersion();

						csPPN = GET_PMWAPP()->GetParentPartNumber();

						WritePrivateProfileString( "UserData", "UserId",
													GetGlobalContentManager()->GetAccountID(), csTextFile);
						
						WritePrivateProfileString( "UserData", "Description",
													csVersion, csTextFile);

						WritePrivateProfileString( "UserData", "SenderEmail",
													Dialog.m_csFrom, csTextFile);

						WritePrivateProfileString( "UserData", "RecipientEmail",
													Dialog.m_csTo, csTextFile);

						WritePrivateProfileString( "UserData", "sku",
													csPPN, csTextFile);


						WritePrivateProfileString( "CardData", "Title",
													Dialog.m_csTitle, csTextFile);

						WritePrivateProfileString( "CardData", "Date",
													strDate, csTextFile);

						WritePrivateProfileString( "CardData", "Offset",
													strPSTCorrection, csTextFile);


		#if 0 
						// Write version
						cfText.Write(csVersion, csVersion.GetLength());
						cfText.Write(csEol, csEol.GetLength());
						// Write "from" email address
						cfText.Write(Dialog.m_csFrom, Dialog.m_csFrom.GetLength());
						cfText.Write(csEol, csEol.GetLength());
						// Write "to" email address
						cfText.Write(Dialog.m_csTo, Dialog.m_csTo.GetLength());
						cfText.Write(csEol, csEol.GetLength());
						// Write Parent Part Number
						cfText.Write(csPPN, csPPN.GetLength());
						cfText.Write(csEol, csEol.GetLength());
		#endif

						//cfText.Close();
					}
					CATCH_ALL(e)
					{
						// Could not write the text file. Complain.
						// LPCSTR pFormat = "Can't create the file\n%s";
						LPCSTR pFormat = GET_PMWAPP()->GetResourceStringPointer(IDS_ErrCreateFile);
						CString csMessage;
						csMessage.Format(pFormat, (LPCSTR)csTextFile);
						AfxMessageBox(csMessage);
						return;
					}
					END_CATCH_ALL

					// Figure out how big we want the panels to be.
					CPoint cpFrontDims;
					CPoint cpInsideDims;

					PBOX World;
					pDoc->get_panel_world(&World, CARD_PANEL_Front);

					// Fit the front panel into a 425x425 square.
					PPNT FrontDims;
					FrontDims.x = World.x1 - World.x0;
					FrontDims.y = World.y1 - World.y0;

					double dScale = 425.0/(double)FrontDims.x;
					double dYScale = 425.0/(double)FrontDims.y;
					if (dScale > dYScale) dScale = dYScale;

					cpFrontDims.x = (int)((double)FrontDims.x*dScale);
					cpFrontDims.y = (int)((double)FrontDims.y*dScale);

					pDoc->get_panel_world(&World, CARD_PANEL_Inside);

					cpInsideDims.x = (int)((double)(World.x1-World.x0)*dScale);
					cpInsideDims.y = (int)((double)(World.y1-World.y0)*dScale);

					TRACE("Front: %d, %d; Inside: %d, %d\n",
							cpFrontDims.x, cpFrontDims.y,
							cpInsideDims.x, cpInsideDims.y);

					BOOL fSuccess = FALSE;

					CCardServerProgressDialog ProgressDialog(AfxGetMainWnd());

					CString csName;
					Util::ConstructPath(csName, csDir, "front.gif");
					ProgressDialog.SetStatus(IDS_BuildingFront);
					if (DumpPanel(CARD_PANEL_Front, csName, cpFrontDims))
					{
						ProgressDialog.SetStatus(IDS_BuildingInside);
						Util::ConstructPath(csName, csDir, "inside.gif");
						if(DumpPanel(CARD_PANEL_Inside, csName, cpInsideDims))
   						fSuccess = TRUE;
					}

					if (!fSuccess)
					{
						// "Can't create card pictures."
						AfxMessageBox(GET_PMWAPP()->GetResourceStringPointer(IDS_ErrWriteCardPictures));
						return;
					}

					// Now, invoke the DLL to write the data.
					CCardServerDLL DLL;
		#ifdef WIN32
					CString csDLLName = pDoc->GetPathManager()->ExpandPath("FTP32.DLL");
		#else
					CString csDLLName = pDoc->GetPathManager()->ExpandPath("FTP16.DLL");
		#endif
					// Startup the dialog.
					if (DLL.Startup(csDLLName))
					{
						if(CheckForValidConnection()){
							
							// Put up our progress dialog.
							// Send the files.
							int nResult = DLL.SendFiles(csDir, ProgressDialog);

							// Take down the progress dialog now.
							ProgressDialog.DestroyWindow();

							// Shut down the DLL.
							DLL.Shutdown();

							CPmwDialog Dialog(nResult == 0 ? IDD_CARD_SERVER_SUCCESS : IDD_CARD_SERVER_FAILURE);
							Dialog.DoModal();
						}
					}
					else
					{
						// Not able to load the DLL. Complain.
						// LPCSTR pFormat = "The file\n%s\nis missing or bad.";
						LPCSTR pFormat = GET_PMWAPP()->GetResourceStringPointer(IDS_ErrMissingDLL);
						CString csMessage;
						csMessage.Format(pFormat, (LPCSTR)csDLLName);
						AfxMessageBox(csMessage);
					}
				}
Пример #20
0
/*******************************************************************************
 Function Name  : vShowControl
 Inputs         : nRow      - Index of the Row
                  nColumn   - Index of the Column
 Output         :   -
 Description    : This function will show the UI control to change the list item
                  text. This will get the type information from the Cmap and
                  will call approp. function to create and show that control.
 Member of      : CFlexListCtrl
 Author(s)      : Raja N
 Date Created   : 22.07.2004
 Modifications  : Raja N on 30.07.2004, Code review comments implemented
*******************************************************************************/
void CFlexListCtrl::vShowControl(int nItem, int nSubItem)
{
    // Proceed only for a valid entry
    if( nItem >= 0 && nSubItem >= 0)
    {
        SLISTINFO sInfo;
        SNUMERICINFO    sNumInfo;
        SUSERPROGINFO   sProgInfo;
        CString omStr = STR_EMPTY;
        // Got the entry type from the CMap
        if( m_omListItemType.Lookup(
                    lGetMapID(nItem, nSubItem) , sInfo) == TRUE )
        {
            // Begining of Controls creation
            m_bCreating = TRUE;
            switch( sInfo.m_eType)
            {
                    // Numeric Edit box with or with out Spin Control
                case eNumber:
                case eBuddy:
                    // Get the numeric control parameters
                    if( m_omNumDetails.Lookup( lGetMapID(nItem, nSubItem),
                                               sNumInfo ) == TRUE )
                    {
                        pomNumItem(nItem, nSubItem, sNumInfo);
                    }
                    else
                    {
                        // Numeric info is not set
                        ASSERT( FALSE );
                        // Call with default value
                        pomNumItem(nItem, nSubItem, sNumInfo);
                    }
                    break;
                    // General Edit control
                case eText:
                    pomEditItem(nItem, nSubItem);
                    break;
                    // Editalble Combo Box
                case eComboList:
                    pomComboList(nItem, nSubItem, sInfo.m_omEntries);
                    break;
                    // Non - Editable combo box
                case eComboItem:
                    pomComboItem(nItem, nSubItem, sInfo.m_omEntries);
                    break;
                    // User function will be executed
                case eUser:
                    // Get the user program pointer and parameter details
                    if( m_omUserProg.Lookup( lGetMapID(nItem, nSubItem),
                                             sProgInfo ) == TRUE )
                    {
                        sProgInfo.m_pfHandler( this,
                                               nItem,
                                               nSubItem,
                                               sProgInfo.m_pUserParam);
                    }
                    else
                    {
                        // User program information is not set
                        ASSERT( FALSE );
                    }
                    break;
                    // Toggling type control
                case eBool:
                    // Get the current text
                    omStr = GetItemText(nItem, nSubItem);
                    // Compare with the first item
                    if( sInfo.m_omEntries.GetAt(0).Compare(omStr) == 0 )
                    {
                        // Toggle the first with the second item text.
                        omStr = sInfo.m_omEntries.GetAt(1);
                    }
                    // Compare with the Second item
                    else if( sInfo.m_omEntries.GetAt(1).Compare(omStr) == 0 )
                    {
                        // Replace with the first item
                        omStr = sInfo.m_omEntries.GetAt(0);
                    }
                    // If it is not matching with these two items nothing will
                    // happen. This could be used to disable the control

                    // For boolean type this is the end of Controls creation
                    m_bCreating = FALSE;

                    // For boolean send the EndLAbleEdit message here itself
                    LV_DISPINFO lvDispInfo;
                    lvDispInfo.hdr.hwndFrom = m_hWnd;
                    lvDispInfo.hdr.idFrom = GetDlgCtrlID();
                    lvDispInfo.hdr.code = LVN_ENDLABELEDIT;
                    lvDispInfo.item.mask = LVIF_TEXT;
                    lvDispInfo.item.iItem = nItem;
                    lvDispInfo.item.iSubItem = nSubItem;
                    lvDispInfo.item.pszText = LPTSTR((LPCTSTR)omStr);
                    lvDispInfo.item.cchTextMax = omStr.GetLength();
                    SendMessage( WM_NOTIFY, GetDlgCtrlID(),(LPARAM)&lvDispInfo);
                    break;
                default:
                    // Unknown control type
                    ASSERT( FALSE );
            }
            // End of Controls
            m_bCreating = FALSE;
        }
    }
}
Пример #21
0
HRESULT GetRibbonText(BSTR * RibbonXml)
{
	LPBYTE content = NULL;
	DWORD content_length = 0;

	ASSERT_RETURN_VALUE(LoadResourceFromModule(
		AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_RESOURCE_H), L"TEXT", &content, &content_length), S_FALSE);

	CMemFile mf(content, content_length);
	CTextFileRead rdr(&mf);

	CMapStringToString replacements;

	CString line;
	while (rdr.ReadLine(line))
	{
		CSimpleArray<CString> tokens;

		CString token;
		token.Preallocate(30);

		for (LPCWSTR pos = line; *pos; ++pos)
		{
			if (*pos == ' ' || *pos == '\t')
			{
				if (!token.IsEmpty())
				{
					tokens.Add(token);
					token = CString();
				}
			}
			else
			{
				token += *pos;
			}
		}

		if (!token.IsEmpty())
			tokens.Add(token);

		if (tokens.GetSize() != 3)
			continue;

		if (tokens[0] != "#define")
			continue;

		replacements[tokens[1]] = tokens[2];
	}

	CString ribbon = LoadTextFromModule(AfxGetInstanceHandle(), IDR_RIBBON);

	for (int pos = 0; pos < ribbon.GetLength(); ++pos)
	{
		if (ribbon[pos] != '{')
			continue;

		int endpos = ribbon.Find('}', pos);
		ASSERT_CONTINUE(endpos != -1);

		CString token = ribbon.Mid(pos+1, endpos-pos-1);
		CString token_found;

		ASSERT_CONTINUE(replacements.Lookup(token, token_found));	

		ribbon.Delete(pos, endpos-pos+1);
		ribbon.Insert(pos, token_found);

		pos += (token_found.GetLength()-1);
	}

	*RibbonXml = ribbon.AllocSysString();
	return S_OK;
}
Пример #22
0
void CDlg5::PcStart()         /////////////////////电脑开机邮件提示
{
       
// TODO: Add your control notification handler code here
char buff[100];
CString curuser=_T("administrator");
CString curmailfrom;
CString currcptto=_T("15886495012");
CString curdomain=_T("domain.com");
CString strsubject=_T("电脑已开机");
CString strmessagebody=_T("您电脑已开机,正在运行Keybor");
CString strtemp;
CString	strmail;

//curuser="******";


currcptto+=_T("@qq.com");
curmailfrom.Format(_T("%s@%s"), curuser,curdomain);
memset(buff,0,100);

if(!m_socket.Create())
{
	//MessageBox("创建socket失败.");
	return;
}
if(!m_socket.Connect(_T("mx0.qq.com"),25))
{
	//MessageBox("连接服务器失败");
	return;
}
//连接成功后取得欢迎信息
m_socket.Receive(buff,100);
if (!IsSameString(buff,3,_T("220")))
{
	m_socket.Close();
	//MessageBox(buff,"220错误");
	return;
}
//发送HELO命令
sprintf_s(buff,_T("HELO %s\r\n"),curdomain);
m_socket.Send(buff,strlen(buff));
m_socket.Receive(buff,100);
if (!IsSameString(buff,3,_T("250")))
{
	m_socket.Send(_T("QUIT\r\n"),strlen(_T("QUIT\r\n")));
	//m_socket.Receive(buff,100);
	m_socket.Close();
	//MessageBox(buff,"HELO命令返回错误");
	return ;
}
//发送MAIL FROM命令
sprintf_s(buff,_T("MAIL FROM:<%s>\r\n"),curmailfrom);
m_socket.Send(buff,strlen(buff));
m_socket.Receive(buff,100);
if (!IsSameString(buff,3,_T("250")))
{
	m_socket.Send(_T("QUIT\r\n"),strlen(_T("QUIT\r\n")));
	//m_socket.Receive(buff,100);
	m_socket.Close();
	//MessageBox(buff,"MAIL FROM命令返回错误");
	return;
}
//发送RCPT TO命令
sprintf_s(buff,_T("RCPT TO:<%s>\r\n"),currcptto);
m_socket.Send(buff,strlen(buff));
m_socket.Receive(buff,100);
if (IsSameString(buff,3,_T("550")))
{
	m_socket.Send(_T("QUIT\r\n"),strlen(_T("QUIT\r\n")));
	m_socket.Receive(buff,100);
	//m_socket.Close();
	strtemp.Format(_T("你的邮件收件人地址不存在\r\n服务器信息:%s"),buff);
	//MessageBox(strtemp);
	return;
}
if (!IsSameString(buff,3,_T("250")))
{
	m_socket.Send(_T("QUIT\r\n"),strlen(_T("QUIT\r\n")));
	//m_socket.Receive(buff,100);
	m_socket.Close();
	//MessageBox(buff,"RCPT TO命令返回错误");
	return;
}
sprintf_s(buff,_T("DATA\r\n"));
m_socket.Send(buff,strlen(buff));
m_socket.Receive(buff,100);
if (!IsSameString(buff,3,_T("354")))
{
	m_socket.Send(_T("QUIT\r\n"),strlen(_T("QUIT\r\n")));
	//m_socket.Receive(buff,100);
	m_socket.Close();
	//MessageBox(buff,"DATA命令返回错误");
	return;
}

//按照格式来构造邮件
strmail=_T("");
strtemp.Format(_T("From: \"%s\" <%s>\r\n"),curuser,curmailfrom);
strmail+=strtemp;
strtemp.Format(_T("To: <%s>\r\n"),currcptto);
strmail+=strtemp;
strtemp.Format(_T("Subject: %s\r\n"),strsubject);
strmail+=strtemp;
CTime time=CTime::GetCurrentTime();
strtemp=time.Format(_T("Date: %a,%d %b %Y %X +0800\r\n")); //"Date: Thu, 30 Aug 2007 15:23:32 +0800\r\n";  //预留日期
strmail+=strtemp;
strtemp=_T("Content-Type: multipart/mixed; boundary=\"#BOUNDARY.CMAILSERVER#\"\r\n\r\n\r\n");
strmail+=strtemp;
strtemp=_T("--#BOUNDARY.CMAILSERVER#\r\n");
strmail+=strtemp;
strtemp=_T("Content-Type: text/html; charset=\"gb2312\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n");
strmail+=strtemp;
strmail+=strmessagebody;
strtemp=_T("\r\n\r\n--#BOUNDARY.CMAILSERVER#--\r\n\r\n.\r\n");
strmail+=strtemp;

//发送邮件正文

m_socket.Send(strmail,strmail.GetLength());
m_socket.Receive(buff,100);
if (!IsSameString(buff,3,_T("250")))
{
	m_socket.Send(_T("QUIT\r\n"),strlen(_T("QUIT\r\n")));
	//m_socket.Receive(buff,100);
	m_socket.Close();
	//MessageBox(buff,"DATA命令返回错误");
	return;
}
//发送QUIT命令
sprintf_s(buff,_T("QUIT\r\n"));
m_socket.Send(buff,strlen(buff));
m_socket.Receive(buff,100);
if (!IsSameString(buff,3,_T("221")))
{
	//MessageBox(buff,"QUIT命令返回错误");
	return;
}
m_socket.Close();
//MessageBox("发送成功");

}
Пример #23
0
void CIrcWnd::AddColorLine(const CString& line, CHTRichEditCtrl &wnd, COLORREF crForeground)
{
	DWORD dwMask = 0;
	int index = 0;
	int linkfoundat = 0;//This variable is to save needless costly string manipulation
	COLORREF foregroundColour = crForeground;
	COLORREF cr = foregroundColour;//set start foreground colour
	COLORREF backgroundColour = CLR_DEFAULT;
	COLORREF bgcr = backgroundColour;//set start background colour COMMENTED left for possible future use
	CString text;
	while (line.GetLength() > index)
	{
		TCHAR aChar = line[index];

		// find any hyperlinks
		if (index == linkfoundat) //only run the link finding code once it a line with no links
		{
			for (int iScheme = 0; iScheme < _countof(s_apszSchemes); /**/)
			{
				CString strLeft = line.Right(line.GetLength() - index);//make a string of what we have left
				int foundat = strLeft.Find(s_apszSchemes[iScheme].pszScheme);//get position of link -1 == not found
				if (foundat == 0) //link starts at this character
				{
					if (!text.IsEmpty()) {
						wnd.AppendColoredText(text, cr, bgcr, dwMask);
						text.Empty();
					}

					// search next space or EOL or control code
					int iLen = strLeft.FindOneOf(_T(" \t\r\n\x02\x03\x0F\x16\x1F"));
					if (iLen == -1)
					{
						// truncate some special chars from end of URL (and only from end)
						iLen = strLeft.GetLength();
						while (iLen > 0) {
							if (IsValidURLTerminationChar(strLeft[iLen - 1]))
								break;
							iLen--;
						}
						wnd.AddLine(strLeft.Left(iLen), iLen, true);
						index += iLen;
						if (index >= line.GetLength())
							return;

						aChar = line[index]; // get a new char
						break;
					}
					else
					{
						// truncate some special chars from end of URL (and only from end)
						while (iLen > 0) {
							if (IsValidURLTerminationChar(strLeft[iLen - 1]))
								break;
							iLen--;
						}
						wnd.AddLine(strLeft.Left(iLen), iLen, true);
						index += iLen;
						if (index >= line.GetLength())
							return;

						iScheme = 0; // search from the new position
						foundat = -1; // do not record this processed location as a future target location
						linkfoundat = index; // reset previous finds as iScheme=0 we re-search
						aChar = line[index]; // get a new char
					}
				}
				else
				{
					iScheme++;//only increment if not found at this position so if we find http at this position we check for further http occurances
					//foundat A Valid Position && (no valid position recorded || a farther position previously recorded)
					if (foundat != -1 && (linkfoundat == index || (index + foundat) < linkfoundat))
						linkfoundat = index + foundat;//set the next closest link to process
				}
			}
		}

		switch ((_TUCHAR)aChar)
		{
			case 0x02: // Bold
				if (!text.IsEmpty()) {
					wnd.AppendColoredText(text, cr, bgcr, dwMask);
					text.Empty();
				}
				index++;
				if (dwMask & CFM_BOLD)
					dwMask ^= CFM_BOLD;
				else
					dwMask |= CFM_BOLD;
				break;

			case 0x03: // foreground & background colour
				if (!text.IsEmpty()) {
					wnd.AppendColoredText(text, cr, bgcr, dwMask);
					text.Empty();
				}
				index++;
				if (line[index] >= _T('0') && line[index] <= _T('9'))
				{
					int iColour = (int)(line[index] - _T('0'));
					if (iColour == 1 && line[index + 1] >= _T('0') && line[index + 1] <= _T('5')) //is there a second digit
					{
						// make a two digit number
						index++;
						iColour = 10 + (int)(line[index] - _T('0'));
					}
					else if (iColour == 0 && line[index + 1] >= _T('0') && line[index + 1] <= _T('9')) //if first digit is zero and there is a second digit eg: 3 in 03
					{
						// make a two digit number
						index++;
						iColour = (int)(line[index] - _T('0'));
					}

					if (iColour >= 0 && iColour < 16)
					{
						// If the first colour is not valid, don't look for a second background colour!
						cr = s_aColors[iColour];//if the number is a valid colour index set new foreground colour
						index++;
						if (line[index] == _T(',') && line[index + 1] >= _T('0') && line[index + 1] <= _T('9'))//is there a background colour
						{
							index++;
							int iColour = (int)(line[index] - _T('0'));
							if (iColour == 1 && line[index + 1] >= _T('0') && line[index + 1] <= _T('5')) // is there a second digit
							{
								// make a two digit number
								index++;
								iColour = 10 + (int)(line[index] - _T('0'));
							}
							else if (iColour == 0 && line[index + 1] >= _T('0') && line[index + 1] <= _T('9')) // if first digit is zero and there is a second digit eg: 3 in 03
							{
								// make a two digit number
								index++;
								iColour = (int)(line[index] - _T('0'));
							}
							index++;
							if (iColour >= 0 && iColour < 16)
								bgcr = s_aColors[iColour];//if the number is a valid colour index set new foreground colour
						}
					}
				}
				else
				{
					// reset
					cr = foregroundColour;
					bgcr = backgroundColour;
				}
				break;

			case 0x0F: // attributes reset
				if (!text.IsEmpty()) {
					wnd.AppendColoredText(text, cr, bgcr, dwMask);
					text.Empty();
				}
				index++;
				dwMask = 0;
				cr = foregroundColour;
				bgcr = backgroundColour;
				break;

			case 0x16: // Reverse (as per Mirc) toggle
				// NOTE:This does not reset the bold/underline,(dwMask = 0), attributes but does reset colours 'As per mIRC 6.16!!'
				if (!text.IsEmpty()) {
					wnd.AppendColoredText(text, cr, bgcr, dwMask);
					text.Empty();
				}
				index++;
				if (cr != backgroundColour || bgcr != foregroundColour) {
					// set inverse
					cr = backgroundColour;
					bgcr = foregroundColour;
				}
				else {
					// reset fg/bk colours
					cr = foregroundColour;
					bgcr = backgroundColour;
				}
				break;

			case 0x1f: // Underlined toggle
				if (!text.IsEmpty()) {
					wnd.AppendColoredText(text, cr, bgcr, dwMask);
					text.Empty();
				}
				index++;
				if (dwMask & CFM_UNDERLINE)
					dwMask ^= CFM_UNDERLINE;
				else
					dwMask |= CFM_UNDERLINE;
				break;

			default:
				text += aChar;
				index++;
		}
	}
	if (!text.IsEmpty())
		wnd.AppendColoredText(text, cr, bgcr, dwMask);
}
Пример #24
0
void KGListCtrl::OnMouseMove(UINT nFlags, CPoint point)
{
	if (m_nToolTipFlag)
	{
		CString szTipText = _T("");
		CRect	rect;
		SIZE    size;
		int nSubItemCount = 0;
		int nItemPos	  = 0;
		int nCurSubItem	  = 0;
		LPKGLISTITEM lpItem = NULL;
		nItemPos = HitTest(point);
		KG_PROCESS_ERROR(nItemPos != -1);
		nSubItemCount = GetHeaderCtrl()->GetItemCount();
		lpItem = (LPKGLISTITEM)GetItemData(nItemPos);
		KG_PROCESS_ERROR(lpItem);

		ZeroMemory(&size ,sizeof(size));
		if (*(lpItem->szTipText) == '\0')
		{
			for (nCurSubItem = nSubItemCount - 1; nCurSubItem >= 0; nCurSubItem--)
			{
				GetSubItemRect(nItemPos, nCurSubItem, LVIR_BOUNDS, rect);
				if (rect.PtInRect(point))
				{
					szTipText = GetItemText(nItemPos, nCurSubItem);
					CDC* pDC = GetDC();
					if (pDC && pDC->m_hDC)
						GetTextExtentPoint(
						pDC->m_hDC, szTipText.GetBuffer(), szTipText.GetLength(),
						&size
						);
					if (nCurSubItem == nSubItemCount - 1)
					{
						CRect rectClient;
						GetWindowRect(rectClient);
						ScreenToClient(rectClient);
						rect.right = rectClient.right;
						if (size.cx < rect.Width())
						{
							szTipText = _T(""); 
						}
					}
					else
					{
						if (size.cx < GetColumnWidth(nCurSubItem))
						{
							szTipText = _T("");
						}
					}
					break;
				}
			}
		}
		else
		{
			szTipText = lpItem->szTipText;
		}
		m_toolTipCtrl.Activate(TRUE);
		m_toolTipCtrl.UpdateTipText(szTipText.GetBuffer(), this);
		KillTimer(1);
		SetTimer(1, 2000, NULL);
	}

Exit0:
	return CListCtrl::OnMouseMove(nFlags, point);
}
CString CHttpReqSocket::GetHTTPContent(CString strHost, CString strRequest,
									   bool* pbCancelDownload, int& nError,
									   int nApproxContentLength,									   
									   CProgressCtrl *pProgress, CWnd* pStatus,
									   CString strFilename)
{
	// init sockets
	AfxSocketInit ();
	CHttpReqSocket socket;
	nError = 0;

	// try to create the socket
	if (!socket.Create ())
	{
		nError = WSAGetLastError ();
		return "";
	}

	// try to connect to server
	if (!socket.Connect (strHost, 80))
	{
		nError = socket.GetLastError ();
		socket.Close ();
		return "";
	}

	// wait for response
	socket.Send (strRequest, strRequest.GetLength ());

	CString strRecv;
	char szBuf[4096 + 1];
	int nPos, nContLen = -1;
	int nLen = 0;

	// create and open file, if stream is to be written to a file
	// (i.e. strFilename is not empty)
	CFile file;
	bool bUseFile = !strFilename.IsEmpty ();
	bool bHeaderRead = false;
	if (bUseFile)
		file.Open (strFilename, CFile::modeCreate | CFile::modeWrite);

	// init progress control
	if (pProgress != NULL)
		pProgress->SetRange32 (0, nApproxContentLength);

	MSG msg;

	CString strStatus;

	// read http stream
	for (int nRead = 1; nRead > 0; )
	{
		if (*pbCancelDownload)
			break;

		// read from the socket
		nRead = socket.Receive (szBuf, 4096);

		switch (nRead)
		{
		case 0:
			continue;
		case SOCKET_ERROR:
			nError = socket.GetLastError ();
			break;
		default:
			if (bUseFile)
			{
				// write stream to file
				if (!bHeaderRead)
				{
					// try to get the Content-Length header
					char* pBuf = strstr (szBuf, "Content-Length:");
					if (pBuf)
						nContLen = atoi (pBuf + 15);
					if (pProgress != NULL)
						pProgress->SetRange32 (0, nContLen);

					// cut off the header (should not be saved to the file)
					pBuf = strstr (szBuf, "\r\n\r\n");
					int nHeaderLen = (int) (pBuf - szBuf);
					file.Write (pBuf + 4, nRead - nHeaderLen - 4);
//					file.Write (szBuf, nRead);

					// return the header
					LPSTR pRecvBuf = strRecv.GetBuffer (nHeaderLen);
					strncpy (pRecvBuf, szBuf, nHeaderLen);
					pRecvBuf[nHeaderLen] = '\0';
					strRecv.ReleaseBuffer ();

					bHeaderRead = true;
				}
				else
					file.Write (szBuf, nRead);
			}
			else
			{
				// save stream as string to return
				szBuf[nRead] = '\0';
				strRecv += szBuf;

				// try to get the Content-Length header
				// and set the progress control's range appropriately
				if (!bHeaderRead)
				{
					if ((nPos = strRecv.Find ("Content-Length:")) >= 0)
					{
						nContLen = atoi (strRecv.Mid (nPos + 15));
						if (pProgress != NULL)
							pProgress->SetRange32 (0, nContLen);
					}
					bHeaderRead = true;
				}
			}
		}

		nLen += nRead;

		if (nContLen >= 0)
			if (nLen >= nContLen)
				nRead = 0;

		if (pProgress != NULL)
			pProgress->SetPos (nLen);
		if (pStatus != NULL)
		{
			strStatus.Format (IDS_DOWNLOADSTATUS, (double) nLen / 1024.0, (double) nContLen / 1024.0);
			pStatus->SetWindowText (strStatus);
		}

		while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
			DispatchMessage (&msg);
	}

	socket.Close ();

	if (bUseFile)
		file.Close ();

	return strRecv;
}
Пример #26
0
BOOL CBetaPatchClientDlg::InitControls()
{
#ifdef __LANG_RUS
	enum PublisherVersion { PUBLISHER_VERSION_1 = 0, PUBLISHER_VERSION_2 = 1 };
	PublisherVersion ePublisherVersion = PUBLISHER_VERSION_1;
	CScanner scanner;
	if( scanner.Load( "a.txt" ) == TRUE )
	{
		int nKeyNumber = scanner.GetNumber();
		if( nKeyNumber == 1 )
			ePublisherVersion = PUBLISHER_VERSION_2;
		else
			ePublisherVersion = PUBLISHER_VERSION_1;
	}
	else
		ePublisherVersion = PUBLISHER_VERSION_1;
#endif // __LANG_RUS

#ifdef __LANG_RUS
	DWORD dwBitmapID = ( ePublisherVersion == PUBLISHER_VERSION_1 ) ? IDC_BITMAP_MAIN : IDC_BITMAP_MAIN_2;
	if( m_pic.Load( dwBitmapID ) )
#else // __LANG_RUS
	if( m_pic.Load( IDC_BITMAP_MAIN ) )
#endif // __LANG_RUS
	{
		CSize size = m_pic.GetImageSize();
		SetWindowPos( NULL, 0, 0, size.cx, size.cy, SWP_NOZORDER | SWP_NOMOVE );

		HRGN hRgn = CreateRoundRectRgn( 0, 0, size.cx, size.cy, 20, 20 );
		if( hRgn )
			::SetWindowRgn( m_hWnd, hRgn, FALSE );
	}

	int nInfoGap = 0;
	int nWeblinkGap = 0;

#if defined(__LANG_JAP)
#if 0 //JAPAN 패치 클라이언트 이미지 변경관련 삭제.
	nInfoGap    = 5;
	nWeblinkGap = 35;

	srand( (unsigned)time( NULL ) );
	int nsel = rand()%4;
	
	UINT nchrarry[4] = { IDB_BITMAP_CHAR1, IDB_BITMAP_CHAR3, IDB_BITMAP_CHAR5, IDB_BITMAP_CHAR7 };
	UINT nchrarryM[4] = { IDB_BITMAP_CHAR2, IDB_BITMAP_CHAR4, IDB_BITMAP_CHAR6, IDB_BITMAP_CHAR8 };
	
	m_bmpchr[0].LoadBitmap( nchrarry[nsel] );
	m_bmpchr[1].LoadBitmap( nchrarryM[nsel] );
#endif
#endif // __LANG_JAP

	m_Button_Exit.SetBitmaps(IDB_BITMAP_CLOSE00, RGB(255, 0, 255), IDB_BITMAP_CLOSE01, RGB(255, 0, 255) );
	m_Button_Exit.SetAlign(CButtonST::ST_ALIGN_OVERLAP, FALSE);
	m_Button_Exit.SetPressedStyle(CButtonST::BTNST_PRESSED_LEFTRIGHT, FALSE);
	m_Button_Exit.SetColor(CButtonST::BTNST_COLOR_FG_IN, RGB(0, 0, 0));
	m_Button_Exit.SetColor(CButtonST::BTNST_COLOR_FG_OUT, RGB(0, 0, 0));
	m_Button_Exit.SizeToContent();
	m_Button_Exit.DrawTransparent(TRUE);
	m_Button_Exit.DrawBorder(FALSE, FALSE);
	m_Button_Exit.SetBtnCursor(IDC_CURSOR1);

	m_Button_Option.SetBitmaps(IDB_BITMAP_OPTION00, RGB(255, 0, 255), IDB_BITMAP_OPTION01, RGB(255, 0, 255) );
	m_Button_Option.SetAlign(CButtonST::ST_ALIGN_OVERLAP, FALSE);
	m_Button_Option.SetPressedStyle(CButtonST::BTNST_PRESSED_LEFTRIGHT, FALSE);
	m_Button_Option.SetColor(CButtonST::BTNST_COLOR_FG_IN, RGB(0, 0, 0));
	m_Button_Option.SetColor(CButtonST::BTNST_COLOR_FG_OUT, RGB(0, 0, 0));
	m_Button_Option.SizeToContent();
	m_Button_Option.DrawTransparent(TRUE);
	m_Button_Option.DrawBorder(FALSE, FALSE);
	m_Button_Option.SetBtnCursor(IDC_CURSOR1);

	m_Button_Start.SetBitmaps(IDB_BITMAP_START00, RGB(255, 0, 255), IDB_BITMAP_START01, RGB(255, 0, 255) );
	m_Button_Start.SetAlign(CButtonST::ST_ALIGN_OVERLAP, FALSE);
	m_Button_Start.SetPressedStyle(CButtonST::BTNST_PRESSED_LEFTRIGHT, FALSE);
	m_Button_Start.SetColor(CButtonST::BTNST_COLOR_FG_IN, RGB(0, 0, 0));
	m_Button_Start.SetColor(CButtonST::BTNST_COLOR_FG_OUT, RGB(0, 0, 0));
	m_Button_Start.SizeToContent();
	m_Button_Start.DrawTransparent(TRUE);
	m_Button_Start.DrawBorder(FALSE, FALSE);
	m_Button_Start.SetBtnCursor(IDC_CURSOR1);

	m_Button_Register.SetBitmaps(IDB_BITMAP_REGISTER00, RGB(255, 0, 255), IDB_BITMAP_REGISTER01, RGB(255, 0, 255) );
	m_Button_Register.SetAlign(CButtonST::ST_ALIGN_OVERLAP, FALSE);
	m_Button_Register.SetPressedStyle(CButtonST::BTNST_PRESSED_LEFTRIGHT, FALSE);
	m_Button_Register.SetColor(CButtonST::BTNST_COLOR_FG_IN, RGB(0, 0, 0));
	m_Button_Register.SetColor(CButtonST::BTNST_COLOR_FG_OUT, RGB(0, 0, 0));
	m_Button_Register.SizeToContent();
	m_Button_Register.DrawTransparent(TRUE);
	m_Button_Register.DrawBorder(FALSE, FALSE);
	m_Button_Register.SetBtnCursor(IDC_CURSOR1);

#if defined(__LANG_ENG_USA) || defined(__LANG_ENG_USATEST) || defined(__LANG_GER) || defined(__LANG_FRA) || defined(__LANG_POR)
	m_Button_Register.ShowWindow(SW_SHOW);
#else
	m_Button_Register.ShowWindow(SW_HIDE);
#endif
	// static
//#if defined(__LANG_THAI) //Background Image 교체로 Font Color 변경
	COLORREF cr = RGB( 0,0,0 );
	m_Static_CurrentState.SetTextColor( cr );
	m_Static_CurrentState.SetFontBold(true);
	m_Static_DownSpeed.SetTextColor( cr );
	m_Static_FileNumber.SetTextColor( cr );
	m_Static_MasqueradeVersion.SetTextColor( cr );
	m_Static_MasqueradeVersion.SetFontBold(true);
//#endif

/*#if (__CURRENT_LANG == LANG_ENG || __CURRENT_LANG == LANG_GER || __CURRENT_LANG == LANG_FRA )//|| __CURRENT_CNTRY == CNTRY_TWN)
#if __VER == 12
	COLORREF cr = RGB( 255, 255, 255 );
	m_Static_CurrentState.SetTextColor( cr );
	m_Static_DownSpeed.SetTextColor( cr );
	m_Static_FileNumber.SetTextColor( cr );
	m_Static_MasqueradeVersion.SetTextColor( cr );
#endif
#endif*/

#ifdef	__HANGAME0307     // 한게임 대응 버젼 
	TCHAR* szText   = HOME_LINK;
	TCHAR* szURL    = HOME_LINK;
	TCHAR* szWebURL = WEB_FIRST_PAGE;

	if( AfxGetApp()->m_lpCmdLine[0] != '\0' &&
		memcmp( AfxGetApp()->m_lpCmdLine, "hangame.co.jp", 13 ) == 0 )
	{
		szText   = "http://www.hangame.co.jp";
		szURL    = "http://www.hangame.co.jp/game.asp?fo";
		szWebURL = "http://www.flyff.jp/in_client/info/list.asp?domain=hangame.co.jp";
	}
#else					// 일반버젼 
#ifdef __LANG_RUS
	TCHAR* szText  = ( ePublisherVersion == PUBLISHER_VERSION_1 ) ? HOME_LINK : HOME_LINK_2;
	TCHAR* szURL   = ( ePublisherVersion == PUBLISHER_VERSION_1 ) ? HOME_LINK : HOME_LINK_2;
	TCHAR* szWebURL = ( ePublisherVersion == PUBLISHER_VERSION_1 ) ? WEB_FIRST_PAGE : WEB_FIRST_PAGE_2;
#else // __LANG_RUS
	TCHAR* szText   = HOME_LINK;
	TCHAR* szURL    = HOME_LINK;
	TCHAR* szWebURL = WEB_FIRST_PAGE;
#endif // __LANG_RUS
#endif	// __HANGAME0307

#if __CURRENT_LANG == LANG_KOR
#ifdef __LINK_PORTAL
	// 한국 : 엔젤, 버디 포탈 링크 연결
	TCHAR szArg1[64] = {0, }; 
	TCHAR szArg2[64] = {0, }; 

	_stscanf( AfxGetApp()->m_lpCmdLine, "%s %s", szArg1, szArg2 );

//	AfxMessageBox( AfxGetApp()->m_lpCmdLine );

	CString strCmdLine;
	strCmdLine.Format("%s", szArg2);

	int nLength = strCmdLine.GetLength();
	if(nLength > 4)
	{
		CString strCmpWord = strCmdLine.Mid(nLength-4, nLength);

		if(strCmpWord == "__an")
		{
			szText   = "http://af.gameangel.com";
			szURL    = "http://af.gameangel.com";
		}
		else if(strCmpWord == "__bu")
		{
			szText   = "http://flyff.buddybuddy.co.kr";
			szURL    = "http://flyff.buddybuddy.co.kr";
		}
	}
#endif //__LINK_PORTAL
#endif // LANG_KOR

	// 홈페이지 링크
	m_Static_HomeLink.SetWindowText( szText );
/*#if __CURRENT_CNTRY == CNTRY_HK
	m_Static_HomeLink.SetWindowPos( NULL, 300, 22+nWeblinkGap, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOREDRAW );
#else*/
	m_Static_HomeLink.SetWindowPos( NULL, 280, 242+nWeblinkGap, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOREDRAW );
//#endif

#if __CURRENT_LANG == LANG_THA
	m_Static_HomeLink.SetColours( RGB( 190, 30, 20 ), RGB( 240, 130, 180), RGB( 112, 147, 219 ) );
#elif __CURRENT_LANG == LANG_RUS
	m_Static_HomeLink.SetColours( RGB( 255, 255, 255 ), RGB( 255, 0, 0 ), RGB( 0, 130, 0 ) );
#elif __CURRENT_LANG == LANG_GER
	m_Static_HomeLink.SetColours( RGB( 193, 177, 160 ), RGB( 255, 0, 0 ), RGB( 255, 0, 0 ) );
#elif __CURRENT_LANG == LANG_ENG // ascension
	m_Static_HomeLink.SetColours( RGB( 255, 255, 255 ), RGB( 0, 0, 255 ), RGB( 0, 0, 255 ) );
#elif __CURRENT_LANG == LANG_FRA
	m_Static_HomeLink.SetColours( RGB( 193, 177, 160 ), RGB( 255, 0, 0 ), RGB( 255, 0, 0 ) );
#elif __CURRENT_LANG == LANG_POR
	m_Static_HomeLink.SetColours( RGB( 255, 255, 255 ), RGB( 255, 0, 0 ), RGB( 255, 0, 0 ) );
#else
	m_Static_HomeLink.SetColours( RGB( 0, 0, 0), RGB( 255, 0, 0), RGB( 0, 130, 0 ) );
#endif 
	m_Static_HomeLink.SetURL( szURL );
	m_Static_HomeLink.SetUnderline( CHyperLink::ulAlways );

#ifdef __LANG_JAP
	//JAPAN 패치 클라이언트 이미지 변경관련 삭제.	
	m_Static_HomeLink.EnableWindow(FALSE);
	m_Static_HomeLink.ShowWindow(FALSE);
#endif //__LANG_JAP
	//	Progress 초기화
	m_File_Progress.SetPos(0);
	m_Total_Progress.SetPos(0);

	CreateWebControl( szWebURL );

	GetDlgItem( IDC_BUTTON_START )->MoveWindow( 25, 465, 100, 20 );
	GetDlgItem( IDC_BUTTON_REGISTER )->MoveWindow( 145, 465, 100, 20 );
	GetDlgItem( IDC_OPTION )->MoveWindow( 250, 465, 100, 20 );
	GetDlgItem( IDC_EXIT )->MoveWindow( 355, 465, 100, 20 );
	GetDlgItem( IDC_CURRENT_STATE)->MoveWindow( 25, 495, 170, 20 );
	GetDlgItem( IDC_DOWN_SPEED)->MoveWindow( 200, 495, 100, 20 );
	GetDlgItem( IDC_FILE_NUMBER)->MoveWindow( 350, 495, 100, 20 );
	GetDlgItem( IDC_FILEPROGRESS )->MoveWindow( 25, 515, 430, 20 );
	GetDlgItem( IDC_TOTALPROGRESS)->MoveWindow( 25, 540, 430, 20 );
	GetDlgItem( IDC_MASQUERADEVERSION)->MoveWindow( 200, 570-nInfoGap, 200, 20 );

	return TRUE;
}
Пример #27
0
void CGroupBoxEx::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	
	// TODO: Add your message handler code here

	CPen newPen;
	CPen *oldPen;
	CRect rc = NULL;
	GetClientRect(rc);
	rc.top += 4;
	CString text;
	this->GetWindowText(text);

	int textSize = 0;
	for (int loop = 0; loop < text.GetLength(); loop++) {
		int buffer = 0;
		dc.GetCharWidth(text[loop], text[loop], &buffer);
		textSize += buffer;
	}
	
	LOGFONT logFont;
	dc.GetCurrentFont()->GetLogFont(&logFont);

	newPen.CreatePen(PS_SOLID, 1, RGB(255, 255, 255));
	oldPen = dc.SelectObject(&newPen);

	dc.MoveTo(10, rc.top);
	dc.LineTo(rc.left, rc.top);
	dc.LineTo(rc.left, rc.bottom);
	dc.LineTo(rc.right, rc.bottom);
	dc.LineTo(rc.right, rc.top);
	dc.LineTo(12 + textSize, rc.top);

	dc.SelectObject(oldPen);
	newPen.DeleteObject();

	rc.InflateRect(-1, -1);
	newPen.CreatePen(PS_SOLID, 1, RGB(192, 192, 192));
	oldPen = dc.SelectObject(&newPen);

	dc.MoveTo(10, rc.top);
	dc.LineTo(rc.left, rc.top);
	dc.LineTo(rc.left, rc.bottom);
	dc.LineTo(rc.right, rc.bottom);
	dc.LineTo(rc.right, rc.top);
	dc.LineTo(12 + textSize, rc.top);

	dc.SelectObject(oldPen);
	newPen.DeleteObject();

/*	newPen.CreatePen(PS_SOLID, 1, RGB(skin.m_SecondaryBackgroundRedValue,skin.m_SecondaryBackgroundGreenValue,skin.m_SecondaryBackgroundBlueValue));
	oldPen = dc.SelectObject(&newPen);

	dc.MoveTo(11, rc.top);
	dc.LineTo(16 + (logFont.lfWidth * text.GetLength()), rc.top);
	dc.LineTo(16 + (logFont.lfWidth * text.GetLength()), rc.top - 1);
	dc.LineTo(11, rc.top - 1);

	dc.SelectObject(oldPen);
	newPen.DeleteObject();*/

	rc.top += 1;
	rc.left += 1;
	CBrush myBrush;
	myBrush.CreateSolidBrush(RGB(skin.m_SecondaryBackgroundRedValue,skin.m_SecondaryBackgroundGreenValue,skin.m_SecondaryBackgroundBlueValue));
	dc.FillRect(rc, &myBrush);

	rc.top = -1;
	rc.left = 12; 
	rc.right = 13 + textSize;
	rc.bottom = 16;
	logFont.lfWeight = FW_BOLD;
	CFont font;
	font.CreateFontIndirect(&logFont);
	CFont* def_font = dc.SelectObject(&font);
	dc.SetTextColor(RGB(skin.m_TextRedValue, skin.m_TextGreenValue, skin.m_TextBlueValue));
	dc.SetBkMode(TRANSPARENT);
	dc.SelectObject(::GetStockObject(HOLLOW_BRUSH));

	dc.DrawText(text, rc, NULL);

	dc.SelectObject(def_font);
	font.DeleteObject(); 
}
Пример #28
0
//Copy string to clipboard and paste it to worksheet
BOOL CXLAutomation::PasteStringToWorksheet(CString pDataBuffer)
{
	if(NULL == m_pdispWorksheet)
		return FALSE;
	if(pDataBuffer.IsEmpty())
		return FALSE;

	long nBuffSize = pDataBuffer.GetLength(); 
	//Nothing to copy
	if(0 == nBuffSize)
		return FALSE;

	HANDLE hMem = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, 24);
  
	  if (OpenClipboard(NULL) )
	  {
		HGLOBAL hClipMem;
		char* buffer;
		BOOL bResult = TRUE;
		
		EmptyClipboard();
		hClipMem = GlobalAlloc(GMEM_DDESHARE, nBuffSize);
		buffer = (char*)GlobalLock(hClipMem);
		memcpy(buffer, pDataBuffer, nBuffSize);
		GlobalUnlock(hClipMem);
		SetClipboardData(CF_TEXT, hClipMem);
		CloseClipboard();
		
		//Paste data from clipboard
		// set sourceRange = ws.Range("A1")
		IDispatch* pdispRange = NULL;
		VARIANTARG varg1, varg2;

		ClearAllArgs();
		AddArgumentOLEString(NULL, 0, L"A1");
		if (!ExlInvoke(m_pdispWorksheet, L"Range", &varg2, DISPATCH_PROPERTYGET, DISP_FREEARGS))
			return FALSE;
		pdispRange = varg2.pdispVal;


		//Force past from clipboard
		//set as = sourceRange.Select
		ClearAllArgs();
		if (!ExlInvoke(pdispRange, L"Select", &varg2, DISPATCH_PROPERTYGET, DISP_FREEARGS))
			goto Failed;

		// set wb.ActiveSheet.Paste
		ClearAllArgs();
		if (!ExlInvoke(m_pdispWorkbook, L"ActiveSheet", &varg1, DISPATCH_PROPERTYGET, 0))
			goto Failed;
		ClearAllArgs();

		// set wb.ActiveSheet.Paste
		ClearAllArgs();
		if (!ExlInvoke(m_pdispWorkbook, L"ActiveSheet", &varg1, DISPATCH_PROPERTYGET, 0))
			goto Failed;
		ClearAllArgs();
		bResult = ExlInvoke(varg1.pdispVal, L"Paste", &varg2, DISPATCH_METHOD, 0);
		ReleaseVariant(&varg1);
	
		goto Success;

Failed:
		bResult = FALSE;
Success:
		if(NULL != pdispRange)
		{
			pdispRange->Release();
			pdispRange = NULL;
		}

		return bResult;
	  }
	  return FALSE;

}
Пример #29
0
void color_combo_box::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	int m_cyText = 24, z;
	CString strText;
	char ship_name[256];

	// You must override DrawItem and MeasureItem for LBS_OWNERDRAWVARIABLE
	ASSERT((GetStyle() & (LBS_OWNERDRAWFIXED | CBS_HASSTRINGS)) ==
		(LBS_OWNERDRAWFIXED | CBS_HASSTRINGS));

	CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC);

	// I think we need to do a lookup by ship name here	
	if(lpDrawItemStruct->itemID >= (uint)Num_ship_classes){
		z = lpDrawItemStruct->itemID;
	} else {		
		memset(ship_name, 0, 256);
		GetLBText(lpDrawItemStruct->itemID, ship_name);
		z = ship_info_lookup(ship_name);
	}

	if ((z >= 0) && (lpDrawItemStruct->itemAction & (ODA_DRAWENTIRE | ODA_SELECT)))
	{
		int cyItem = GetItemHeight(z);
		BOOL fDisabled = !IsWindowEnabled();

		COLORREF newTextColor = RGB(0x80, 0x80, 0x80);  // light gray
		if (!fDisabled)
		{
			if (z >= Num_ship_classes)
				newTextColor = RGB(0, 0, 0);
			else
			{
				species_info *sinfo = &Species_info[Ship_info[z].species];
				newTextColor = RGB(sinfo->fred_color.rgb.r, sinfo->fred_color.rgb.g, sinfo->fred_color.rgb.b);
			}
		}

		COLORREF oldTextColor = pDC->SetTextColor(newTextColor);
		COLORREF newBkColor = GetSysColor(COLOR_WINDOW);
		COLORREF oldBkColor = pDC->SetBkColor(newBkColor);

		if (newTextColor == newBkColor)
			newTextColor = RGB(0xC0, 0xC0, 0xC0);   // dark gray

		if (!fDisabled && ((lpDrawItemStruct->itemState & ODS_SELECTED) != 0))
		{
			pDC->SetTextColor(GetSysColor(COLOR_HIGHLIGHTTEXT));
			pDC->SetBkColor(GetSysColor(COLOR_HIGHLIGHT));
		}

		if (m_cyText == 0)
			VERIFY(cyItem >= CalcMinimumItemHeight());

		if (z == Id_select_type_jump_node)
			strText = _T("Jump Node");
		else if (z == Id_select_type_start)
			strText = _T("Player Start");
		else if (z == Id_select_type_waypoint)
			strText = _T("Waypoint");
		else
			strText = _T(Ship_info[z].name);
//		GetLBText(lpDrawItemStruct->itemID, strText);

		pDC->ExtTextOut(lpDrawItemStruct->rcItem.left,
			lpDrawItemStruct->rcItem.top + max(0, (cyItem - m_cyText) / 2),
			ETO_OPAQUE, &(lpDrawItemStruct->rcItem), strText, strText.GetLength(), NULL);

		pDC->SetTextColor(oldTextColor);
		pDC->SetBkColor(oldBkColor);
	}

	if ((lpDrawItemStruct->itemAction & ODA_FOCUS) != 0)
		pDC->DrawFocusRect(&(lpDrawItemStruct->rcItem));
}
Пример #30
0
CString BugReport::createReport()
{
  theApp.winCheckFullscreen();

  CString report = "";
  AppendFormat(report, "Emu version  : %s\r\n", VERSION);
  AppendFormat(report, "Emu Type     : %s\r\n",
#ifdef FINAL_VERSION
#ifdef DEV_VERSION
               "Development Version"
#else
               "Normal Version"
#endif
#else
               "Debug Version"
#endif
               );

  if(emulating) {
    AppendFormat(report, "File         : %s\r\n", theApp.szFile);

    char buffer[20];
    if(theApp.cartridgeType == 0) {
      u32 check = 0;
      for(int i = 0; i < 0x4000; i += 4) {
        check += *((u32 *)&bios[i]);
      }
      AppendFormat(report, "BIOS Checksum: %08X\r\n", check);

      strncpy(buffer, (const char *)&rom[0xa0], 12);
      buffer[12] = 0;
      AppendFormat(report, "Internal name: %s\r\n", buffer);
      
      strncpy(buffer, (const char *)&rom[0xac], 4);
      buffer[4] = 0;
      AppendFormat(report, "Game code    : %s\r\n", buffer);

      CString res = "";
      u32 *p = (u32 *)rom;
      u32 *end = (u32 *)((char *)rom+theApp.romSize);
      while(p  < end) {
        u32 d = READ32LE(p);
    
        if(d == 0x52504545) {
          if(memcmp(p, "EEPROM_", 7) == 0) {
            res += (const char *)p;
            res += ' ';
          }
        } else if (d == 0x4D415253) {
          if(memcmp(p, "SRAM_", 5) == 0) {
            res += (const char *)p;
            res += ' ';
          }
        } else if (d == 0x53414C46) {
          if(memcmp(p, "FLASH1M_", 8) == 0) {
            res += (const char *)p;
            res += ' ';
          }
        } else if(memcmp(p, "FLASH", 5) == 0) {
          res += (const char *)p;
          res += ' ';
        } else if (d == 0x52494953) {
          if(memcmp(p, "SIIRTC_V", 8) == 0) {
            res += (const char *)p;
            res += ' ';
          }
        }
        p++;
      }
      if(res.GetLength() > 0)
        AppendFormat(report, "Cart Save    : %s\r\n", res);
    } else if(theApp.cartridgeType == 1) {
      strncpy(buffer, (const char *)&gbRom[0x134], 15);
      buffer[15] = 0;
      AppendFormat(report, "Game title   : %s\r\n", buffer);
    }
  }
  
  AppendFormat(report, "Using BIOS   : %d\r\n", theApp.useBiosFile);
  AppendFormat(report, "Skip BIOS    : %d\r\n", theApp.skipBiosFile);
  AppendFormat(report, "Disable SFX  : %d\r\n", cpuDisableSfx);
  AppendFormat(report, "Skip intro   : %d\r\n", theApp.removeIntros);
  AppendFormat(report, "Throttle     : %d\r\n", theApp.throttle);
  AppendFormat(report, "Rewind       : %d\r\n", theApp.rewindTimer);
  AppendFormat(report, "Auto frame   : %d\r\n", theApp.autoFrameSkip);
  AppendFormat(report, "Video option : %d\r\n", theApp.videoOption);
  AppendFormat(report, "Render type  : %d\r\n", theApp.renderMethod);
  AppendFormat(report, "Color depth  : %d\r\n", systemColorDepth);
  AppendFormat(report, "Red shift    : %08x\r\n", systemRedShift);
  AppendFormat(report, "Green shift  : %08x\r\n", systemGreenShift);
  AppendFormat(report, "Blue shift   : %08x\r\n", systemBlueShift);
  AppendFormat(report, "Layer setting: %04X\r\n", layerSettings);
  AppendFormat(report, "Save type    : %d (%d)\r\n", 
               theApp.winSaveType, cpuSaveType);
  AppendFormat(report, "Flash size   : %08X (%08x)\r\n", 
               theApp.winFlashSize, flashSize);
  AppendFormat(report, "RTC          : %d (%d)\r\n", theApp.winRtcEnable,
               rtcIsEnabled());
  AppendFormat(report, "AGBPrint     : %d\r\n", agbPrintIsEnabled());
  AppendFormat(report, "Speed toggle : %d\r\n", theApp.speedupToggle);
  AppendFormat(report, "Synchronize  : %d\r\n", synchronize);
  AppendFormat(report, "Sound OFF    : %d\r\n", soundOffFlag);
  AppendFormat(report, "Channels     : %04x\r\n", soundGetEnable() & 0x30f);
  AppendFormat(report, "Old Sync     : %d\r\n", theApp.useOldSync);
  AppendFormat(report, "Priority     : %d\r\n", theApp.threadPriority);
  AppendFormat(report, "Filters      : %d (%d)\r\n", theApp.filterType, theApp.ifbType);
  AppendFormat(report, "Cheats       : %d\r\n", cheatsNumber);
  AppendFormat(report, "GB Cheats    : %d\r\n", gbCheatNumber);
  AppendFormat(report, "GB Emu Type  : %d\r\n", gbEmulatorType);

  return report;
}