Ejemplo n.º 1
0
void NS_ISERVER::CLocalServer::LocalAuditUserQuit(CString strTermID, CString strIP,UINT nMemberID)
{
	NET_HEAD_MAN head = {0};
	head.Version = COM_VER;
	head.Length = sizeof TIBAAuditUserQuit;
	head.Cmd = C_MANGER_AUDITUSERQUIT;

	TIBAAuditUserQuit info = {0};

	_snprintf(info.termID, LEN_TERMID, CT2A(strTermID));
	_snprintf(info.termIP, LEN_IPADDR, CT2A(strIP));
	info.memberID=nMemberID;

	CByteArray buffer;
	buffer.SetSize(sizeof NET_HEAD_MAN + head.Length);

	memcpy(buffer.GetData(), &head, sizeof NET_HEAD_MAN);
	memcpy(buffer.GetData() + sizeof NET_HEAD_MAN, &info, sizeof TIBAAuditUserQuit);

	m_lpSocket->SendBuffer(buffer.GetData(), buffer.GetSize());

	buffer.RemoveAll();

	IBA_LOG(_T("发送实名下机信息,TermID=%s,IP=%s,MemberID=%d"),strTermID,strIP,nMemberID);
}
Ejemplo n.º 2
0
void NS_ISERVER::CLocalServer::LocalAskNotice(BOOL bSigned)
{
	NET_HEAD_MAN head = {0};
	head.Version = COM_VER;
	head.Length = sizeof tag_ask_read_notice;
	head.Cmd = C_MANGER_ASKREADNOTICE;

	tag_ask_read_notice notice = {0};
	notice.nAsk = (UINT)bSigned;

	CByteArray buffer;
	buffer.SetSize(sizeof NET_HEAD_MAN + head.Length);

	memcpy(buffer.GetData(), &head, sizeof NET_HEAD_MAN);
	memcpy(buffer.GetData() + sizeof NET_HEAD_MAN, &notice, sizeof tag_ask_read_notice);

	m_lpSocket->SendBuffer(buffer.GetData(), buffer.GetSize());

	buffer.RemoveAll();

	if (bSigned)
	{
		CIBALog::GetInstance()->Write(_T("发送通告签收成功"));
	}
	else
	{
		CIBALog::GetInstance()->Write(_T("发送获取通告的请求"));
	}
	
}
Ejemplo n.º 3
0
bool CMinizip::Extract(LPCTSTR FileName, LPCTSTR DestPath, UINT BufSize)
{
    USES_CONVERSION;
    if (unzLocateFile(m_ZipFile, T2CA(FileName), 0) != UNZ_OK)
        return(FALSE);
    if (unzOpenCurrentFile(m_ZipFile) != UNZ_OK)
        return(FALSE);
    CByteArray	ba;
    ba.SetSize(BufSize);
    bool	retc = FALSE;	// assume failure
    TRY {
        CFile	DestFile(DestPath, CFile::modeCreate | CFile::modeWrite);
        int	BytesRead;
        while ((BytesRead = unzReadCurrentFile(m_ZipFile, ba.GetData(), BufSize)) > 0) {
            DestFile.Write(ba.GetData(), BytesRead);
        }
        if (!BytesRead)	// if EOF
            retc = TRUE;	// success provided current file closes OK
    }
    CATCH (CFileException, e) {
        e->ReportError();
    }
    END_CATCH
    if (unzCloseCurrentFile(m_ZipFile) != UNZ_OK)	// close fails if bad CRC
        return(FALSE);
    return(retc);
}
Ejemplo n.º 4
0
CString ConvertReceivedDataToString(CByteArray & data)
   {
     // data is UTF-8 encoded
    CArray<WCHAR, WCHAR> wc;
     // First, compute the amount of space required.  n will include the
     // space for the terminal NUL character
    INT_PTR n = ::MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)data.GetData(), (int)data.GetSize(), NULL, 0);
    if(n == 0)
       { /* failed */
        DWORD err = ::GetLastError();
        TRACE(_T("%s: MultiByteToWideChar (1) returned error %d\n"), AfxGetApp()->m_pszAppName, err);
        return CString(_T(""));
       } /* failed */
    else
       { /* success */
        wc.SetSize(n);
        n = ::MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)data.GetData(), (int)data.GetSize(), (LPWSTR)wc.GetData(), (int)n);
        if(n == 0)
           { /* failed */
            DWORD err = ::GetLastError();
            TRACE(_T("%s: MultiByteToWideChar (2) returned error %d\n"), AfxGetApp()->m_pszAppName, err);
            return CString(_T(""));
           } /* failed */
       } /* success */     

     // Data is now in Unicode
     // If we are a Unicode app we are done
     // If we are an ANSI app, convert it back to ANSI

#ifdef _UNICODE
     // If this is a Unicode app we are done
    return CString(wc.GetData(), (int)wc.GetSize());
#else // ANSI
    // Invert back to ANSI
    CString s;
    n = ::WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wc.GetData(), (int)wc.GetSize(), NULL, 0, NULL, NULL);
    if(n == 0)
       { /* failed */
        DWORD err = ::GetLastError();
        TRACE(_T("%s: WideCharToMultiByte (1) returned error %d\n"), AfxGetApp()->m_pszAppName, err);
        return CString("");
       } /* failed */
    else
       { /* success */
        LPSTR p = s.GetBuffer((int)n);
        n = ::WideCharToMultiByte(CP_ACP, 0, wc.GetData(), (int)wc.GetSize(), p, (int)n, NULL, NULL);
        if(n == 0)
           { /* conversion failed */
            DWORD err = ::GetLastError();
            TRACE(_T("%s: WideCharToMultiByte (2) returned error %d\n"), AfxGetApp()->m_pszAppName, err);
            s.ReleaseBuffer();
            return CString("");
           } /* conversion failed */
        s.ReleaseBuffer();
        return s;
       } /* success */
#endif
   } // ConvertReceivedDataToString
Ejemplo n.º 5
0
HRESULT CClipboard::GetData(BYTE *pData, UINT *pnDataLength, UINT nClipboardKey)
{
   HRESULT hr = S_OK;

   if (pnDataLength == NULL)
      return E_POINTER;
   if (nClipboardKey == 0)
      return E_INVALIDARG;

   CByteArray *pByteArray = NULL;
   if (m_mapData.Lookup(nClipboardKey, pByteArray))
   {
      if (pData == NULL)
         *pnDataLength = pByteArray->GetSize();
      else
      {
         UINT nToCopy = min(*pnDataLength, (unsigned)pByteArray->GetSize());
         memcpy(pData, pByteArray->GetData(), nToCopy);
         *pnDataLength = nToCopy;
      }
   }
   else
      hr = S_FALSE; // element not found


   return hr;
}
Ejemplo n.º 6
0
BOOL CWDRealName::SendToProxy(CByteArray &buffer)
{
	BOOL bRet = FALSE;

	CWinSocket ProxySocket;

	if (ProxySocket.Create())
	{
		if (ProxySocket.Connect(CNetBarConfig::GetInstance()->GetProxyIP(), 7834, 5000))
		{
			if (ProxySocket.Send(buffer.GetData(), buffer.GetSize()) > 0)
			{
				bRet = TRUE;
			}
		}
		else
		{
			IBA_LOG(_T("Can't connect to %s(7834)!"), CNetBarConfig::GetInstance()->GetProxyIP());
		}

		ProxySocket.Close();
	}

	return bRet;
}
Ejemplo n.º 7
0
void NS_ISERVER::CLocalServer::LocalLoginZdReturn(ID_LOGINRETURN_ZD *pLogin_zd )
{
	NET_HEAD_MAN head = {0};
	head.Version = COM_VER;
	head.Length = sizeof ID_LOGINRETURN_ZD;
	head.Cmd = C_LOGIN_ZD;

	CByteArray buffer;
	buffer.SetSize(sizeof NET_HEAD_MAN + head.Length);

	memcpy(buffer.GetData(), &head, sizeof NET_HEAD_MAN);
	memcpy(buffer.GetData() + sizeof NET_HEAD_MAN, pLogin_zd, sizeof ID_LOGINRETURN_ZD);

	m_lpSocket->SendBuffer(buffer.GetData(), buffer.GetSize());

	buffer.RemoveAll();

	IBA_LOG0(_T("发送智多实名登录"));
}
Ejemplo n.º 8
0
void CChordEaseDoc::ReadSongText(CFile& File, CString& Text)
{
	ULONGLONG	LongLen = File.GetLength();
	ASSERT(LongLen <= UINT_MAX);
	UINT	len = static_cast<UINT>(LongLen);
	// assume input file is ANSI text
#ifdef UNICODE
	USES_CONVERSION;
	CByteArray	buf;
	buf.SetSize(len + 1);	// allocate buffer; extra byte for terminator
	File.Read(buf.GetData(), len);	// read ANSI text into byte buffer
	LPCSTR	pText = reinterpret_cast<LPCSTR>(buf.GetData());
	Text = A2W(pText);	// convert text from ANSI to Unicode and store
#else	// ANSI
	LPTSTR	pText = Text.GetBuffer(len);	// allocate text buffer
	File.Read(pText, len);	// read text into buffer
	Text.ReleaseBuffer(len);	// not null-terminated, so specify length
#endif
}
Ejemplo n.º 9
0
void CLocalServer::SendBuffer(const NET_HEAD_MAN* pHead, const void* pBuf, BOOL bCheckStatus)
{
	if (bCheckStatus && m_CheckInStatus != 1)
	{
		return;
	}

	CByteArray buffer;
	buffer.SetSize(sizeof NET_HEAD_MAN + pHead->Length);

	memcpy(buffer.GetData(), pHead, sizeof NET_HEAD_MAN);

	if (pBuf != NULL)
	{
		memcpy(buffer.GetData() + sizeof NET_HEAD_MAN, pBuf, pHead->Length);
	}

	m_lpSocket->SendBuffer(buffer.GetData(), buffer.GetSize());
	buffer.RemoveAll();
}
Ejemplo n.º 10
0
bool CPackets::WriteHostNameReply()
{
	static const int MAX_HOST_NAME = 256;
	DWORD	PktLen = sizeof(PACKET_HDR) + MAX_HOST_NAME;
	CByteArray	pkt;
	pkt.SetSize(PktLen);
	FRAP_HOST_NAME_REPLY	*pp = (FRAP_HOST_NAME_REPLY *)pkt.GetData();
	if (gethostname(pp->HostName, MAX_HOST_NAME) == SOCKET_ERROR)
		return(FALSE);
	InitHdr(*pp, PMID_HOST_NAME_REPLY, PktLen);
	return(Write(*pp, PktLen));
}
Ejemplo n.º 11
0
BOOL CMFCControlContainer::GetControlData(WORD nIDC, DWORD& dwSize, BYTE*& pbData)
{
	CObject* pData = NULL;
	if (m_mapControlData.Lookup(nIDC, pData) && pData != NULL)
	{
		CByteArray* pArray = (CByteArray*)pData;
		dwSize = (DWORD)pArray->GetSize();
		pbData = pArray->GetData();
		return TRUE;
	}

	return FALSE;
}
Ejemplo n.º 12
0
void CLocalServer::LocalUnlockScreen(INT_PTR nIndex, CString strUnlockPwd)
{
	if (m_CheckInStatus != 1)
	{
		return;
	}

	if (ComputerList.IsInvaildIndex(nIndex))
	{
		return;
	}

	CComputerInfo& computer = ComputerList.GetComputer(nIndex);

	SCREEN_TERMINFO snapComputer = {0};
	_snprintf(snapComputer.termID, LEN_TERMID, CW2A(computer.GetTerminalID()));
	_snprintf(snapComputer.termIP, LEN_IPADDR, CW2A(computer.GetComputerIP()));

	NET_HEAD_MAN head = {0};

	head.Version = COM_VER;
	head.Length = sizeof SCREEN_TERMINFO + sizeof CHECK_PASSWORD;
	head.Cmd = C_MANGER_UNLOCKSCREEN;

	CHECK_PASSWORD pwd = {0};

	_snprintf(pwd.cPassword, LEN_CLIPASSWORD, CW2A(strUnlockPwd));
	
	CByteArray buffer;
	buffer.SetSize(sizeof NET_HEAD_MAN + head.Length);

	memcpy(buffer.GetData(), &head, sizeof NET_HEAD_MAN);
	memcpy(buffer.GetData() + sizeof NET_HEAD_MAN, &snapComputer, sizeof SCREEN_TERMINFO);
	memcpy(buffer.GetData() + sizeof NET_HEAD_MAN + sizeof SCREEN_TERMINFO, &pwd, sizeof CHECK_PASSWORD);

	m_lpSocket->SendBuffer(buffer.GetData(), buffer.GetSize());

	buffer.RemoveAll();
}
Ejemplo n.º 13
0
void CCommandProcessor::OnRespondGetLog(BYTE *pBuffer, size_t /*bufLen*/)
{
	if (!m_bGetLog)
	{
		return;
	}
	
	m_bGetLog = FALSE;

	try
	{
		NET_HEAD_MAN head = {0};
		SCREEN_TERMINFO stTermInfo = {0};

		GetHead(pBuffer, &head);
		GetBody(pBuffer, &stTermInfo, sizeof(stTermInfo));

		CByteArray buf;
		buf.SetSize(head.Length - sizeof(stTermInfo));
		CopyMemory(buf.GetData(), pBuffer + sizeof(head) + sizeof(stTermInfo), buf.GetSize());

		CString strPicFile(theApp.GetWorkPath() + _T("\\IBATermLog\\"));
		CIBAHelpper::MakeSurePathExists(strPicFile);

		strPicFile.Append(CA2W(stTermInfo.termID));
		strPicFile.Trim();

		if (head.Version == 1) //zip
		{
			strPicFile.AppendFormat(_T("[%s].zip"), CIBAHelpper::GetCurrentTimeAsString());
		}
		else
		{
			strPicFile.AppendFormat(_T("[%s].log"), CIBAHelpper::GetCurrentTimeAsString());
		}
		
		SaveFile(strPicFile, buf);

	}
	catch (CFileException* e)
	{		
		e->Delete();
		CIBALog::GetInstance()->Write(_T("Get Log: Operation file failed."));
	}
	catch (...)
	{
		CIBALog::GetInstance()->Write(_T("Get Log failed."));
	}
}
Ejemplo n.º 14
0
void CMFCControlContainer::SetControlData(WORD nIDC, DWORD dwSize, BYTE* pbData)
{
	CByteArray* pArray = new CByteArray;
	pArray->SetSize(dwSize);

	BYTE* pbBuffer = pArray->GetData();
	if (memcpy_s(pbBuffer, dwSize, pbData, dwSize) != 0)
	{
		delete pArray;
		ASSERT(FALSE);
		return;
	}

	m_mapControlData.SetAt(nIDC, pArray);
}
Ejemplo n.º 15
0
bool CPackets::WriteStripDone(UINT JobID, UINT ThreadIdx, float RenderTime, UINT y1, UINT y2, const ESCTIME *Strip, UINT StripSize)
{
	UINT	PktLen = sizeof(FRAP_STRIP_DONE_HDR) + StripSize;
	CByteArray	pkt;
	pkt.SetSize(PktLen);
	FRAP_STRIP_DONE	*pp = (FRAP_STRIP_DONE *)pkt.GetData();
	InitHdr(*pp, PMID_STRIP_DONE, PktLen);
	pp->JobID = JobID;
	pp->ThreadIdx = ThreadIdx;
	pp->RenderTime = RenderTime;
	pp->y1 = y1;
	pp->y2 = y2;
	pp->StripSize = StripSize;
	memcpy(pp->Strip, Strip, StripSize);
	return(Write(*pp, PktLen));
}
Ejemplo n.º 16
0
bool CTobCompiler::CompileFile(LPCTSTR fsrcname, LPCTSTR fdstname, F_ErrorHandler ErrorHandler)
{
	Reset();
	CString err;
	bool haserr = false;
	m_line = 1;

	m_fsrc = fopen(fsrcname, "rb");
	if(!m_fsrc)
	{
		m_err.Format("can't open src file '%s'", fsrcname);
		ErrorHandler(GetErrorString(err));
		return false;
	}
	for(;;)
	{
		EToken r = CompilePass1();
		if(r == ERR_EOF) break;
		if(r < 0)
		{
			haserr = true;
			if(!ErrorHandler(GetErrorString(err))) return false;
		}
		if(r == ERR_SEVERE) return false;
	}
	fclose(m_fsrc); m_fsrc = 0;

	if(!CompilePass2(ErrorHandler) || haserr) return false;

	m_fdst = fopen(fdstname, "wb");
	if(!m_fdst)
	{
		m_err.Format("can't create dst file '%s'", fdstname);
		ErrorHandler(GetErrorString(err));
		return false;
	}
	if(m_bin.GetSize() > 0 && fwrite(m_bin.GetData(), m_bin.GetSize(), 1, m_fdst) != 1)
	{
		fclose(m_fdst); m_fdst = 0;
		m_err.Format("can't write dst file '%s'", fdstname);
		ErrorHandler(GetErrorString(err));
		return false;
	}
	fclose(m_fdst); m_fdst = 0;
	return true;
}
Ejemplo n.º 17
0
bool CPackets::WriteDib(UINT JobID, UINT FrameID, float RenderTime, PVOID DibBits, const DIB_INFO& DibInfo)
{
	UINT	DibLen = DibInfo.Length;
	UINT	PktLen = sizeof(FRAP_DIB_HDR) + DibLen;
	CByteArray	pkt;
	pkt.SetSize(PktLen);
	FRAP_DIB	*pp = (FRAP_DIB *)pkt.GetData();
	InitHdr(*pp, PMID_DIB, PktLen);
	pp->JobID = JobID;
	pp->FrameID = FrameID;
	pp->RenderTime = RenderTime;
	pp->Width = DibInfo.Size.cx;
	pp->Height = DibInfo.Size.cy;
	pp->BitCount = DibInfo.BitCount;
	pp->DibLen = DibLen;
	memcpy(pp->DibBits, DibBits, DibLen);
	return(Write(*pp, PktLen));
}
Ejemplo n.º 18
0
void CHtmlView::BeforeNavigate2(LPDISPATCH /* pDisp */, VARIANT* URL,
		VARIANT* Flags, VARIANT* TargetFrameName,
		VARIANT* PostData, VARIANT* Headers, BOOL* Cancel)
{
	ASSERT(V_VT(URL) == VT_BSTR);
	ASSERT(V_VT(TargetFrameName) == VT_BSTR);
	ASSERT(V_VT(PostData) == (VT_VARIANT | VT_BYREF));
	ASSERT(V_VT(Headers) == VT_BSTR);
	ASSERT(Cancel != NULL);

	USES_CONVERSION;

	VARIANT* vtPostedData = V_VARIANTREF(PostData);
	CByteArray array;
	if (V_VT(vtPostedData) & VT_ARRAY)
	{
		// must be a vector of bytes
		ASSERT(vtPostedData->parray->cDims == 1 && vtPostedData->parray->cbElements == 1);

		vtPostedData->vt |= VT_UI1;
		COleSafeArray safe(vtPostedData);

		DWORD dwSize = safe.GetOneDimSize();
		LPVOID pVoid;
		safe.AccessData(&pVoid);

		array.SetSize(dwSize);
		LPBYTE lpByte = array.GetData();

		memcpy(lpByte, pVoid, dwSize);
		safe.UnaccessData();
	}
	// make real parameters out of the notification

	CString strTargetFrameName(V_BSTR(TargetFrameName));
	CString strURL = V_BSTR(URL);
	CString strHeaders = V_BSTR(Headers);
	DWORD nFlags = V_I4(Flags);

	// notify the user's class
	OnBeforeNavigate2(strURL, nFlags, strTargetFrameName,
		array, strHeaders, Cancel);
}
Ejemplo n.º 19
0
void CCommandProcessor::SaveFile(CString strFile, CByteArray &buf)
{
	CFile File;

	if (File.Open(strFile, CFile::modeCreate | CFile::modeWrite))
	{
		File.Write(buf.GetData(), (UINT)buf.GetSize());
		File.Flush();
		File.Close();
		
		if (CIBAConfig::GetInstance()->GetOpenAfterSave())
		{
			ShellExecute(NULL, _T("open"), strFile, NULL, NULL, SW_SHOWNORMAL);
		}
	}
	else
	{
		CIBALog::GetInstance()->Write(_T("SaveFile: Create file failed."));
	}
}
void CXTPSyntaxEditLexCfgFileReader::WriteString(CFile& file, LPCTSTR pcszString)
{
	int nStrLen = (int)_tcslen(pcszString);

#ifdef _UNICODE
	CByteArray arBufferMBCS;
	arBufferMBCS.SetSize(nStrLen*2+4);

	char* pTextMBCS = (char*)arBufferMBCS.GetData();

	int nNewLen = WideCharToMultiByte(CP_ACP, 0,
		pcszString, -1, pTextMBCS, nStrLen*2+1, NULL, NULL);

	nStrLen = nNewLen ? nNewLen-1 : 0;
#else
	char* pTextMBCS = (char*)pcszString;
#endif

	file.Write(pTextMBCS, nStrLen);
	file.Write("\r\n", 2);
}
Ejemplo n.º 21
0
HRESULT CClipboard::AddData(BYTE *pData, UINT nDataLength, UINT nClipboardKey)
{
   if (pData == NULL && nDataLength > 0)
      return E_POINTER;
   if (nClipboardKey == 0)
      return E_INVALIDARG;

   CByteArray *pByteArray = new CByteArray();
   pByteArray->SetSize(nDataLength, 0);
   memcpy(pByteArray->GetData(), pData, nDataLength);

   CByteArray *pByteArrayOld = NULL;
   if (m_mapData.Lookup(nClipboardKey, pByteArrayOld))
   {
      m_mapData.RemoveKey(nClipboardKey);
      delete pByteArrayOld;
   }

   m_mapData.SetAt(nClipboardKey, pByteArray);

   return S_OK;
}
Ejemplo n.º 22
0
void CRichEditCtrlGS::SetRTF(const UINT resID)
{ // Obtain a handle and the memory to the resource
  HINSTANCE hApp = ::GetModuleHandle(0);
  ASSERT(hApp);
  HRSRC hResInfo = ::FindResource(hApp, MAKEINTRESOURCE(resID), TEXT("RTF"));
  if( NULL == hResInfo ) return;
  HGLOBAL hRes = ::LoadResource(hApp, hResInfo);
  if( NULL == hRes ) return;
  LPVOID pRTFText = ::LockResource(hRes);
  if( NULL == pRTFText ) return;
  DWORD dwRTFSize = ::SizeofResource(hApp, hResInfo);
  if( 0 == dwRTFSize )
    { ::FreeResource(hRes);
	  return;
    }
  CByteArray arrbRTF;
  arrbRTF.SetSize(dwRTFSize);
  LPBYTE pArrRTF = arrbRTF.GetData();
  ::CopyMemory(pArrRTF,pRTFText,dwRTFSize);
  ::FreeResource(hRes);
  SetRTF(arrbRTF);
}
Ejemplo n.º 23
0
DWORD CALLBACK CRichEditCtrlGS::StreamOutCByteArray(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb)
{ SCookieByteArray *pCookie = (SCookieByteArray *)dwCookie;
  long lWriteSize = cb; // We can only Write such much
  *pcb = 0;             // Till now we have nothing written so far

  if( pCookie->lStart < 0 )
	{ return (0); // Nothing to do
	}
  if( 0 == cb )
	{ return(0); // Nothing to do
	}
  if( NULL == pCookie->pOutText )
	{ return(0); // Nothing to do
	}
  CByteArray arrBuffer;
  arrBuffer.SetSize(lWriteSize);
  BYTE *pByte = arrBuffer.GetData();
  memcpy(pByte,pbBuff,lWriteSize);
  pCookie->pOutText->Append(arrBuffer);
  *pcb = lWriteSize;   
  pCookie->lStart += lWriteSize;
  return 0;
}
Ejemplo n.º 24
0
CTobCompiler::EToken CTobCompiler::CompilePass1()
{
    EToken r, LastToken;
    CString str, buf, sizebuf;
    CByteArray* bin;
    SValueType* val;
    SExpression* exp;

    for(;;)
    {
        BOOL bSkipGetToken = FALSE;
        if ((r = GetToken(str)) <= 0) return r;
_SkipGetToken:
        if (r == SYM_DEF)
        {
/*
            if (m_bin.GetSize() > 0)
            {
                m_err = "const token can not defined after data";
                return ERR_NORMAL;
            }
*/
            if ((r = GetToken(str)) < 0) return r;
            if (r != SYM_TOKEN)
            {
                m_err = "not found token after '@'";
                return ERR_NORMAL;
            }

            if (str == "_IGNORECASE")
            {
                m_Option.bIgnoreCase = TRUE;
                continue;
            }

            if ((r = GetToken(buf)) < 0) return r;
            if (r == SYM_BIN)
            {
                bin = new CByteArray;
                if ((r = GetBinary(*bin)) < 0) { delete bin; return r; }
                AddMap(m_binmap, str, bin);
            }
            else if (r == SYM_STR)
            {
                bin = new CByteArray;
                if ((r = GetString(*bin)) < 0) { delete bin; return r; }
                AddMap(m_binmap, str, bin);
            }
            else if (r == SYM_INT)
            {
                ULONG Length;
                BOOL bHex = (buf[0] == '0' && buf[1] == 'x');

                r = GetToken(sizebuf);
                LastToken = r;
                if (r == SYM_TYPE)
                {
                    r = GetToken(sizebuf);
                    if (r != SYM_TOKEN)
                    {
                        m_err = "not found type after ':'";
                        return ERR_NORMAL;
                    }

                    Length = GetSizeFromType(sizebuf[0]);
                    if (Length == -1)
                    {
                        m_err.Format("unknown type '%c' after ':'", sizebuf[0]);
                        return ERR_NORMAL;
                    }
                }
                else
                {
                    Length = -1;
                }
                val = new SValueType((int)strtoul(buf, NULL, bHex ? 16 : 10), Length);
                AddMap(m_valmap, str, val);

                if (Length == -1)
                    bSkipGetToken = TRUE;

                r = SYM_INT;
            }
            else if (r == SYM_FLOAT)
            {
                AddMap(m_valmap, str, new SValueType(atof(buf)));
            }
            else
            {
                m_err.Format("not found '[' or ''' or '\"' or number after '@%s'", (LPCTSTR)str);
                return ERR_NORMAL;
            }

            if (m_Option.bIgnoreCase)
                str.MakeUpper();

            if (str == "_DEFI")
            {
                if (r != SYM_INT || val->ival < 1 || val->ival > 4)
                {
                    m_err = "_DEFI must be 1/2/3/4";
                    return ERR_NORMAL;
                }
                m_Option.DefInt = val->ival;
            }
            else if (str == "_DEFF")
            {
                if (r != SYM_INT || val->ival != 4 && val->ival != 8)
                {
                    m_err = "_DEFF must be 4/8";
                    return ERR_NORMAL;
                }
                m_Option.DefFloat = val->ival;
            }
            else if (str == "_MOD")
            {
                if (r != SYM_INT)
                {
                    m_err = "_MOD must be number";
                    return ERR_NORMAL;
                }

                while (m_bin.GetSize() % val->ival)
                    m_bin.Add(0);
            }
            else if (str == "_INCLUDE")
            {
                FILE *fsrc;
                WCHAR szPath[MAX_PATH];
                CByteArray *bin;

                if (m_Option.bIgnoreCase)
                    str.MakeLower();

                if (!m_binmap.Lookup(str, bin))
                    continue;

                m_binmap.RemoveKey(str);

                MultiByteToWideChar(
                    CP_GB2312,
                    0,
                    (LPSTR)bin->GetData(),
                    -1,
                    szPath,
                    countof(szPath));

                delete bin;

                fsrc = m_fsrc;
                m_fsrc = _wfopen(szPath, L"rb");
                if (m_fsrc == NULL)
                {
                    m_fsrc = fsrc;
                    m_err.Format("can't open include file '%S'", szPath);
                    return ERR_SEVERE;
                }
                else
                {
                    EToken r;
                    for(;;)
                    {
                        r = CompilePass1();
                        if (r == ERR_EOF)
                            break;

                        if (r < 0)
                        {
                            if (!ErrorHandlerInternal(GetErrorString(m_err)))
                                break;
                        }

                        if (r == ERR_SEVERE)
                            break;
                    }

                    fclose(m_fsrc);
                    m_fsrc = fsrc;
                    if (r < 0)
                        return r;
                }
            }

            if (bSkipGetToken)
            {
                str = sizebuf;
                r = LastToken;
                goto _SkipGetToken;
            }
        }
        else if (r == SYM_BIN)
        {
            if ((r = GetBinary(m_bin)) < 0) return r;
        }
        else if (r == SYM_STR)
        {
            if ((r = GetString(m_bin)) < 0) return r;
        }
        else if (r == SYM_TOKEN)
        {
            if (!m_binmap.Lookup(str, bin))
            {
                m_err.Format("unknown token '%s'", (LPCTSTR)str);
                return ERR_NORMAL;
            }
            m_bin.Append(*bin);
        }
        else if (r == SYM_LABEL)
        {
            if ((r = GetToken(str)) < 0) return r;
            if (r != SYM_TOKEN)
            {
                m_err = "not found token after '#'";
                return ERR_NORMAL;
            }
            if (m_valmap.Lookup(str, val))
            {
                m_err.Format("already defined label token '%s'", (LPCTSTR)str);
                return ERR_NORMAL;
            }
            m_valmap.SetAt(str, new SValueType(m_bin.GetSize()));
        }
        else if (r == SYM_EXP_BEGIN)
        {
            int i = m_exparr.GetSize();
            do
            {
                int len = m_Option.DefInt;
                BOOL hastype = FALSE;
                exp = new SExpression(m_bin.GetSize(), m_line);
                for(;;)
                {
                    if ((r = GetToken(buf)) < 0)
                    {
                        delete exp;
                        return r;
                    }

                    if (r == SYM_TOKEN)
                    {
                        val = NULL;
                        if (!hastype && len > 0 && m_valmap.Lookup(buf, val) && val->isfloat)
                            len = -m_Option.DefFloat;
                        exp->m_item.Add(buf);
                        if (val != NULL && val->m_size != -1)
                            len = val->isfloat ? -val->m_size : val->m_size;
                    }
                    else if (r == SYM_ADD)
                    {
                        exp->m_item.Add("+");
                    }
                    else if (r == SYM_SUB)
                    {
                        exp->m_item.Add("-");
                    }
                    else if (r == SYM_DEF)
                    {
                        exp->m_item.Add("@");
                    }
                    else if (r == SYM_INT)
                    {
                        exp->m_item.Add(buf);
                    }
                    else if (r == SYM_FLOAT)
                    {
                        if (!hastype && len > 0)
                            len = -m_Option.DefFloat;
                        exp->m_item.Add(buf);
                    }
                    else if (r == SYM_TYPE)
                    {
                        int newlen;
                        if ((r = GetToken(buf)) < 0) { delete exp; return r; }
                        if (r != SYM_TOKEN)
                        {
                            delete exp;
                            m_err = "not found type after ':'";
                            return ERR_NORMAL;
                        }

                        newlen = GetSizeFromType(buf[0]);
                        if (newlen == -1)
                        {
                            delete exp;
                            m_err.Format("unknown type '%c' after ':'", buf[0]);
                            return ERR_NORMAL;
                        }

                        if (hastype && newlen != len)
                        {
                            delete exp;
                            m_err = "found different types in one expression";
                            return ERR_NORMAL;
                        }
                        hastype = TRUE;
                        len = newlen;
                    }
                    else if (r == SYM_BIN)
                    {
                        if (exp->m_item.GetSize() > 0)
                        {
                            delete exp;
                            m_err = "found different types in one expression";
                            return ERR_NORMAL;
                        }
                        if ((r = GetBinary(m_bin)) < 0) { delete exp; return r; }
                    }
                    else if (r == SYM_STR)
                    {
                        if (exp->m_item.GetSize() > 0)
                        {
                            delete exp;
                            m_err = "found different types in one expression";
                            return ERR_NORMAL;
                        }
                        if ((r = GetString(m_bin)) < 0) { delete exp; return r; }
                    }
                    else if (r == SYM_NEXT || r == SYM_EXP_END)
                    {
                        break;
                    }
                    else
                    {
                        delete exp;
                        m_err.Format("unknown or bad symbol1 '%s' in expression", (LPCTSTR)str);
                        return ERR_NORMAL;
                    }
                }
                if (exp->m_item.GetSize() <= 0)
                {
                    delete exp;
                }
                else
                {
                    exp->m_size = len;
                    m_exparr.Add(exp);
                    if (len < 0) len = -len;
                    while(len--)
                        m_bin.Add(0);
                }
            }
            while(r != SYM_EXP_END);
            for(int j = m_exparr.GetSize(); i < j; ++i)
                m_exparr[i]->m_self = m_bin.GetSize();
        }
        else
        {
            m_err.Format("unknown or bad symbol2 '%s'", (LPCTSTR)str);
            return ERR_NORMAL;
        }
    }
}
Ejemplo n.º 25
0
int CPartFileConvert::performConvertToeMule(CString folder)
{
	BOOL bWorking;
	CString filepartindex,newfilename;
	CString buffer;
	UINT fileindex;
	CFileFind finder;
	
	CString partfile=folder;
	folder.Delete(folder.ReverseFind('\\'),folder.GetLength());
	partfile=partfile.Mid(partfile.ReverseFind('\\')+1,partfile.GetLength());


	UpdateGUI(0,GetResString(IDS_IMP_STEPREADPF),true);

	filepartindex=partfile.Left(partfile.Find('.'));
	//int pos=filepartindex.ReverseFind('\\');
	//if (pos>-1) filepartindex=filepartindex.Mid(pos+1,filepartindex.GetLength()-pos);

	UpdateGUI(4,GetResString(IDS_IMP_STEPBASICINF));

	CPartFile* file=new CPartFile();
	EPartFileFormat eFormat = PMT_UNKNOWN;
		
	if (file->LoadPartFile(folder, partfile, &eFormat) == PLR_CHECKSUCCESS)
	{
		pfconverting->partmettype = (uint8_t)eFormat;
		switch (pfconverting->partmettype)
		{
			case PMT_UNKNOWN:
			case PMT_BADFORMAT:
				delete file;
				return CONV_BADFORMAT;
				break;
		}
	}
	else
	{
		delete file;
		return CONV_BADFORMAT;
	}

	CString oldfile=folder+_T("\\")+partfile.Left(partfile.GetLength()- ((pfconverting->partmettype==PMT_SHAREAZA)?3:4) );

	pfconverting->size=file->GetFileSize();
	pfconverting->filename=file->GetFileName();
	pfconverting->filehash= EncodeBase16( file->GetFileHash() ,16);
	UpdateGUI(pfconverting);

	if (theApp.downloadqueue->GetFileByID(file->GetFileHash())!=0) {
		delete file;
		return CONV_ALREADYEXISTS;
	}
	
	if (pfconverting->partmettype==PMT_SPLITTED ) {
		try {
			CByteArray ba;
			ba.SetSize(PARTSIZE);

			CFile inputfile;
			int pos1,pos2;
			CString filename;

			// just count
			UINT maxindex=0;
			UINT partfilecount=0;
			bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part"));
			while (bWorking)
			{
				bWorking = finder.FindNextFile();
				++partfilecount;
				buffer=finder.GetFileName();
				pos1=buffer.Find('.');
				pos2=buffer.Find('.',pos1+1);
				fileindex=_tstoi(buffer.Mid(pos1+1,pos2-pos1) );
				if (fileindex==0) continue;
				if (fileindex>maxindex) maxindex=fileindex;
			}
			float stepperpart;
			if (partfilecount>0) {
				stepperpart=(80.0f / partfilecount );
				if ((uint64_t)maxindex*PARTSIZE<=pfconverting->size) pfconverting->spaceneeded=(uint64_t)maxindex*PARTSIZE;
					else pfconverting->spaceneeded=((uint64_t)(pfconverting->size / PARTSIZE) * PARTSIZE)+(pfconverting->size % PARTSIZE);
			} else {
				stepperpart=80.0f;
				pfconverting->spaceneeded=0;
			}
			
			UpdateGUI(pfconverting);

			if (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < ((uint64_t)maxindex*PARTSIZE) ) {
				delete file;
				return CONV_OUTOFDISKSPACE;
			}

			// create new partmetfile, and remember the new name
			file->CreatePartFile();
			newfilename=file->GetFullName();

			UpdateGUI(8,GetResString(IDS_IMP_STEPCRDESTFILE));
			file->m_hpartfile.SetLength( pfconverting->spaceneeded );

			uint16_t curindex=0;
			bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part"));
			while (bWorking)
			{
				bWorking = finder.FindNextFile();
				
				//stats
				++curindex;
				buffer.Format(GetResString(IDS_IMP_LOADDATA),curindex,partfilecount);
				UpdateGUI( 10+(curindex*stepperpart) ,buffer);

				filename=finder.GetFileName();
				pos1=filename.Find('.');
				pos2=filename.Find('.',pos1+1);
				fileindex=_tstoi(filename.Mid(pos1+1,pos2-pos1) );
				if (fileindex==0) continue;

				uint32_t chunkstart=(uint32_t)(fileindex-1) * PARTSIZE ;

				// open, read data of the part-part-file into buffer, close file
				inputfile.Open(finder.GetFilePath(),CFile::modeRead|CFile::shareDenyWrite);
				uint32_t readed=inputfile.Read( ba.GetData() ,PARTSIZE);
				inputfile.Close();

				buffer.Format(GetResString(IDS_IMP_SAVEDATA),curindex,partfilecount);
				UpdateGUI( 10+(curindex*stepperpart) ,buffer);

				// write the buffered data
				file->m_hpartfile.Seek(chunkstart, CFile::begin );
				file->m_hpartfile.Write(ba.GetData(),readed);
			}
		}
		catch(CFileException* error) {
			CString strError(GetResString(IDS_IMP_IOERROR));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if (error->GetErrorMessage(szError, _countof(szError))){
				strError += _T(" - ");
				strError += szError;
			}
			LogError(false, _T("%s"), strError);
			error->Delete();
			delete file;
			return CONV_IOERROR;
		}
		file->m_hpartfile.Close();
	}
	// import an external common format partdownload
	else //if (pfconverting->partmettype==PMT_DEFAULTOLD || pfconverting->partmettype==PMT_NEWOLD || Shareaza  ) 
	{
		
		if (!pfconverting->removeSource) 
			pfconverting->spaceneeded = (UINT)GetDiskFileSize(oldfile);

		UpdateGUI(pfconverting);

		if (!pfconverting->removeSource && (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < pfconverting->spaceneeded) ) {
			delete file;
			return CONV_OUTOFDISKSPACE;
		}

		file->CreatePartFile();
		newfilename=file->GetFullName();

		file->m_hpartfile.Close();

		BOOL ret=FALSE;
		UpdateGUI( 92 ,GetResString(IDS_COPY));
		DeleteFile(newfilename.Left(newfilename.GetLength()-4));

		if (!PathFileExists(oldfile)) {
			// data file does not exist. well, then create a 0 byte big one
			HANDLE hFile = CreateFile( newfilename.Left(newfilename.GetLength()-4) ,    // file to open
							GENERIC_WRITE,          // open for reading
							FILE_SHARE_READ,       // share for reading
							NULL,                  // default security
							CREATE_NEW,         // existing file only
							FILE_ATTRIBUTE_NORMAL, // normal file
							NULL);                 // no attr. template
			 
			ret= !(hFile == INVALID_HANDLE_VALUE) ;

			CloseHandle(hFile);
		}
			else 
		if (pfconverting->removeSource) 
			ret=MoveFile( oldfile, newfilename.Left(newfilename.GetLength()-4) );
		else 
			ret=CopyFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ,false);

		if (!ret) {
			file->DeleteFile();
			//delete file;
			return CONV_FAILED;
		}

	}


	UpdateGUI( 94 ,GetResString(IDS_IMP_GETPFINFO));

	DeleteFile(newfilename);
	if (pfconverting->removeSource)
		MoveFile(folder+_T("\\")+partfile,newfilename);
	else CopyFile(folder+_T("\\")+partfile,newfilename,false);


	file->m_hasharray.release();
	for ( GapList::iterator it = file->gaplist.begin(); it != file->gaplist.end(); ++it ) {
		delete *it;
	}
	file->gaplist.clear();

	if (file->LoadPartFile(thePrefs.GetTempDir(), file->GetPartMetFileName()) != PLR_LOADSUCCESS) {
		//delete file;
		file->DeleteFile();
		return CONV_BADFORMAT;
	}

	if (pfconverting->partmettype==PMT_NEWOLD || pfconverting->partmettype==PMT_SPLITTED ) {
		file->completedsize = file->m_uTransferred;
		file->m_uCompressionGain = 0;
		file->m_uCorruptionLoss = 0;
	}

	UpdateGUI( 100 ,GetResString(IDS_IMP_ADDDWL));

	theApp.downloadqueue->AddDownload(file,thePrefs.AddNewFilesPaused());
	file->SavePartFile();
	
	if (file->GetStatus(true) == PS_READY)
		theApp.sharedfiles->SafeAddKFile(file); // part files are always shared files


	if (pfconverting->removeSource) {

		bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*"));
		while (bWorking)
		{
			bWorking = finder.FindNextFile();
			VERIFY( _tunlink(finder.GetFilePath()) == 0 );
		}

		if (pfconverting->partmettype==PMT_SPLITTED)
			RemoveDirectory(folder+_T("\\"));
	}

	return CONV_OK;
}
/**
 * Modifies a user param byte array with the ExtParam data passed with
 * argument pParam. ExtParam data objects will be build from 
 * Ext_User_Prm_Data_Const/Ref fields within the GSD. Extparam data 
 * describes the datatype of the Ext_User_Prm_Data, the offset within
 * the user param byte array and the value. The passed user param byte
 * array (see argument UserParam) grows as necessary.
 * Existing user param bytes within the array will be or-ed with the
 * new byte value.
 *
 * @param			CByteArray & UserParam - user param byte array to
 *                  modify. The byte array will grow as necessary.
 * @param			ExtParam *pParam - Reference to ExtParam data 
 *                  object describing the Ext_User_Prm_Data. Shall not
 *                  be NULL.
 * @exception		CMemoryException
 * @see			    GSD: Ext_User_Prm_Data_Const/Ref
*/
void ModifyParamArray(CByteArray & UserParam, ExtParam *pParam)
{
	int offset = 0;
    int sizeArray = 0;
    int sizeBytes = 0;


    ASSERT(pParam);

    switch(pParam->GetParamType()) {
    case Array:
        {
		    CByteArray* pBytes = pParam->GetByteArray();

		    sizeBytes = pBytes->GetSize();
            sizeArray = UserParam.GetSize();
		    offset = pParam->GetByteOffset();

            if(offset + sizeBytes > sizeArray) {
                //grow the array
                UserParam.SetSize(offset + sizeBytes);
                BYTE *pb = UserParam.GetData();
                //preset array
                size_t sizeSet = offset + sizeBytes - sizeArray;
                memset(&pb[sizeArray],0,sizeSet);
            }

		    for (int x = 0; x < sizeBytes; x++) {
			    BYTE userbyte = UserParam.GetAt(offset);
			    BYTE setbyte  = pBytes->GetAt(x);
			    userbyte |= setbyte;
			    UserParam.SetAt(offset++, userbyte);
		    }// next x
	    }
        break;
    case Byte:
	    {
		    offset = pParam->GetByteOffset();
            sizeArray = UserParam.GetSize();
            sizeBytes = sizeof(BYTE);

            if(offset + sizeBytes > sizeArray) {
                //grow the array
                UserParam.SetSize(offset + sizeBytes);
                BYTE *pb = UserParam.GetData();
                //preset array
                size_t sizeSet = offset + sizeBytes - sizeArray;
                memset(&pb[sizeArray],0,sizeSet);
            }

			BYTE userbyte = UserParam.GetAt(offset);	// Get current value in Bytearray
			if (pParam->IsBitArea())	{
				userbyte &= ~MakeBitFieldInByte(pParam->GetBitAreaStart(),
											   pParam->GetBitAreaLength());
				userbyte |= (BYTE)(pParam->GetUsedValue() << pParam->GetBitAreaStart());
			}
			else	{
				userbyte = (BYTE)pParam->GetUsedValue();
			}
			UserParam.SetAt(offset, userbyte);		// Set new value in ByteArray

	    }
        break;
    case Word:
	    {
            BYTE setbyte = 0;
		    WORD data = (WORD)pParam->GetUsedValue();

		    offset = pParam->GetByteOffset();
            sizeArray = UserParam.GetSize();
            sizeBytes = sizeof(data);
            
            if(offset + sizeBytes > sizeArray) {
                //grow the array
                UserParam.SetSize(offset + sizeBytes);
                BYTE *pb = UserParam.GetData();
                //preset array
                size_t sizeSet = offset + sizeBytes - sizeArray;
                memset(&pb[sizeArray],0,sizeSet);
            }
            
            for (int i = sizeBytes - 1; i >= 0 ; i--)	{
			    BYTE userbyte = UserParam.GetAt(offset);
			    setbyte = (BYTE)((data  >> (i*8)) & 0x000000FF);
			    userbyte = setbyte;
			    UserParam.SetAt(offset++, userbyte);
		    }
	    }
        break;
    case DWord:
	    {
		    BYTE setbyte = 0;
		    DWORD data = (DWORD)pParam->GetUsedValue();

		    offset = pParam->GetByteOffset();
            sizeArray = UserParam.GetSize();
            sizeBytes = sizeof(data);
            
            if(offset + sizeBytes > sizeArray) {
                //grow the array
                UserParam.SetSize(offset + sizeBytes);
                BYTE *pb = UserParam.GetData();
                //preset array
                size_t sizeSet = offset + sizeBytes - sizeArray;
                memset(&pb[sizeArray],0,sizeSet);
            }

		    for (int i = sizeBytes - 1; i >= 0 ; i--)	{
			    BYTE userbyte = UserParam.GetAt(offset);
			    setbyte = (BYTE)((data  >> (i*8)) & 0x000000FF);
			    userbyte = setbyte;
			    UserParam.SetAt(offset++, userbyte);
		    }
	    }
        break;
    default:
        break;
    }
}
/*static*/
HRESULT CSheetConfigGSD::GetExtUserParams(IExtUserParam* pParam, ExtParam* pExtParam)
{
	if (pParam == NULL || pExtParam == NULL)
		return E_POINTER;

	BSTR    sName;
	USES_CONVERSION;
    HRESULT hr = pParam->get_Description(&sName);
    if (SUCCEEDED(hr)) {
		pExtParam->SetDescription(sName);
		::SysFreeString(sName);
    }
	else	{
		delete pExtParam;
		return hr;
	}

    long lTmp = 0;
    long lOffset = 0;
    hr = pParam->get_Offset(&lOffset);
    if (SUCCEEDED(hr)) {
		pExtParam->SetByteOffset(lOffset);
    }
	else	{
		delete pExtParam;
		return hr;
	}
    BOOL bConst = FALSE;
    BOOL bVarEnum = FALSE;
    BOOL bVarRange = FALSE;
    BOOL bBitArea = FALSE;
    hr = pParam->get_IsConstantParam(&bConst);
    if (SUCCEEDED(hr)) {
		pExtParam->SetIfConstant(bConst);
	}
	else	{
		delete pExtParam;
		return hr;
	}

    if (bConst)
    {
        CComVariant vtBytes;
        hr = pParam->get_ConstPrmBytes(&vtBytes);
        if (SUCCEEDED(hr)) {
			HRESULT     hr;
			// is it what we expected in VARIANT?
            ASSERT(vtBytes.vt == (VT_UI1 | VT_ARRAY));
			if (vtBytes.vt == (VT_UI1 | VT_ARRAY))
			{
				// now show values
				SAFEARRAY   *psaBytes = vtBytes.parray;

				long    lBound = 0, uBound = 0;
				hr = ::SafeArrayGetLBound(psaBytes, 1, &lBound);
				_ASSERTE(SUCCEEDED(hr));
				hr = ::SafeArrayGetUBound(psaBytes, 1, &uBound);
				_ASSERTE(SUCCEEDED(hr));
				// loop thru all objects in this level:
				CByteArray octets;
				octets.RemoveAll();
				for (long i = lBound; i <= uBound; i++)
				{
					BYTE    ucVal;
					hr = ::SafeArrayGetElement(psaBytes, &i, &ucVal);
					_ASSERTE(SUCCEEDED(hr));
					if (FAILED(hr)) {
						continue;
					}
					octets.Add(ucVal);
				}// next byte
				pExtParam->SetConstantBytes(octets.GetData(), octets.GetSize());
			}
		}
        pExtParam->SetParamType(Array);
        return S_OK;
    }

    hr = pParam->get_DefaultValue(&lTmp);
    if (SUCCEEDED(hr)) {
		pExtParam->SetDefaultValue(lTmp);
    }
    hr = pParam->get_IsVariableEnumParam(&bVarEnum);
    if (SUCCEEDED(hr)) {
		//pExtParam->SetIfVariableEnum(bVarEnum);
    }
	else	{
		delete pExtParam;
		return hr;
	}
    hr = pParam->get_IsVariableMinMaxParam(&bVarRange);
    if (SUCCEEDED(hr)) {
        hr = pParam->get_MinValue(&lTmp);
        if (SUCCEEDED(hr)) {
			pExtParam->SetLowerValue(lTmp);
        }
        hr = pParam->get_MaxValue(&lTmp);
        if (SUCCEEDED(hr)) {
			pExtParam->SetUpperValue(lTmp);
        }
    }
	else	{
		delete pExtParam;
		return hr;
	}
    hr = pParam->get_IsBitArea(&bBitArea);
    if (SUCCEEDED(hr)) {
		pExtParam->SetIfBitArea(bBitArea);
        // show bit area params
        hr = pParam->get_BitAreaStart(&lTmp);
        if (SUCCEEDED(hr)) {
			pExtParam->SetBitAreaStart(lTmp);
		}
        hr = pParam->get_BitAreaLength(&lTmp);
        if (SUCCEEDED(hr)) {
			pExtParam->SetBitAreaLength(lTmp);
        }
    }
	else	{
		delete pExtParam;
		return hr;
	}

	CComVariant vtValues, vtNames;
	hr = pParam->NamedEnumValues(&vtValues, &vtNames);
	if (SUCCEEDED(hr)) {
		HRESULT hr;
		// is it what we expected in VARIANT?
        ASSERT(vtValues.vt == (VT_I4 | VT_ARRAY));
        ASSERT(vtNames.vt == (VT_BSTR | VT_ARRAY));
		if (   (vtValues.vt == (VT_I4 | VT_ARRAY))
			&& (vtNames.vt == (VT_BSTR | VT_ARRAY))  )
		{
			// now show values and texts
			SAFEARRAY   *psaValues = vtValues.parray;
			SAFEARRAY   *psaNames = vtNames.parray;

			long    lBound = 0, uBound = 0;
			hr = ::SafeArrayGetLBound(psaValues, 1, &lBound);
			_ASSERTE(SUCCEEDED(hr));
			hr = ::SafeArrayGetUBound(psaValues, 1, &uBound);
			_ASSERTE(SUCCEEDED(hr));
			// loop thru all objects in this level:
			for (long i = lBound; i <= uBound; i++)
			{
				LONG    lVal;
				BSTR    sName;
				hr = ::SafeArrayGetElement(psaValues, &i, &lVal);
				_ASSERTE(SUCCEEDED(hr));
				hr = ::SafeArrayGetElement(psaNames, &i, &sName);
				_ASSERTE(SUCCEEDED(hr));
				if (FAILED(hr)) {
					continue;
				}
				NamedEnumValues* pElement = new NamedEnumValues;
				pElement->Value = lVal;
				pElement->szName = sName;
				pExtParam->AddNamedEnumVal(pElement);
                SysFreeString(sName);
			}// next
		}
	}// end if (SUCCEEDED(hr))

    if (bVarEnum && !pExtParam->IsVariableEnumParam())
    {
        CComVariant vtEnums;
        hr = pParam->EnumValues(&vtEnums);
        if (SUCCEEDED(hr)) {
            ASSERT(vtEnums.vt == (VT_I4 | VT_ARRAY));
			if (vtEnums.vt == (VT_I4 | VT_ARRAY))	{
				// now show values and texts
				SAFEARRAY   *psaValues = vtEnums.parray;

				long    lBound = 0, uBound = 0;
				hr = ::SafeArrayGetLBound(psaValues, 1, &lBound);
				_ASSERTE(SUCCEEDED(hr));
				hr = ::SafeArrayGetUBound(psaValues, 1, &uBound);
				_ASSERTE(SUCCEEDED(hr));
				// loop thru all objects in this level:
				for (long i = lBound; i <= uBound; i++)
				{
					LONG    lVal;
					CString szName;
					hr = ::SafeArrayGetElement(psaValues, &i, &lVal);
					_ASSERTE(SUCCEEDED(hr));
					if (FAILED(hr)) {
						continue;
					}
					szName.Format(_T("%d"), lVal);

					NamedEnumValues* pElement = new NamedEnumValues;
					pElement->Value = lVal;
					pElement->szName = szName;
					pExtParam->AddNamedEnumVal(pElement);
				} //next i
			}// end if
        }// end if
    }// end if

    SetExtParamType(pParam,pExtParam);
    return S_OK;
}
Ejemplo n.º 28
0
BOOL ConvertStringToSendData(const CString & s, CByteArray & msg)
    {
#ifdef _UNICODE
     int n = ::WideCharToMultiByte(CP_UTF8, 0, s, -1, NULL, 0, NULL, NULL);
     if(n == 0)
        { /* failed */
         //DWORD err = ::GetLastError();
         msg.SetSize(0);
         return FALSE;
        } /* failed */
     else
        { /* success */
         msg.SetSize(n);
         n = ::WideCharToMultiByte(CP_UTF8, 0, s, -1, (LPSTR)msg.GetData(), n, NULL, NULL);
         if(n == 0)
            { /* conversion failed */
             DWORD err = ::GetLastError();
             msg.SetSize(0);
             return FALSE;
            } /* conversion failed */
         else
            { /* use multibyte string */
             msg.SetSize(n - 1);
             return TRUE;
            } /* use multibyte string */
        } /* success */
#else // ANSI
     CArray<WCHAR, WCHAR> wc;

     int n = ::MultiByteToWideChar(CP_ACP, 0, s, -1, NULL, 0);
     if(n == 0)
        { /* failed */
         DWORD err = ::GetLastError();
         msg.SetSize(0);
         return FALSE;
        } /* failed */
     else
        { /* success */
         wc.SetSize(n);
         n = ::MultiByteToWideChar(CP_ACP, 0, s, -1, wc.GetData(), n);
        } /* success */     

     n = ::WideCharToMultiByte(CP_UTF8, 0, wc.GetData(), -1, NULL, 0, NULL, NULL);
     if(n == 0)
        { /* failed */
         DWORD err = ::GetLastError();
         msg.SetSize(0);
         return FALSE;
        } /* failed */
     else
        { /* success */
         msg.SetSize(n);
         n = ::WideCharToMultiByte(CP_UTF8, 0, wc.GetData(), -1, (LPSTR)msg.GetData(), n, NULL, NULL);
         if(n == 0)
            { /* conversion failed */
             DWORD err = ::GetLastError();
             msg.SetSize(0);
             return FALSE;
            } /* conversion failed */
         else
            { /* use multibyte string */
             msg.SetSize(n - 1);
             return TRUE;
            } /* use multibyte string */
        } /* success */
#endif
    } // ConvertStringToSendData
Ejemplo n.º 29
0
BOOL CTobCompiler::CompileFile(LPWSTR fsrcname, LPWSTR fdstname, F_ErrorHandler ErrorHandler)
{
    WChar szOutput[MAX_PATH];
    CString err;
    BOOL haserr = FALSE;

    Reset();

    m_line = 1;

    m_fsrc = _wfopen(fsrcname, L"rb");
    if (!m_fsrc)
    {
        m_err.Format("can't open src file '%S'", fsrcname);
        (this->*ErrorHandler)(GetErrorString(err));
        return FALSE;
    }

    for(;;)
    {
        EToken r = CompilePass1();
        if (r == ERR_EOF)
            break;

        if (r < 0)
        {
            haserr = TRUE;
            if (!(this->*ErrorHandler)(GetErrorString(err)))
                return FALSE;
        }

        if (r == ERR_SEVERE)
            return FALSE;
    }

    fclose(m_fsrc);
    m_fsrc = 0;

    if (!CompilePass2(ErrorHandler) || haserr)
        return FALSE;

    if (fdstname == NULL)
    {
        CByteArray* bin;
        if (m_binmap.Lookup("_FILE", bin) && bin->GetSize() > 0)
        {
            MultiByteToWideChar(
                CP_GB2312,
                0,
                (LPSTR)bin->GetData(),
                bin->GetSize(),
                szOutput,
                countof(szOutput));
            fdstname = szOutput;
        }
        else
        {
            LPWSTR pszExtension;

            lstrcpyW(szOutput, fsrcname);
            pszExtension = findextw(szOutput);
            !lstrcmpiW(pszExtension, L".bin") ? lstrcatW(pszExtension, L".bin") : lstrcpyW(pszExtension, L".bin");
            fdstname = szOutput;
        }
    }

    m_fdst = _wfopen(fdstname, L"wb");
    if (m_fdst == NULL)
    {
        m_err.Format("can't create dst file '%S'", fdstname);
        (this->*ErrorHandler)(GetErrorString(err));
        return FALSE;
    }

    if (m_bin.GetSize() > 0 && fwrite(m_bin.GetData(), m_bin.GetSize(), 1, m_fdst) != 1)
    {
        fclose(m_fdst); m_fdst = 0;
        m_err.Format("can't write dst file '%S'", fdstname);
        (this->*ErrorHandler)(GetErrorString(err));
        return FALSE;
    }

    fclose(m_fdst);
    m_fdst = NULL;

    return TRUE;
}
Ejemplo n.º 30
0
CTobCompiler::EToken CTobCompiler::GetString(CByteArray& bin)
{
    CByteArray temp;
    int c, d, e;
    for(;;)
    {
        if ((c = fgetc(m_fsrc)) < 0) break;
        if (c == '\n') ++m_line;
        else if (ms_tokentable[c] == 3)
        {
            m_err.Format("found invalid char 0x%02X in src file at %p", c, ftell(m_fsrc)-1);
            return ERR_NORMAL;
        }
        else if (c < ' ') continue;
        else if (c == '\'' || c == '"')
        {
            if ((d = fgetc(m_fsrc)) > 0)
            {
                if (d == ':')
                {
                    if ((d = fgetc(m_fsrc)) < 0) break;
                    e = GetSizeFromType(d);
                    if (e == -1)
                    {
                        m_err.Format("unknown type '%c' after ':'", d);
                        return ERR_NORMAL;
                    }

                    d = temp.GetSize();
                    for(int i = 0; i < e; ++i)
                        bin.Add(((BYTE*)&d)[i]);
                }
                else if (fseek(m_fsrc, -1, SEEK_CUR))
                {
                    m_err.Format("can not seek src file at %p", ftell(m_fsrc));
                    return ERR_SEVERE;
                }
            }
            bin.Append(temp);
            if (c == '"')
                bin.Add(0);

            if (m_Option.bIgnoreCase)
                strlwr((LPSTR)bin.GetData());
            return SYM_STR;
        }
        else if (c == '\\')
        {
            if ((c = fgetc(m_fsrc)) < 0) break;
            switch(CHAR_UPPER(c))
            {
                case 'N': c = '\n';   break;
                case 'R': c = '\r';   break;
                case 'T': c = '\t';   break;
                case '0': c = '\0';   break;
                case '1': c = '\x01'; break;
                case '2': c = '\x02'; break;
                case '3': c = '\x03'; break;
                case '4': c = '\x04'; break;
                case '5': c = '\x05'; break;
                case '6': c = '\x06'; break;
                case '7': c = '\x07'; break;
                case '8': c = '\x08'; break;
                case '9': c = '\x09'; break;
                case 'A': c = '\x0a'; break;
                case 'B': c = '\x0b'; break;
                case 'C': c = '\x0c'; break;
                case 'D': c = '\x0d'; break;
                case 'E': c = '\x0e'; break;
                case 'F': c = '\x0f'; break;
                case 'X':
                {
                    if ((c = fgetc(m_fsrc)) < 0) goto end_;
                    BYTE b0 = ms_hextable[c];
                    if (b0 == 16)
                    {
                        m_err.Format("bad hex char 0x%02X after '\\x'", b0);
                        return ERR_NORMAL;
                    }
                    if ((c = fgetc(m_fsrc)) < 0) goto end_;
                    BYTE b1 = ms_hextable[c];
                    if (b1 == 16)
                    {
                        m_err.Format("bad hex char 0x%02X after '\\x'", b1);
                        return ERR_NORMAL;
                    }
                    temp.Add((BYTE)((b0<<4) + b1));
                }
            }
        }
        if (c >= 0x81)
        {
            if ((d = fgetc(m_fsrc)) < 0) break;
            if (d < 0x40)
            {
                if (fseek(m_fsrc, -1, SEEK_CUR))
                {
                    m_err.Format("can not seek src file at %p", ftell(m_fsrc));
                    return ERR_SEVERE;
                }
                m_err.Format("found half wide char at %p", ftell(m_fsrc)-1);
                return ERR_NORMAL;
            }
            temp.Add((BYTE)c);
            temp.Add((BYTE)d);
        }
        else
        {
            temp.Add((BYTE)c);
        }
    }
end_:
    if (!feof(m_fsrc))
        m_err.Format("can not read src file at %p", ftell(m_fsrc));
    else
        m_err = "bad string at the end of src file";
    return ERR_SEVERE;
}