예제 #1
0
파일: tstring.cpp 프로젝트: RuidSiel/taglib
void String::copyFromUTF8(const char *s, size_t length)
{
  d->data.resize(length);

  UTF8toUTF16(s, length, &d->data[0], d->data.size());
  d->data.resize(::wcslen(d->data.c_str()));
}
예제 #2
0
void CMCUCommonTest::testEmptyInput()
{
	string strResult = UTF16toUTF8( L"" );
	CPPUNIT_ASSERT_EQUAL( strResult, string("") );

	wstring strWR = UTF8toUTF16( "" );
	CPPUNIT_ASSERT_EQUAL( strWR, wstring(L"") );
}
예제 #3
0
void CMCUCommonTest::testUtfConvert()
{
	wstring strW = L"lzx是大好人!!";

	string strA = UTF16toUTF8( strW );
	wstring strFinalW = UTF8toUTF16( strA );

	CPPUNIT_ASSERT_EQUAL( strW, strFinalW );
}
예제 #4
0
static jstring TQAItem_GetQuestioner_username(JNIEnv* env, jobject thiz)
{
    TQAItem* pObj = (TQAItem*)env->GetIntField(thiz, gTQAItemFieldID.nativeJavaObj);
    if (pObj == 0) return NULL;

    size_t size = strlen(pObj->sQuestioner_username.c_str());
    jchar* data = UTF8toUTF16((char*)pObj->sQuestioner_username.c_str(), &size);
    jstring str = env->NewString((const jchar*)data, size);
    free(data);
    return str;
}
static jstring CMSpecialTopic_GetImage(JNIEnv* env, jobject thiz)
{
    CMSpecialTopic* pObj = (CMSpecialTopic*)env->GetIntField(thiz, gCMSpecialTopicFieldID.nativeJavaObj);

    const char* ret = pObj->GetImage();
    size_t size = strlen(ret);
    jchar* data = UTF8toUTF16((char*)ret, &size);
    jstring str = env->NewString((const jchar*)data, size);
    free(data);
    return str;
}
예제 #6
0
파일: sspi.hpp 프로젝트: wallix/redemption
 static void copyFromUtf8(Array& arr, uint8_t const* data)
 {
     if (data) {
         size_t user_len = UTF8Len(data);
         arr.init(user_len * 2);
         UTF8toUTF16({data, strlen(char_ptr_cast(data))}, arr.get_data(), user_len * 2);
     }
     else {
         arr.init(0);
     }
 }
static jstring TRepalymentItem_GetHeadImage(JNIEnv* env, jobject thiz)
{
    TRepalymentItem* pObj = (TRepalymentItem*)env->GetIntField(thiz, gTRepalymentItemFieldID.nativeJavaObj);
    if (pObj == 0) return NULL;

    size_t size = strlen(pObj->sHeadImage);
    jchar* data = UTF8toUTF16((char*)pObj->sHeadImage, &size);
    jstring str = env->NewString((const jchar*)data, size);
    free(data);
    return str;
}
예제 #8
0
static jstring CMCategoryItem_GetTitle(JNIEnv* env, jobject thiz)
{
    CMCategoryItem* pObj = (CMCategoryItem*)env->GetIntField(thiz, gCMCategoryItemFieldID.nativeJavaObj);
    if (pObj == 0) return NULL;

    size_t size = strlen(pObj->sTitle);
    jchar* data = UTF8toUTF16((char*)pObj->sTitle, &size);
    jstring str = env->NewString((const jchar*)data, size);
    free(data);
    return str;
}
static jstring TTrainSignInItem_GetFlag(JNIEnv* env, jobject thiz)
{
    TTrainSignInItem* pObj = (TTrainSignInItem*)env->GetIntField(thiz, gTTrainSignInItemFieldID.nativeJavaObj);
    if (pObj == 0) return NULL;

    size_t size = strlen(pObj->sFlag.c_str());
    jchar* data = UTF8toUTF16((char*)pObj->sFlag.c_str(), &size);
    jstring str = env->NewString((const jchar*)data, size);
    free(data);
    return str;
}
예제 #10
0
static jstring CMSettings_GetDefautlEnterpriseSlogan(JNIEnv* env, jobject thiz)
{
    CMSettings* pObj = (CMSettings*)env->GetIntField(thiz, gCMSettingsFieldID.nativeJavaObj);

    const char* ret = pObj->GetDefautlEnterpriseSlogan();
    size_t size = strlen(ret);
    jchar* data = UTF8toUTF16((char*)ret, &size);
    jstring str = env->NewString((const jchar*)data, size);
    free(data);
    return str;
}
예제 #11
0
/*=========================================================================+
	Add_Element:
		Add a "<tag> value </tag>" element to an XML block.  If the
		optional tag attribute and value are provided, then the element
		will look like "<tag attribute=value> value </tag>" instead.

+=========================================================================*/
int
ExitXMLBlock::Add_Element(
			DOMDocument*	pDocument,
			DOMElement*		pParentElement,
			string			sTag,
			string			sValue,
			string			sTagAttribute,		//		= "",
			string			sTagAttributeValue	//		= ""
	)
{
	DOMElement*			pElement	= NULL;
	STATUS_T			tStatus		= E_SUCCESS;
	XMLCh*				pxcValue	= NULL;
	int					iRc			= -1;		// FailureS
	
	// Create element.
	if (pDocument && pParentElement && !sTag.empty() && !sValue.empty()) {
		pxcValue = UTF8toUTF16(sTag);
		DOMElement* pChild = pDocument->createElement(pxcValue);
		delete pxcValue;

		pxcValue = UTF8toUTF16(sValue);
		DOMText* pText = pDocument->createTextNode(pxcValue);
		delete pxcValue;

		pChild->appendChild(pText);

		// Add the tag attribute if specified.
		if (!sTagAttribute.empty() && !sTagAttributeValue.empty()) {
			XMLCh* pxcAttr	= UTF8toUTF16(sTagAttribute);
			XMLCh* pxcValue	= UTF8toUTF16(sTagAttributeValue);
			pChild->setAttribute(pxcAttr, pxcValue);
			delete pxcAttr;
			delete pxcValue;
		}

		pParentElement->appendChild(pChild);
		iRc = 0;
	} 
	return iRc;
}
예제 #12
0
static jstring Hello_stringFromJNI(JNIEnv* env,jobject thiz)
{
	Hello* he = (Hello*)env->GetIntField(thiz,helloFieldID);
	if(he == NULL)
		return NULL;
	char* jni_str = (char*)he->stringFromJNI();
	size_t size = strlen(jni_str);
	jchar* data = UTF8toUTF16((char*)jni_str,&size);
	jstring str = env->NewString(data,size);
	free(data);
	return str;
}
예제 #13
0
ExitXMLBlock::ExitXMLBlock(
		string		sInputXML
	)
{
	int iRc;

	// xerces-c
	m_pXmlDocument				= NULL;
	m_pXmlTranscoder			= NULL;

	// Initialize member variables.
	m_sInputXML					= sInputXML;
	m_sExitType					= "";
	m_sObjectDn					= "";
	m_sObjectName				= "";
	m_sObjectClass				= "";
	m_sAuthenticationType		= AUTHTYPE_NONE;
	m_sAuthenticationUser		= "";
	m_sAuthenticationPassword	= "";

	try {
		XMLPlatformUtils::Initialize();
	}
	catch (const XMLException& toCatch) {
		char* pszMessage = XMLString::transcode(toCatch.getMessage());
		cerr << "Error during initialization! :\n" << pszMessage << "\n";
		XMLString::release(&pszMessage);
	}

	// Create UTF-16/UTF-8 conversion transcoder
	Initialize_Transcoder();

	// Get Implementation
	if (ExitXMLBlock::g_pImplementation == NULL) {
		XMLCh* pzcValue = UTF8toUTF16("LS");
		ExitXMLBlock::g_pImplementation = DOMImplementationRegistry::getDOMImplementation(pzcValue);
		delete pzcValue;
	}

	// Initialize XML Parser
	m_pXmlWriter = ExitXMLBlock::g_pImplementation ->createDOMWriter();
	m_pXmlBuilder = ExitXMLBlock::g_pImplementation->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
	m_pXmlWriter->setFeature(XMLUni::fgDOMXMLDeclaration, false);
	m_pXmlBuilder->resetDocumentPool();
	m_pXmlDocument = NULL;

	// Parse the input.
	iRc = Parse_ETA_Input_XML();
	if (iRc == 0) {
	}
}
예제 #14
0
/*=========================================================================+
	Find_Node:
		Locate the node with the indicated tag.

+=========================================================================*/
DOMNodeList*
ExitXMLBlock::Find_Node(
		DOMDocument*			pDocument,
		string					sTag,
		bool					bFindMultipleNodes		// = true
	)
{
	DOMNodeList*	pNodeList	= NULL;
	XMLCh*			pxcTag		= NULL;

	pxcTag = UTF8toUTF16(sTag);
	pNodeList = pDocument->getElementsByTagName(pxcTag);
	delete pxcTag;

	return pNodeList;
}
예제 #15
0
HRESULT GetDnaHeader(bool showErrors, std::wstring& header)
{
	// We find the .dna file and load a 1k string from the file.
	// To locate the file:
	// 1. First check for packed __MAIN__ DNA resource,
	// 2. Else load file next to .xll file, 
	// Else E_FAIL.
	// This sequence matches the load sequence in ExcelDna.Integration.DnaLibrary.Initialize().
	// NOTE: __MAIN__ DNA resource can not currently be compressed.
	
	HRESULT hr = E_FAIL;
	const DWORD MAX_HEADER_LENGTH = 1024;
	DWORD headerLength = 0;
	BYTE headerBuffer[MAX_HEADER_LENGTH] ;

	HRSRC hResDna = FindResource(hModuleCurrent, L"__MAIN__", L"DNA");
	if (hResDna != NULL)
	{
		HGLOBAL hDna = LoadResource(hModuleCurrent, hResDna);
		DWORD sizeDna = SizeofResource(hModuleCurrent, hResDna);
		void* pDna = LockResource(hDna);
		headerLength = min(sizeDna, MAX_HEADER_LENGTH);
		CopyMemory(headerBuffer, pDna, headerLength);
	}
	else
	{
		SafeFile dnaFile;
		std::wstring dnaPath(GetAddInFullPath());
		RenameExtension(dnaPath, L".dna");
		if (!FileExists(dnaPath.c_str()))
		{
			if (showErrors)
			{
				ShowMessage(IDS_MSG_HEADER_DNANOTFOUND, 
				IDS_MSG_BODY_DNAPATHNOTEXIST, 
				IDS_MSG_FOOTER_ENSUREDNAFILE,
				hr);
			}
			return E_FAIL;
		}
		hr = dnaFile.Create(dnaPath, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING);
		if (FAILED(hr))
		{
			if (showErrors)
			{
				ShowMessage(IDS_MSG_HEADER_DNAPROBLEM, 
				IDS_MSG_BODY_DNAOPENFAILED, 
				IDS_MSG_FOOTER_UNEXPECTED,
				hr);
			}
			return E_FAIL;
		}
		hr = dnaFile.Read((LPVOID)headerBuffer, MAX_HEADER_LENGTH, headerLength);
		if (FAILED(hr))
		{
			if (showErrors)
			{
				ShowMessage(IDS_MSG_HEADER_DNAPROBLEM, 
				IDS_MSG_BODY_DNAOPENFAILED, 
				IDS_MSG_FOOTER_UNEXPECTED,
				hr);
			}
			return E_FAIL;
		}
	}
	if (IsBufferUTF8(headerBuffer, headerLength))
	{
		header = UTF8toUTF16(std::string((char*)headerBuffer, headerLength));
	}
	else
	{
		header = std::wstring((wchar_t*)headerBuffer, headerLength);
	}
	return S_OK;
}
예제 #16
0
bool widgetSetClipboardText(const char *text)
{
	bool ret = false;

	// Copy of text with \n => \r\n
	char *newText;

	// UTF-16 version of newText
	uint16_t *utf16NewText;

	// Number of bytes utf16NewText is in size
	size_t nbytes;

	int count, i, j;

	// Get the number of '\n' characters in the text
	for (i = count = 0; text[i]; i++)
	{
		if (text[i] == '\n')
		{
			count++;
		}
	}

	// Allocate enough space for the \r\n string
	newText = malloc(strlen(text) + count + 1);

	// Copy the string, converting \n to \r\n
	for (i = j = 0; text[i]; i++, j++)
	{
		// If the character is a newline prepend a \r
		if (text[i] == '\n')
		{
			newText[j++] = '\r';
		}

		// Copy the character (\n or otherwise)
		newText[j] = text[i];
	}

	// NUL terminate
	newText[j] = '\0';

	// Convert to UTF-16
	utf16NewText = UTF8toUTF16(newText, &nbytes);

	// Open the clipboard
	if (OpenClipboard(NULL))
	{
		HGLOBAL hGlobal;
		uint16_t *clipboardText;

		// Empty it (which also transfers ownership of it to ourself)
		EmptyClipboard();

		// Allocate global space for the text
		hGlobal = GlobalAlloc(GMEM_MOVEABLE, nbytes);

		// Lock the newly allocated memory
		clipboardText = GlobalLock(hGlobal);

		// Copy the text
		memcpy(clipboardText, utf16NewText, nbytes);

		// Unlock the memory (must come before CloseClipboard())
		GlobalUnlock(hGlobal);

		// Place the handle on the clipboard
		if (SetClipboardData(CF_UNICODETEXT, hGlobal))
		{
			// We were successful
			ret = true;
		}

		// Close the clipboard
		CloseClipboard();
	}

	// Release the malloc-ed strings
	free(newText);
	free(utf16NewText);

	return ret;
}
예제 #17
0
/*=========================================================================+
	Parse_ETA_Input_XML:

		Parse the input XML block.

		eTrust Admin sends an XML block containing data of the
		object being processed.  The XML block also contains
		optional authentication data.

	The format of the input XML block is:
		<eTExitInvoke eTExitType={type of exit}>
			< {objectclass} >
				<eTDN> {dn of object being processed} </eTDN>
				<eTName> {name of object being processed} </eTName>
				< {attribute} > {value} </ {attribute} >
			< {objectclass} >

			<Authentication>
				<Type> {type of authentication} </Type>
				<User> {user to authenticate as} </User>
				<Password> {password (in the clear)} </Password>
			</Authentication>
		</eTExitInvoke>


		The {attribute} and {value} are specific to the object
		being processed.  E.g., if the object has attribute "City"
		and value "Renton", the XML block will contains the tag:
			<City>Renton</City>

		If the attribute is multi-valued, each value will have a
		separate tag:
			<City>Renton</City>
			<City>Kirkland</City>

+=========================================================================*/
int
ExitXMLBlock::Parse_ETA_Input_XML()
{
	int				iRc			= -1;		// failure
	DOMElement*		pElement	= NULL;
	DOMNodeList*	pNodeList	= NULL;
	XMLCh*			pxcTag		= NULL;
	const XMLCh*	pxcValue	= NULL;
	UTF8*			pszuValue	= NULL;
	string			sTagName;
	string			sTagValue;
	string			sErrMsg;
	int				iTagCount;

	// Load the XML document.
	try {
		m_pXmlBuilder->resetDocumentPool();
		MemBufInputSource oSource(
							(const XMLByte*)m_sInputXML.c_str(),
							m_sInputXML.length(),
							"InputBuffer",
							false);
		Wrapper4InputSource oWrapper(&oSource, false);
		m_pXmlDocument = m_pXmlBuilder->parse(oWrapper);
	}
	catch (const XMLException& toCatch) {
		sErrMsg = XMLString::transcode(toCatch.getMessage());
        cerr << "\nError during parsing\nException message is: \n" << sErrMsg << "\n";
		goto exit;
	}
	catch (const DOMException& toCatch) {
        const unsigned int iMaxChars = 2047;
        XMLCh pzcErrMsg[iMaxChars + 1];
		sErrMsg = XMLString::transcode(toCatch.msg);
		cerr << "\nDOM Error during parsing\nException message is: \n" << sErrMsg << "\n";
        if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, pzcErrMsg, iMaxChars))
                cerr << "Message is: " << XMLString::transcode(pzcErrMsg) << endl;
		goto exit;
	}
	catch (...) {
        cerr << "\nUnexpected exception during parsing\n";
		goto exit;
	}

	// Get the exit type from the top level node's tag attribute.
	pElement = m_pXmlDocument->getDocumentElement();

	pxcTag = UTF8toUTF16(UTFEXIT_EXITTYPE);
	pxcValue = pElement->getAttribute(pxcTag);
	delete pxcTag;
	if (pxcValue) {
		this->m_sExitType = UTF16toUTF8(pxcValue);
	}

	// Find all the child nodes.
	pNodeList = pElement->getChildNodes();
	if (!pNodeList) {
		goto exit;
	}

	/*
	|| Get the number of tags found under the top level node.
	|| If the node_list is empty initialize the tag count to 0.
	*/
	iTagCount = pNodeList->getLength();
	// cout << "Tag Count:" << iTagCount << endl;

	// Get the tag and value under the top level node and parse each tag.
	for (int iIndex = 0; iIndex < iTagCount; iIndex++) {
		DOMNode* pNode = pNodeList->item(iIndex);
		if (!pNode) {
			// Error!
			continue;
		}

		short siTagType = pNode->getNodeType();
		if (siTagType != 1 /* DOMNode::NodeType::ELEMENT_NODE */) {
			continue;
		}

		/*
		|| Get the tag name.  If failed to get the tag name,
		|| skip the current tag.
		*/
		pxcValue = pNode->getNodeName();
		if (pxcValue) {
			sTagName = UTF16toUTF8(pxcValue);
		}

		pxcValue = pNode->getNodeValue();
		if (pxcValue) {
			sTagValue = UTF16toUTF8(pxcValue);
		}

#if 0
		cout << "Node Name: '" << sTagName << "'" << endl;
		cout << "Node Type: " << siTagType << endl;
		cout << "Node Value: '" << (sTagValue.empty() ? "<empty>" : sTagValue) << "'" << endl;
		const XMLCh* pxcValue = pNode->getTextContent();
		string sTagText = UTF16toUTF8(pxcValue);
		cout << "Node Text: '" << (sTagText.empty() ? "<empty>" : sTagText) << "'" << endl;
		cout << endl;
#endif

		if (sTagName == UTFEXIT_AUTHENTICATION) {
			Parse_Authentication_Block(sTagName);

		} else {
			this->m_sObjectClass = sTagName;
			Parse_Object_Block(this->m_sObjectClass);
		}
	}
	iRc = 0;	// success!

exit:
	return iRc;
}
예제 #18
0
/*=========================================================================+
	Build_Return_XML:
		Build the XML block that eTrust Admin expects the program exit
		to return.

		<eTExitReturn>
			<eTExitReturnCategory></eTExitReturnCategory>
			<eTExitReturnNative></eTExitReturnNative>
			<eTExitContinue></eTExitContinue>
			<eTExitLogMsg></eTExitLogMsg>
			<eTExitCustom></eTExitCustom>
		</eTExitReturn>

	    The return XML buffer provided by eTrust Admin is over 4000 bytes
		long.  There will be no problem fitting the entire output XML
		document into this buffer unless sLogMessage or the custom_msg built
		from the return values array is very long.  Thus, this code attempts
		first to build an XML buffer with all of the provided information
		and if it is too long does the following:
			case 1:  custom_msg is provided
				--> generate a failure exit return block with no custom_msg

			case 2:  sLogMessage is provided, but no custom_msg
				--> replace the very long sLogMessage with a short one.

+=========================================================================*/
void
ExitXMLBlock::Build_Return_XML(
		STATUS_T	tStatus,
		bool		bContinueEtaExecution,
		string		sLogMessage,
		string &	sReturnXML,						// OUT
		int			iMaxReturnLength,
		bool		bObscureValue  // = false
	)
{
	int iRc;
	string	suValue;
	UTF8	pszuValue[32];
	XMLCh*	pxcValue;

	pxcValue = UTF8toUTF16(UTFEXIT_EXITRETURN);
	DOMDocument* pDocument = ExitXMLBlock::g_pImplementation->createDocument(0, pxcValue, 0);
	delete pxcValue;
	DOMElement* pRootElement = pDocument->getDocumentElement();

	// ...eTrust Admin Category.
	suValue = Convert_Status_To_Category_String(tStatus);
	iRc = Add_Element(pDocument, pRootElement, UTFEXIT_EXITRETURNCATEGORY, suValue);

	// ...Program exit return code.
	sprintf(pszuValue, "%d", tStatus);
	iRc = Add_Element(pDocument, pRootElement, UTFEXIT_EXITRETURNNATIVE, pszuValue);

	// ...Should eTrust Admin continue execution?
	suValue = (bContinueEtaExecution ? UTFEXIT_TRUE : UTFEXIT_FALSE);
	iRc = Add_Element(pDocument, pRootElement, UTFEXIT_EXITCONTINUE, suValue);

	// ...Log message.
	if (!sLogMessage.empty()) {
		iRc = Add_Element(pDocument, pRootElement, UTFEXIT_EXITLOGMSG, sLogMessage);
	}

	// ...Custom message (used for return values today; and perhaps for
	// other exit-type specific purposes in the future).
	if (m_vsReturnValues.size() > 0) {
		pxcValue = UTF8toUTF16(UTFEXIT_EXITCUSTOM);
        DOMElement* pElement = pDocument->createElement(pxcValue);
		delete pxcValue;
        pRootElement->appendChild(pElement);

		// Add each return value as <eTFuncReturn>...</eTFuncReturn>
		for (unsigned int iIndex = 0; iIndex <  m_vsReturnValues.size(); iIndex++) {
			if (bObscureValue) {	// add the obscured attribute for passwords
				Add_Element(
					pDocument,
					pElement,
					UTFEXIT_CF_FUNCRETURN,
					m_vsReturnValues[iIndex],
					"obscured",
					"yes");
			} else {
				Add_Element(
					pDocument,
					pElement,
					UTFEXIT_CF_FUNCRETURN,
					m_vsReturnValues[iIndex]);
			}
		}
	}

	// Generate the return XML string
	DOMBuilder* pBuilder;	// Parser
	DOMWriter*	pWriter;	// Serializer

	pWriter = ExitXMLBlock::g_pImplementation->createDOMWriter();
	pBuilder = ExitXMLBlock::g_pImplementation->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
	pWriter->setFeature(XMLUni::fgDOMXMLDeclaration, false);
	pBuilder->resetDocumentPool();

	const XMLCh* pxcReturnXML = pWriter->writeToString(*pRootElement);
	sReturnXML = UTF16toUTF8(pxcReturnXML);

	if (pBuilder) {
		delete pBuilder;
	}
	if (pWriter) {
		delete pWriter;
	}
	
	if (pDocument) {
		delete pDocument;
		pDocument = NULL;
	}

	// Check to make sure it isn't too long for the return buffer
	int iLength = sReturnXML.length();
	if (iLength >= iMaxReturnLength) {
		sReturnXML = "";
		sLogMessage = "ERROR: Return XML buffer too long";

		// If too long, and a custom message was provided, fail the
		// call (and consequently do not report an output value).
		if (m_vsReturnValues.size() > 0) {
			m_vsReturnValues.clear();
			tStatus = E_FAILURE;
			bContinueEtaExecution = false;
		}
	}
}
예제 #19
0
BOOL CHtmlWnd::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
	// TODO: 在此添加专用代码和/或调用基类

	NM_HTMLVIEW* pnmHTMLView = (NM_HTMLVIEW*)lParam;


	switch (pnmHTMLView->hdr.code)
	{
		// this code is processed when a user clicks on a hyperlink
	case NM_HOTSPOT:
		{
			
			// read the target string

			tstring strUrl = UTF8toUTF16( (const char *)pnmHTMLView->szTarget );

            Log() << _T( "NM_HOTSPOT url: " ) <<  strUrl << endl;

			if( m_bWaittingNavigateComplete )
			{
				//停止控件继续操作
				*pResult = 1;
				return TRUE;
			}

            // test.
            //static int n=0;
            //n++;
            //if ( n%5 == 0 )
            //{
            //    strUrl = _T( "/download/downloadmcu.do?abce=1&de=2" );
            //}


			LPCTSTR lpUrlToken = _T( "/download/downloadmcu.do?" );
			CString UrlString = ( LPCTSTR )strUrl.c_str();
			if ( UrlString.Left( _tcslen( lpUrlToken ) ).CompareNoCase( lpUrlToken ) == 0 )
			{
				//判断是下载MCU链接 不兼容其它版本MSP

				//需要拼接完整的URL
                tstring strCurUrl = GetCurUrl();
				int nPos = strCurUrl.find( _T( '/' ), _tcslen( _T( "http://" ) ) );
                tstring strUrlDir;
               
                if ( nPos > 0 )
                {
                    // 不要带上 '/'。
                    strUrlDir = strCurUrl.substr( 0, nPos );
                }
                else
                {
                    strUrlDir = strCurUrl + _T( "/" );
                }

                // this->GetFailHtmlUrl()
//				tstring strFullUrl;
				if( 1 )
				{
					
					 tstring strDownloadUrl ;
                     strDownloadUrl = strUrlDir + strUrl;

					Log() << L"Download Url:"<< strDownloadUrl << endl;

					//调用系统Shell下载
					{
						//添加是为了不显示IE的历史记录
						SHELLEXECUTEINFO seInfo;
						memset( &seInfo, 0, sizeof( seInfo ) );
						seInfo.cbSize = sizeof( seInfo );
						seInfo.fMask = 0;
						seInfo.hwnd = this->GetSafeHwnd();

						//seInfo.lpVerb = _T( "Open" );
						seInfo.lpVerb = _T("Open");
						//seInfo.lpVerb = _T( "iexplore.exe %1" );
						//seInfo.lpFile = strUrl.c_str();
						//seInfo.lpFile = DownloadFullUrl;
						seInfo.lpFile = _T("IEXPLORE.EXE");
						seInfo.lpParameters = L"about:blank";
						BOOL bResult = ::ShellExecuteEx( &seInfo );
					}

					Sleep(1000);

					SHELLEXECUTEINFO seInfo;
					memset( &seInfo, 0, sizeof( seInfo ) );
					seInfo.cbSize = sizeof( seInfo );
					seInfo.fMask = 0;
					seInfo.hwnd = this->GetSafeHwnd();

					//seInfo.lpVerb = _T( "Open" );
					seInfo.lpVerb = _T("Open");
					//seInfo.lpVerb = _T( "iexplore.exe %1" );
					//seInfo.lpFile = strUrl.c_str();
					//seInfo.lpFile = DownloadFullUrl;
					seInfo.lpFile = _T("IEXPLORE.EXE");
					seInfo.lpParameters = strDownloadUrl.c_str();
					BOOL bResult = ::ShellExecuteEx( &seInfo );					

					Log() << _T( "shell execute result: " ) << bResult << _T( " instapp: " ) << seInfo.hInstApp 
						<< _T( " process: " ) << seInfo.hProcess << endl;
				}
				else
				{
					Log() << L"服务器地址不是合法的HTTP地址:"<< endl;
				}

				//停止控件继续操作
				*pResult = 1;
				return TRUE;				
			}
			

			break;

		}
	case NM_META:
		{
			Log() << _T( "NM_META" ) << endl;
// 			tstring strHttpEquiv = UTF8toUTF16( (const char *)pnmHTMLView->szTarget );
// 			tstring strData = UTF8toUTF16( ( const char * ) pnmHTMLView->szData );
// 
// 			Log() << _T( "meta httpequiv: " ) << strHttpEquiv << endl;
// 			Log() << _T( "meta data: " ) << strData << endl;

			//BOOL bResult = this->GetParent()->SendMessage( WM_HTML_WND_META, (WPARAM)strHttpEquiv.c_str(), (LPARAM)strData.c_str() );
			//return bResult;
		}
		break;
	case NM_BEFORENAVIGATE:
		{
			// 等待Navigate 完成.
			m_bWaittingNavigateComplete = TRUE;

			tstring strUrl = UTF8toUTF16( (const char *)pnmHTMLView->szTarget );

			Log() << _T( "NM_BEFORENAVIGATE: " ) << strUrl << endl;

            // 对于页面载入失败的页面,不再检测是否失败。
            if ( strUrl == this->GetFailHtmlUrl() )
            {
                Log() << _T( "Open the Fail page shold not check fail load! m_bWaittingNavigateComplete = FALSE。fail page: " ) 
                    << strUrl << endl;
                m_bWaittingNavigateComplete = FALSE;
            }

			
//			MessageBox( strUrl.c_str(), TEXT( "你打开的URL链接:" ) );

			/** 记录历史. */
			if( INVALID_INDEX == m_nCurUrlHistoryIndex || ( strUrl.compare( m_tHistoryUrl[m_nCurUrlHistoryIndex] ) != 0 ) )
			{
				m_nCurUrlHistoryIndex ++;
				m_nCurUrlHistoryIndex %= MAX_HISTORY;
				if ( int( m_tHistoryUrl.size() ) <= m_nCurUrlHistoryIndex )
				{
					m_tHistoryUrl.push_back( strUrl );				
				}
				else
				{
					m_tHistoryUrl[m_nCurUrlHistoryIndex] = strUrl;
				}
				m_nHistoryEndIndex = m_nCurUrlHistoryIndex;

				if ( m_nHistoryHeadIndex == INVALID_INDEX )
				{
					m_nHistoryHeadIndex = m_nCurUrlHistoryIndex;
				}
				else if( m_nHistoryHeadIndex == m_nCurUrlHistoryIndex )
				{
					m_nHistoryHeadIndex ++;
					m_nHistoryHeadIndex %= MAX_HISTORY;
				}
			}

			BOOL bResult = this->GetParent()->SendMessage( WM_HTML_WND_PRE_LOAD, (WPARAM)strUrl.c_str() );

			return bResult;

		}
		break;

	case NM_NAVIGATECOMPLETE:
		{
			// Navigate 完成.
			tstring strUrl = UTF8toUTF16( (const char *)pnmHTMLView->szTarget );
			m_bWaittingNavigateComplete = FALSE;
			Log() << _T( "NM_NAVIGATECOMPLETE url: " ) << strUrl << endl;

			// 更新历史记录。
			if ( m_nCurUrlHistoryIndex != INVALID_INDEX )
			{
				this->m_tHistoryUrl[ m_nCurUrlHistoryIndex ] = strUrl;
			}
			
		}
		break;

	case NM_DOCUMENTCOMPLETE:
		if ( m_bWaittingNavigateComplete && m_bIsFaild == FALSE)
		{
			Log() << _T( "NM_DOCUMENTCOMPLETE not do NM_NAVIGATECOMPLETE" ) << endl;
			//tstring strUrl = UTF8toUTF16( (const char *)pnmHTMLView->szTarget );
			//Log() << _T( "m_bWaittingNavigateComplete = false Url " )<< strUrl << endl;
			tstring strFailHtml = this->GetFailHtmlUrl();
			m_bWaittingNavigateComplete = FALSE;
			this->OpenUrl( strFailHtml.c_str() );
			m_bIsFaild = TRUE;
		}
		else
		{
			m_bWaittingNavigateComplete = FALSE;
			m_bIsFaild = FALSE;
		}
		Log() << _T( "NM_DOCUMENTCOMPLETE" ) << endl;
		break;
	case NM_TITLE:
		Log() << _T( "NM_TITLE" ) <<endl;
		break;
	case NM_TITLECHANGE:
		Log() << _T( "NM_TITLECHANGE" ) << endl;
		break;
	case NM_INLINE_IMAGE:
		Log() << _T( "NM_INLINE_IMAGE" ) << endl;
		break;
	case NM_CONTEXTMENU:
		{
			//MessageBox( TEXT( "NM_CONTEXTMENU!" ) );
			NM_HTMLCONTEXT * pnmHTMLContext = (NM_HTMLCONTEXT *)lParam;
			HandlePopupMenu(pnmHTMLContext->pt);
			*pResult = 1;
			return TRUE;
			//return FALSE;
		}
		break;
	default:
		Log() << _T( "html notify: pnmHTMLView->hdr.code = " ) << pnmHTMLView->hdr.code << endl;
		break;
	}		

	return CDialog::OnNotify(wParam, lParam, pResult);
}
예제 #20
0
void FormatTime(ScriptValue &s, ScriptValue *args) {
	unsigned char *c = args[0].stringVal->value;
	if (!AllocateStringValue(s, (int)(3 * strlen(c) + 14))) return;
	static bool settz = 0;
	if (args[0].stringVal->value[0] == 'S') {
		args[0].stringVal->value[0] = args[0].stringVal->value[0];
	}
	// Nasty layout, but boils down to:  If a tz is specified, try to set it.
	// If either couldn't set it or not specified and was set previously, unset it.
	while (1) {
		if (args[2].stringVal->len >= 1 && args[2].stringVal->len <= 20) {
			if (args[2].stringVal->len < 4 || (args[2].stringVal->len == 4 && !IsNumber(args[2].stringVal->value[3]))) {
				for (int i=0; i<sizeof(tzlist)/sizeof(tzlist[0]); i++) {
					if (!stricmp(tzlist[i][0], (char*)args[2].stringVal->value)) {
						char temp[60] = "TZ=";
						sprintf(temp+3, tzlist[i][1]);
						if (!_putenv(temp)) {
							_tzset();
							settz = 1;
							break;
						}
					}
				}
			}
			else {
				wchar_t temp[60] = L"TZ=";
				if (UTF8toUTF16(temp+3, args[2].stringVal->value, args[2].stringVal->len) > 0) {
					if (!_wputenv(temp)) {
						_tzset();
						settz = 1;
						break;
					}
				}
			}
		}
		if (settz) {
			if (!_putenv("TZ=")) {
				_tzset();
				settz = 0;
			}
		}
		break;
	}
	static LCID locale = 0;
	if (!locale) {
		locale = GetThreadLocale();
	}
	__int64 x = args[1].intVal;
	if (!x) x = time64i();
	tm *date = _localtime64(&x);
	SYSTEMTIME st;

	st.wYear = date->tm_year+1900;
	st.wMonth = date->tm_mon+1;
	st.wDayOfWeek = date->tm_wday;
	st.wDay = date->tm_mday;
	st.wHour = date->tm_hour;
	st.wMinute = date->tm_min;
	st.wSecond = date->tm_sec;
	st.wMilliseconds = 0;
	char *out = (char*) s.stringVal->value;
	char * start = (char*) c;
	//static const char *wday[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
	//static const char *wday2[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
	//static const char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
	//static const char *months2[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
	while (*start) {
		if (LCASE(start[0]) == 'h') {
			int h = date->tm_hour;
			if (*start == 'h') {
				if (h >12) h -= 12;
				else if (!h) h = 12;
			}
			GenericDisplay(start, out, h);
		}
		else if (LCASE(start[0]) == 'n')
			GenericDisplay(start, out, date->tm_min);
		else if (LCASE(start[0]) == 's')
			GenericDisplay(start, out, date->tm_sec);
		else if (LCASE(start[0]) == 't') {
			char letter = 'A';
			if (date->tm_hour >= 12) letter = 'P';
			if (start[0] == 't')
				out++[0]  = LCASE(letter);
			else
				out++[0]  = letter;
			start ++;
			if (start[0] == 't') {
				out++[0]  = 'm';
				start ++;
			}
			else if (start[0] == 'T') {
				out++[0]  = 'M';
				start ++;
			}
		}
		else if (LCASE(start[0]) == 'd') {
			if (LCASE(start[1]) == 'd' && LCASE(start[2]) == 'd') {
				start += 2;
				int incr = 1;
				wchar_t day[100];
				int len;
				if (LCASE(start[1]) == 'd') {
					len = GetDateFormat(locale, 0, &st, L"dddd", day, sizeof(day)/sizeof(wchar_t));
					//day = wday2[date->tm_wday];
					incr = 2;
				}
				else {
					len = GetDateFormat(locale, 0, &st, L"ddd", day, sizeof(day)/sizeof(wchar_t));
				}
				if (len < 0) len = 0;
				else if (len > 99) len = 99;
				day[len] = 0;
				int e = GetLastError();
				wchar_t *p = day;
				int i;
				for (i=0; i<len && i <99; i++) {
					p[i] = towupper(p[i]);
					if (start[0] != 'D') break;
				}
				UTF16toUTF8(out, day);
				out += strlen(out);
				start += incr;
			}
			else
				GenericDisplay(start, out, date->tm_mday);
		}
		else if (LCASE(start[0]) == 'm') {
			if (LCASE(start[1]) == 'm' && LCASE(start[2]) == 'm') {
				start += 2;
				int incr = 1;
				wchar_t day[100];
				int len;
				if (LCASE(start[1]) == 'm') {
					len = GetDateFormat(locale, 0, &st, L"MMMM", day, sizeof(day)/sizeof(wchar_t));
					//day = wday2[date->tm_wday];
					incr = 2;
				}
				else {
					len = GetDateFormat(locale, 0, &st, L"MMM", day, sizeof(day)/sizeof(wchar_t));
				}
				if (len < 0) len = 0;
				else if (len > 99) len = 99;
				day[len] = 0;
				int e = GetLastError();
				wchar_t *p = day;
				int i;
				for (i=0; i<len && i <99; i++) {
					p[i] = towupper(p[i]);
					if (start[0] != 'M') break;
				}
				UTF16toUTF8(out, day);
				out += strlen(out);
				start += incr;
			}
			else
				GenericDisplay(start, out, 1+date->tm_mon);
		}
		else if (LCASE(start[0]) == 'y') {
			int year = date->tm_year%100;
			if (LCASE(start[1]) == 'y') {
				start++;
				if (LCASE(start[1]) == 'y') {
					start ++;
					year = 1900 + date->tm_year;
					if (LCASE(start[1]) == 'y') start++;
				}
			}
			sprintf(out, "%02i", year);
			out+=strlen(out);
			start++;
		}
		else {
			out ++[0] = start++[0];
		}
		if ((out-(char*)s.stringVal->value) + 20 > s.stringVal->len) {
			size_t d = out - (char*)s.stringVal->value;
			ResizeStringValue(s, s.stringVal->len+50);
			out = (char*)s.stringVal->value + d;
		}
	}
	ResizeStringValue(s, (int)(out-(char*)s.stringVal->value));
}