Ejemplo n.º 1
0
DWORD	dogetlong(CFile f)
{
	DWORD	x;
	f.Read(&x, sizeof(x));
	return x;
}
Ejemplo n.º 2
0
void CBuildMap::OnButtonBuild() 
{
	CreateDirectory(m_pDoc->m_RunPath + "Graphing\\", NULL);
	CFile MapFile;
	
	if(!MapFile.Open(m_pDoc->m_RunPath + "Graphing\\graph.txt", CFile::modeCreate | CFile::modeWrite))
		return;

	CString strHops, strHeight, strWidth;

	// Get hops pref
	m_ebHops.GetWindowText(strHops);
	int MaxHops = 3;
	if(strHops != "")
		MaxHops = atoi(strHops);

	// Get height pref
	m_ebHeight.GetWindowText(strHeight);
	int MapHeight = 3;
	if(strHeight != "")
		MapHeight = atoi(strHeight);

	// Get width pref
	m_ebWidth.GetWindowText(strWidth);
	int MapWidth = 3;
	if(strWidth != "")
		MapWidth = atoi(strWidth);

	// Graph header, default settings here
	CString Header = "graph GnutellaNet \r\n";
			Header += "{ \r\n";
			Header += "\t size=\"" + DWrdtoStr(MapHeight) + "," + DWrdtoStr(MapWidth) + "\" \r\n";
			Header += "\t graph[center=\"" + InsertDecimal((double)MapHeight / 2) + "," + InsertDecimal((double)MapWidth / 2) + "\"] \r\n";
			Header += "\t node [shape=circle,width=.2,height=.2,label=\"\"] \r\n";
	

	// Put ourselves at the center of the graph
	/*CString DotSize = GetDotSize(m_pDoc->m_pShare->m_TotalLocalFiles);
	CString Size    = "width=."    + DotSize;
		    Size   += ", height=." + DotSize;

	Header += "\r\n\t 0 [label=\"You\", fontsize=10, style=filled, color=red, " + Size + "] \r\n\r\n";
	MapFile.Write(Header, Header.GetLength());*/

	m_DetailList.clear();

	//// Map all the branches of nodes from us
	//for(int i = 0; i < m_pComm->m_NodeList.size(); i++)	
	//{
	//	CGnuNode* p = m_pComm->m_NodeList[i];

	//	if(m_pComm->m_NodeList[i]->m_Status != SOCK_CONNECTED)
	//		continue;

	//	// Maps the node directly connected
	//	for(int j = 0; j < p->LocalMap[0].size(); j++)
	//	{
	//		CString NextNode = "\t " + DWrdtoStr(0) + " -- ";
	//				NextNode += DWrdtoStr(p->LocalMap[0][j]) + " [" + GetMapColor(1) + "]\r\n";

	//		MapFile.Write(NextNode, NextNode.GetLength());
	//	}

	//	// Maps node connections
	//	for(j = 0; j < p->MapLinkList.size(); j++)
	//	{
	//		bool Insert = false;

	//		if(p->MapLinkList[j].Hops <= MaxHops)
	//			Insert = true;

	//		if(Insert)
	//		{
	//			AddDetail(p->MapLinkList[j].ParentID);
	//			AddDetail(p->MapLinkList[j].ID);

	//			CString NodeLink = "\t " + DWrdtoStr( p->MapLinkList[j].ParentID );
	//					NodeLink += " -- ";
	//					NodeLink += DWrdtoStr(p->MapLinkList[j].ID) + " [" + GetMapColor(p->MapLinkList[j].Hops) + "]\r\n";
	//			
	//			MapFile.Write(NodeLink, NodeLink.GetLength());
	//		}
	//	}

	//	MapFile.Write("\r\n\r\n", 4);
	//}

	// Write each node's details
	//m_DetailList.sort();
	//
	//std::list<DWORD>::iterator itNode;
	//for(itNode = m_DetailList.begin(); itNode != m_DetailList.end(); itNode++)
	//	for(i = 0; i < m_pComm->MapTable.size(); i++)
	//		if(*itNode == m_pComm->MapTable[i].MapID)
	//		{
	//			// Get size of node
	//			CString Size;
	//			if(m_chkSizeNodes.GetCheck())
	//			{
	//				DotSize = GetDotSize(m_pComm->MapTable[i].FileSize);
	//				Size  =  ",width=."  + DotSize;
	//				Size +=  ",height=." + DotSize;
	//			}

	//			// Get shape of node
	//			CString Shape = "circle";
	//			if(m_chkShapeNodes.GetCheck())
	//			{
	//				if(strcmp(m_pComm->MapTable[i].Client, "BEAR") == 0) 
	//					Shape = "box";
	//				
	//				else if(strcmp(m_pComm->MapTable[i].Client, "LIME") == 0|| strcmp(m_pComm->MapTable[i].Client, "SNUT") == 0) 
	//					Shape = "diamond";

	//				else if(strcmp(m_pComm->MapTable[i].Client, "GNUC") == 0) 
	//					Shape = "triangle";

	//				else
	//					Shape = "circle";
	//			}

	//			// Write node's details
	//			CString Details = "\t " + DWrdtoStr(m_pComm->MapTable[i].MapID) + " [shape=" + Shape + Size + "]\r\n";
	//			MapFile.Write(Details, Details.GetLength());
	//		}

	MapFile.Write("\r\n\r\n", 4);
	
	Header = "\r\n} \r\n";
	MapFile.Write((LPCTSTR) Header, Header.GetLength());
	
	MapFile.Close();

	DeleteFile(m_pDoc->m_RunPath + "Graphing\\graph.gif");

	if( (int) ShellExecute(NULL, "open", "neato.exe", "-Tgif graph.txt -o graph.gif", m_pDoc->m_RunPath + "Graphing\\", SW_HIDE) > 32)
	{
		m_Building     = true;
		m_TimeBuilding = 0;

		m_btnRefresh.EnableWindow(false);
		m_btnBuild.EnableWindow(false);

		m_btnBuild.SetWindowText("Building");
	}
	else
		AfxMessageBox("Error Launching Graphing Software");
}
Ejemplo n.º 3
0
void ReadEffectClip (tEffectClip& ec, CFile& cf)
{
ReadVideoClip (ec.vClipInfo, cf);
ec.xTimeLeft = cf.ReadFix ();
ec.nCurFrame = cf.ReadInt ();
ec.changingWallTexture = cf.ReadShort ();
ec.changingObjectTexture = cf.ReadShort ();
ec.flags = cf.ReadInt ();
ec.nCritClip = cf.ReadInt ();
ec.nDestBm = cf.ReadInt ();
ec.nDestVClip = cf.ReadInt ();
ec.nDestEClip = cf.ReadInt ();
ec.xDestSize = cf.ReadFix ();
ec.nSound = cf.ReadInt ();
ec.nSegment = cf.ReadInt ();
ec.nSide = cf.ReadInt ();
}
Ejemplo n.º 4
0
static inline void ReadTimeStamp(CFile& file, CTime& timeStamp)
{
	unsigned __int64 time;
	file.Read(&time, sizeof(unsigned __int64));
	timeStamp = (time_t)time;
}
Ejemplo n.º 5
0
//上传头像
bool CDataBaseSink::OnRequestUploadFace(WORD wRequestID, DWORD dwContextID, VOID * pData, WORD wDataSize)
{
	//数据验证
	ASSERT(wDataSize==sizeof(DBR_GP_UploadCustomFace));
	if (wDataSize!=sizeof(DBR_GP_UploadCustomFace)) return false;

	//数据转换
	DBR_GP_UploadCustomFace *pUploadCustomFace = (DBR_GP_UploadCustomFace*)pData;

	//文件定义
	CFile fileCustomFace;
	TCHAR szFileName[128];
	_snprintf_s(szFileName, CountArray(szFileName), TEXT("%s\\UploadFile_%ld.zip"), theApp.m_szDirWork, pUploadCustomFace->dwUserID);

	try
	{
		if ( fileCustomFace.Open( szFileName, CFile::modeRead|CFile::typeBinary) )
		{
			BYTE cbCustomFaceData[1024*30];

			//读取文件
			UINT uReadSize = fileCustomFace.Read(cbCustomFaceData, CountArray(cbCustomFaceData));

			//关闭文件
			fileCustomFace.Close();

			LONG lRet=-1;
			try
			{
				lRet = SPUploadFace(pUploadCustomFace->dwUserID, cbCustomFaceData, uReadSize);
			}
			catch (IDataBaseException * pIException)
			{
				//错误信息
				LPCTSTR pszDescribe=pIException->GetExceptionDescribe();
				CTraceService::TraceString(pszDescribe,TraceLevel_Exception);
			}

			//成功判断
			if ( lRet != -1 )
			{
				DBR_GP_UploadFaceResult UploadFaceResult;
				ZeroMemory(&UploadFaceResult, sizeof(UploadFaceResult));
				lstrcpyn(UploadFaceResult.szDescribeMsg, TEXT("头像上传成功!"), sizeof(UploadFaceResult.szDescribeMsg));
				UploadFaceResult.dwFaceVer=lRet;
				UploadFaceResult.bOperateSuccess=true;

				m_pIDataBaseEngineEvent->OnEventDataBaseResult(DBR_GP_UPLOAD_FACE_RESULT,dwContextID,
					&UploadFaceResult,sizeof(UploadFaceResult));
			}
			else
			{
				//操作失败
				DBR_GP_UploadFaceResult UploadFaceResult;
				ZeroMemory(&UploadFaceResult, sizeof(UploadFaceResult));
				lstrcpyn(UploadFaceResult.szDescribeMsg, TEXT("由于数据库操作异常,请重新上传!"), sizeof(UploadFaceResult.szDescribeMsg));
				UploadFaceResult.bOperateSuccess=false;

				m_pIDataBaseEngineEvent->OnEventDataBaseResult(DBR_GP_UPLOAD_FACE_RESULT,dwContextID,
					&UploadFaceResult,sizeof(UploadFaceResult));
			}

			//删除文件
			CFile::Remove(szFileName);
		}
	}catch(...){}	

	return true;
}
Ejemplo n.º 6
0
void CRssReader::Process()
{
  while (GetQueueSize())
  {
    CSingleLock lock(m_critical);

    int iFeed = m_vecQueue.front();
    m_vecQueue.erase(m_vecQueue.begin());

    m_strFeed[iFeed].clear();
    m_strColors[iFeed].clear();

    CCurlFile http;
    http.SetUserAgent(g_advancedSettings.m_userAgent);
    http.SetTimeout(2);
    std::string strXML;
    std::string strUrl = m_vecUrls[iFeed];
    lock.Leave();

    int nRetries = 3;
    CURL url(strUrl);
    std::string fileCharset;

    // we wait for the network to come up
    if ((url.IsProtocol("http") || url.IsProtocol("https")) &&
        !CServiceBroker::GetNetwork().IsAvailable())
    {
      CLog::Log(LOGWARNING, "RSS: No network connection");
      strXML = "<rss><item><title>"+g_localizeStrings.Get(15301)+"</title></item></rss>";
    }
    else
    {
      XbmcThreads::EndTime timeout(15000);
      while (!m_bStop && nRetries > 0)
      {
        if (timeout.IsTimePast())
        {
          CLog::Log(LOGERROR, "Timeout while retrieving rss feed: %s", strUrl.c_str());
          break;
        }
        nRetries--;

        if (!url.IsProtocol("http") && !url.IsProtocol("https"))
        {
          CFile file;
          auto_buffer buffer;
          if (file.LoadFile(strUrl, buffer) > 0)
          {
            strXML.assign(buffer.get(), buffer.length());
            break;
          }
        }
        else
        {
          if (http.Get(strUrl, strXML))
          {
            fileCharset = http.GetProperty(XFILE::FILE_PROPERTY_CONTENT_CHARSET);
            CLog::Log(LOGDEBUG, "Got rss feed: %s", strUrl.c_str());
            break;
          }
          else if (nRetries > 0)
            Sleep(5000); // Network problems? Retry, but not immediately.
          else
            CLog::Log(LOGERROR, "Unable to obtain rss feed: %s", strUrl.c_str());
        }
      }
      http.Cancel();
    }
    if (!strXML.empty() && m_pObserver)
    {
      // erase any <content:encoded> tags (also unsupported by tinyxml)
      size_t iStart = strXML.find("<content:encoded>");
      size_t iEnd = 0;
      while (iStart != std::string::npos)
      {
        // get <content:encoded> end position
        iEnd = strXML.find("</content:encoded>", iStart) + 18;

        // erase the section
        strXML = strXML.erase(iStart, iEnd - iStart);

        iStart = strXML.find("<content:encoded>");
      }

      if (Parse(strXML, iFeed, fileCharset))
        CLog::Log(LOGDEBUG, "Parsed rss feed: %s", strUrl.c_str());
    }
  }
  UpdateObserver();
}
Ejemplo n.º 7
0
BOOL CReadBitmap::CTRead()
   {
   LPCTHEADER  lpTH;
   LPFRAME     lpFrame;
   BOOL        fConvert = FALSE, fRet = FALSE;
   CFile 	   theFile;
   CFile*	   pTheFile;
   FRMTYPEINFO inType, outType;
   LPTR        lpIn, lpIn2,lpOut, lpFrmLine;
   int         x,y,j;
   UINT        bytes_read;
   BOOL        GrayScale;
   BITMAP_ERROR_CODE err;
    CFrameTypeConvert	Convert;

	ProgressBegin(1);
	if ((pTheFile = OpenFile()) == NULL)
	{
		ProgressEnd();
		return(FALSE);
	}

   lpFrame = NULL;
   if ( !(lpTH = ReadCTHeader(pTheFile, m_lpFileName, &err)))
   {
   		SetError(err);
	   goto Exit;
	}

   GrayScale = lpTH->ColSepMask == 8 && lpTH->NumColSep == 1;
	if (GrayScale)
		FrameSetTypeInfo(&inType, FDT_GRAYSCALE, NULL);
    else 
		FrameSetTypeInfo(&inType, FDT_CMYKCOLOR, NULL);

	if (!SetupTypes(&inType, &outType))
		goto Exit;

	fConvert = !FrameTypeInfoEqual( inType, outType );

	if( fConvert )
		{
		if( !Convert.Init( inType, outType, lpTH->Pixels ) )
			{
			SetError(BEC_errMemory);
			goto Exit;
			}
		}
   /* Create the image frame store */
   if ( !(lpFrame = FrameOpen(outType, lpTH->Pixels, lpTH->Lines, lpTH->Resolution)))
	   {
	   SetError(BEC_errFrameOpen);
      goto Exit;
      }

  	pTheFile->Seek (2048, CFile::begin);
	for (y=0; y < lpTH->Lines; y++)
		{
		if ( Progress(y, lpTH->Lines, YES))
			goto Exit;

      TRY
	      {
		   bytes_read = pTheFile->Read(lpTH->lpCTLine, lpTH->LineSize);
         }
      CATCH_ALL(e)
	      {
			goto BadRead;
	      }
      END_CATCH_ALL
		if (bytes_read != lpTH->LineSize)
			goto BadRead;

		if ( !(lpFrmLine = FramePointerRaw( lpFrame, 0, y, YES)))
			goto BadWrite;
		lpIn  = lpTH->lpCTLine;
      lpOut = lpFrmLine;

      lpIn2 = lpIn;
      for (x=0; x < lpTH->Pixels; x++)
			{
         j = 0;
         if (!GrayScale)
            {
            if (lpTH->ColSepMask & 0x1)  // cyan
               {
               j  += lpTH->ChannelSize;
               *lpOut++ = 255 - *lpIn2;
               }
            else
               *lpOut++ = 0;
            if (lpTH->ColSepMask & 0x2)  // magenta
               {
               *lpOut++ = 255 - *(lpIn2 + j);
               j  += lpTH->ChannelSize;
               }
            else
               *lpOut++ = 0;
            if (lpTH->ColSepMask & 0x4)  // yellow
               {
               *lpOut++ = 255 - *(lpIn2 + j);
               j  += lpTH->ChannelSize;
               }
            else
               *lpOut++ = 0;
            }
         if (lpTH->ColSepMask & 0x8)  // black
            *lpOut++ = 255 - *(lpIn2 + j);
         else
            *lpOut++ = 0;
         lpIn2++;
			}
		if( fConvert )
			Convert.ConvertData( lpFrmLine, lpFrmLine, y, lpTH->Pixels );
		}
   m_iWidth       = lpTH->Pixels;
   m_iHeight      = lpTH->Lines;
   m_iRes         = (int)lpTH->Resolution;
   m_lpFrame      = lpFrame;

   fRet = TRUE;
   goto Exit;

BadRead:
	SetError(BEC_errFileRead);
goto Exit;

BadWrite:
	SetError(BEC_errFrameRead);

Exit:
   FreeCTHeader(lpTH);
   CloseFile(pTheFile);
   if (!fRet && lpFrame)
	   FrameClose(lpFrame);

   ProgressEnd();
   return( fRet );
   }
Ejemplo n.º 8
0
void	doputshort(unsigned short int x, CFile f)
{
	f.Write(&x, sizeof(x));
}
Ejemplo n.º 9
0
short int CDBConverter::LoadHDR(CFile fp, bool DXMode)// send to the function the FILE pointer of your open file stream (Koreaobj.hdr)
{
	int						c,d;
	int						cc;

	// Zero out HDR records
	ZeroMemory(&hdrLOD,sizeof(hdrLOD));
	ZeroMemory(&hdrLODRes,sizeof(hdrLODRes));

	cc = 0;
	hdr.version = dogetlong(fp);// dogetlong simply reads in a 4 byte integer
															// since the Mac reads bytes differently, I use a function to read in the bytes and reverse the order.
	hdr.nColor = dogetlong(fp);
	if((hdr.nColor > MAX_COLOR) | (hdr.nColor < 1))
		return (1);
	hdr.nDarkColor = dogetlong(fp);
	for(c=0;c<hdr.nColor;c++)
	{
		for(d=0;d<4;d++)
			hdrColor[c].f[d] = dogetfloat(fp);// dogetfloat reads in a 4 byte float
		
		if (c == 774)	// Formation strip-lights
		{
			hdrColor[c].f[0] = 0.6f;
			hdrColor[c].f[1] = 0.6f;
			hdrColor[c].f[2] = 0.0f;
		}
	}
	hdr.nPalette = dogetlong(fp);
	if((hdr.nPalette > MAX_PALETTE) | (hdr.nPalette < 1))
//		return (2);
		cc = 2;
	for(c=0;c<hdr.nPalette;c++)
	{
		for(d=0;d<256;d++)
		{
			hdrPalette[c].r[d] = dogetchar(fp);  
			hdrPalette[c].g[d] = dogetchar(fp);
			hdrPalette[c].b[d] = dogetchar(fp);
			hdrPalette[c].a[d] = dogetchar(fp);
		}
		hdrPalette[c].uint[0] = dogetlong(fp); 
		hdrPalette[c].uint[1] = dogetlong(fp); 
	}
	hdr.nTexture = dogetlong(fp);
	if((hdr.nTexture > MAX_TEXTURE) | (hdr.nTexture < 1))
		return (3);
	
	hdr.unk[0] = dogetlong(fp); // Largest texture (compressed size)
	for(c=0;c<hdr.nTexture;c++)
	{
		for(d=0;d<10;d++)
			hdrTexture[c].uint[d] = dogetlong(fp);
	}
	hdr.unk[1] = dogetlong(fp); // Max number of nodes
	maxNodes = hdr.unk[1];
	if (hdr.unk[1] < MAX_NODES)
		maxNodes = hdr.unk[1] = MAX_NODES;
	hdr.nLOD = dogetlong(fp);
	LastLOD = hdr.nLOD;
	if((hdr.nLOD > MAX_LOD) | (hdr.nLOD < 1))
		return (4);
	for(c=0;c<hdr.nLOD;c++)
	{
		for(d=0;d<5;d++)										 // [0], [1], [2] not used 
			hdrLOD[c].uint[d] = dogetlong(fp); // [3] KO.lod file offset
	 																			 // [4] LOD length
	}
	hdr.nParent = dogetlong(fp);
	if((hdr.nParent > MAX_PARENT) | (hdr.nParent < 1))
		return (5);
	for(c=0;c<hdr.nParent;c++)
	{
		for(d=0;d<7;d++)
			hdrParent[c].f[d] = dogetfloat(fp);	// Hitbox +"radius" (shadow size???)
		for(d=0;d<2;d++)
			hdrParent[c].uint[d] = dogetlong(fp);	// file offset [0] & size [1]
		for(d=0;d<2;d++)
			hdrParent[c].ushort1[d] = dogetshort(fp);// nTexures [0] & nDynamics[1]
		for(d=0;d<4;d++)
			hdrParent[c].uchar[d] = dogetchar(fp); // nLODs [0], nSwitches [1], nDOFs [2], nSlots [3]
		for(d=0;d<2;d++)
			hdrParent[c].ushort2[d] = dogetshort(fp);	// Unk1 [0] & Unk2 [1]
	}
	for(c=0;c<hdr.nParent;c++)
	{
		if(hdrParent[c].uchar[3] > 100)
			return (6);
		if(hdrParent[c].uchar[3] > 0)// Load Slots
		{
			for(d=0;d<hdrParent[c].uchar[3];d++)
			{
				hdrLODRes[c].slot1[d] = dogetfloat(fp);
				hdrLODRes[c].slot2[d] = dogetfloat(fp);
				hdrLODRes[c].slot3[d] = dogetfloat(fp);
			}
		}
		if(hdrParent[c].ushort1[1] > 10)
			return (7);
		if(hdrParent[c].ushort1[1] > 0)// Load Dynamic
		{
			for(d=0;d<hdrParent[c].ushort1[1];d++)
			{
				hdrLODRes[c].dyn1[d] = dogetfloat(fp);
				hdrLODRes[c].dyn2[d] = dogetfloat(fp);
				hdrLODRes[c].dyn3[d] = dogetfloat(fp);
			}
		}
		if(hdrParent[c].uchar[0] > 10)
			return (8);

		if(hdrParent[c].uchar[0] > 0)// Load LOD indexes
		{
			for(d=0;d<hdrParent[c].uchar[0];d++)
			{
				if(DXMode)
					fp.Read(hdrLODRes[c].LODName[d],32);
				hdrLODRes[c].lodind[d] = dogetlong(fp);
				hdrLODRes[c].distance[d] = dogetfloat(fp);
			}
		}
	}
	return (cc);
} // end LoadHDR()
Ejemplo n.º 10
0
void	doputfloat(float x, CFile f)
{
	f.Write(&x, sizeof(x));
}
Ejemplo n.º 11
0
void	doputchar(char x, CFile f)
{
	f.Write(&x, sizeof(x));
}
Ejemplo n.º 12
0
void	doputlong(long x, CFile f)
{
	f.Write(&x, sizeof(x));
}
Ejemplo n.º 13
0
unsigned short int	dogetshort(CFile f)
{
	unsigned short int	x;
	f.Read(&x, sizeof(x));
	return x;
}
Ejemplo n.º 14
0
char	dogetchar(CFile f)
{
	char	x;
	f.Read(&x, sizeof(x));
	return x;
}
Ejemplo n.º 15
0
// ============================================================================
bool CVisualMSDoc::SaveVMS(const CString &fname, bool bSelOnly)
{
	CFile f;
	if(!f.Open(fname, CFile::modeCreate | CFile::modeWrite))
	{
		MessageBoxf(MaxSDK::GetResourceStringAsMSTR(IDS_ERROR_SAVING_FILE_), (LPCTSTR)fname);
		return false;
	}
	CArchive ar(&f, CArchive::store);

	VmsHeader hdr;
	hdr.magic = VMS_MAGIC;
	hdr.version = VMS_VERSION;

	CUIntArray selArr;

	if(bSelOnly)
	{
		GetSelectionSet(selArr);
		hdr.numObj = GetSelectionCount();
	}
	else
		hdr.numObj = m_objects.GetSize();

	// store the whole header with one write
	ar.Write(&hdr, sizeof(VmsHeader));

	for(int i = 0; i < hdr.numObj; i++)
	{
		CGuiObj *obj;
		if(bSelOnly)
			obj = (CGuiObj*)m_objects[selArr[i]];
		else
			obj = (CGuiObj*)m_objects[i];

		ar << obj->m_createID;

		int numProps = obj->m_properties.GetSize();
		ar << numProps;

		for(int j = 0; j < numProps; j++)
		{
			CProperty *prop = &obj->m_properties[j];
			ar << prop->m_name;
			ar << prop->m_type;
			ar << prop->m_flags;

			switch(prop->m_type)
			{
			case PROP_INTEGER:
			case PROP_OPTION:
				ar << prop->m_integer;
				break;
			case PROP_BOOLEAN:
				ar << (BOOL)prop->m_boolean;
				break;
			case PROP_REAL:
				ar << prop->m_real;
				break;
			case PROP_ARRAY:
				SaveStringArray(ar, prop->m_array);
				break;
			case PROP_STRING:
			case PROP_FILENAME:
				ar << prop->m_string;
				break;

			// if the property type is not supported by the VMS file I/O
			// write it as a string
			default:
				{
					CString str = (LPCTSTR)*prop;
					ar << str;
				}
				break;
			}
		}

		int numEvents = obj->m_handlers.GetSize();
		ar << numEvents;

		for(int j = 0; j < numEvents; j++)
		{
			CHandler *hndlr = &obj->m_handlers[j];
			ar << (BOOL)hndlr->m_use;
			ar << hndlr->m_name;
			ar << hndlr->m_args;
			ar << hndlr->m_text;
		}
	}

	// close the archive and file handle
	ar.Close();
	f.Close();

	return true;
}
Ejemplo n.º 16
0
void	CDBConverter::SaveHDR(CFile fp, bool DXMode)
{
				int						c,d;

	char	LODName[HDR_LODNAMELEN];
	doputlong((long)hdr.version,fp);
	if(hdr.nColor > MAX_COLOR)
		hdr.nColor = MAX_COLOR;
	doputlong((long)hdr.nColor,fp);
	doputlong((long)hdr.nDarkColor,fp);
	for(c=0;c<hdr.nColor;c++)
	{
		for(d=0;d<4;d++)
			doputfloat(hdrColor[c].f[d],fp);
	}
	if(hdr.nPalette > MAX_PALETTE)
		hdr.nPalette = MAX_PALETTE;
	doputlong(hdr.nPalette,fp);
	for(c=0;c<hdr.nPalette;c++)
	{
		for(d=0;d<256;d++)
		{
			doputchar(hdrPalette[c].r[d],fp);
			doputchar(hdrPalette[c].g[d],fp);
			doputchar(hdrPalette[c].b[d],fp);
			doputchar(hdrPalette[c].a[d],fp);
		}
		doputlong(hdrPalette[c].uint[0],fp);
		doputlong(hdrPalette[c].uint[1],fp);
	}
	if(hdr.nTexture > MAX_TEXTURE)
		hdr.nTexture = MAX_TEXTURE;
	doputlong(hdr.nTexture,fp);// 21
	doputlong(hdr.unk[0],fp);
	for(c=0;c<hdr.nTexture;c++)
	{
		for(d=0;d<10;d++)
			doputlong(hdrTexture[c].uint[d],fp);
	}
	// Make sure max number of nodes is big enough
	if (hdr.unk[1] < 10000)
		hdr.unk[1] = 10000;
	doputlong(hdr.unk[1],fp);
	if(hdr.nLOD > MAX_LOD)
		hdr.nLOD = MAX_LOD;
	doputlong(hdr.nLOD,fp);// 54
	for(c=0;c<hdr.nLOD;c++)
	{
		if(c==1629)
				_asm nop;

		for(d=0;d<5;d++)
			doputlong(hdrLOD[c].uint[d],fp);		// <<====  use hdrLOD[c].uint[0] - hdrLOD[c].uint[2] for dxl offset and size
	}
	if(hdr.nParent > MAX_PARENT)
		hdr.nParent = MAX_PARENT;
	doputlong(hdr.nParent,fp);// 16
	for(c=0;c<hdr.nParent;c++)
	{
		if(hdrParent[c].uchar[3] > 100)
			hdrParent[c].uchar[3] = 100;
		if(hdrParent[c].ushort1[1] > 10)
			hdrParent[c].ushort1[1] = 10;
		if(hdrParent[c].uchar[0] > 10)
			hdrParent[c].uchar[0] = 10;
		for(d=0;d<7;d++)
			doputfloat(hdrParent[c].f[d],fp);
		for(d=0;d<2;d++)
			doputlong(hdrParent[c].uint[d],fp);
		for(d=0;d<2;d++)
			doputshort(hdrParent[c].ushort1[d],fp);
		for(d=0;d<4;d++)
			doputchar(hdrParent[c].uchar[d],fp);
		for(d=0;d<2;d++)
			doputshort(hdrParent[c].ushort2[d],fp);
	}
	for(c=0;c<hdr.nParent;c++)
	{
		if(hdrParent[c].uchar[3] > 0)// Save Slots
		{
			for(d=0;d<hdrParent[c].uchar[3];d++)
			{
				doputfloat(hdrLODRes[c].slot1[d],fp);
				doputfloat(hdrLODRes[c].slot2[d],fp);
				doputfloat(hdrLODRes[c].slot3[d],fp);
			}
		}
		if(hdrParent[c].ushort1[1] > 0)// Save Dynamic
		{
			for(d=0;d<hdrParent[c].ushort1[1];d++)
			{
				doputfloat(hdrLODRes[c].dyn1[d],fp);
				doputfloat(hdrLODRes[c].dyn2[d],fp);
				doputfloat(hdrLODRes[c].dyn3[d],fp);
			}
		}
		if(hdrParent[c].uchar[0] > 0)// Save LOD indexes
		{
			for(d=0;d<hdrParent[c].uchar[0];d++)
			{
				if ((int)hdrLODRes[c].lodind[d] == -1)
					hdrLODRes[c].lodind[d] = 0;
				if(!DXMode){
					memset(LODName,0,sizeof(LODName));
					strcpy(LODName,LODNames[LODNUMBER(hdrLODRes[c].lodind[d])]);
					fp.Write(LODName,HDR_LODNAMELEN);
				} else {
					fp.Write(hdrLODRes[c].LODName[d],HDR_LODNAMELEN);
				}
				doputlong(hdrLODRes[c].lodind[d],fp);
				doputfloat(hdrLODRes[c].distance[d],fp);
			}
		}
	}

//	fp.Close();
	return;
} // end SaveHDR()
Ejemplo n.º 17
0
// ============================================================================
bool CVisualMSDoc::MergeVMS(const CString &fname, bool bPaste)
{
	CFile f;
	if(f.Open(fname, CFile::modeRead) == FALSE)
	{
		MessageBoxf(MaxSDK::GetResourceStringAsMSTR(IDS_ERROR_LOADING_FILE_), (LPCTSTR)fname);
		return false;
	}
	DeSelectAll();
	CArchive ar(&f, CArchive::load);

	VmsHeader hdr;
	ar.Read(&hdr, sizeof(VmsHeader));

	if(hdr.magic != VMS_MAGIC)
	{
		MessageBoxf(MaxSDK::GetResourceStringAsMSTR(IDS__IS_NOT_A_VALID_VISUAL_MAXSCRIPT_BINARY), (LPCTSTR)fname);
		ar.Close();
		f.Close();
		return false;
	}

	if(hdr.version != VMS_VERSION)
	{
		MessageBoxf(MaxSDK::GetResourceStringAsMSTR(IDS__HAS_AN_UNSUPPORTED_FILE_VERSION), (LPCTSTR)fname);
		ar.Close();
		f.Close();
		return false;
	}

	CFormEd *formEd = &GetFormObj()->m_formEd;

	for(int i = 0; i < hdr.numObj; i++)
	{
		UINT nID;
		int numProps;

		ar >> nID;
		ar >> numProps;

		CGuiObj *obj = NULL;
		if(nID == 0)
			obj = (CGuiObj*)m_objects[0];
		else
		{
			obj = CGuiObj::Create(nID, formEd, CRect(0,0,60,40));
			if(obj)
			{
				obj->m_selected = FALSE;
				AddObj(obj);
			}
		}

		if(numProps > obj->m_properties.GetSize())
		{
		}

		for(int j = 0; j < numProps; j++)
		{
			// Its possible for there to be more properties then the defualt VMS
			// constructors added so dynamically add these
			if(j >= obj->m_properties.GetSize())
				obj->m_properties.Add(CProperty(_T("dynamic"), CString("")));

			// if were loading the form and its a paste operation
			// dont paste the forms properties, put in a dummy
			CProperty dummyProp;
			CProperty *prop = NULL;
			if(bPaste && nID == 0)
				prop = &dummyProp;
			else
				prop = &obj->m_properties[j];

			ar >> prop->m_name;
			ar >> prop->m_type;
			ar >> prop->m_flags;

			switch(prop->m_type)
			{
			case PROP_STRING:
				// if pasting we want to use the default control names
				if(bPaste && j == IDX_NAME)
				{
					CString name;
					ar >> name;
				}
				else
					ar >> prop->m_string;
				break;
			case PROP_INTEGER:
			case PROP_OPTION:
				ar >> prop->m_integer;
				break;
			case PROP_BOOLEAN:
				{
					BOOL b;
					ar >> b;
					prop->m_boolean = (bool)b;
					break;
				}
			case PROP_REAL:
				ar >> prop->m_real;
				break;
			case PROP_ARRAY:
				LoadStringArray(ar, prop->m_array);
				break;
			case PROP_FILENAME:
				ar >> prop->m_string;
				break;

			// if the property type is not supported by the VMS file I/O
			// read it as a string
			default:
				{
					CString str;
					ar >> str;
					*prop = (LPCTSTR)str;
				}
				break;
			}

			obj->PropChanged(j);
		}
Ejemplo n.º 18
0
int	CDBConverter::LoadCT()
{
	int					c,d;
	CFile				fp;
	char				nctr[6];
	float				BubbleDist;
	char				szMsg[512];
	char				Names[128];

	sprintf(szMsg, "%sFalcon4.ct", KoreaObjFolder); 
	fp.Open(szMsg,CFile::modeRead);
	ctNumber = dogetshort(fp);
	if (ct)
	{
		free(ct);
		ct = NULL;
	}
	ct = (CT*)malloc(ctNumber*sizeof(CT));
	memset(ct, 0, (ctNumber*sizeof(CT)));
	for(c=0;c<ctNumber;c++)
	{
		fp.Seek(c*81+10,CFile::begin);
		ct[c].domain = dogetchar(fp);
		ct[c].cclass = dogetchar(fp);
		ct[c].type = dogetchar(fp);
		ct[c].subtype = dogetchar(fp);
		ct[c].specific = dogetchar(fp);
		ct[c].mode = dogetchar(fp);
		fp.Seek(10,CFile::current);
		BubbleDist = dogetfloat(fp);
		fp.Seek(32,CFile::current);
		for(d=0;d<8;d++)
			ct[c].parent[d] = dogetshort(fp);
//		fseek(fp,2,SEEK_CUR);
		ct[c].ftype = dogetchar(fp);
		ct[c].foffset = dogetlong(fp);
			
	}
	fp.Close();
	sprintf(szMsg, "%sFalcon4.fcd", KoreaObjFolder); // Load Features
	fp.Open(szMsg,CFile::modeRead);
	for(c=0;c<ctNumber;c++)
	{
		if(ct[c].ftype == 1)
		{

			fp.Seek(ct[c].foffset*60+10,CFile::begin);
			fp.Read(ct[c].name,20);
			if(strlen(ct[c].name)){
				strcpy(Names, ct[c].name);
				CompileNewName(Names);
				strcpy(CTNames[c], Names);
			}
		}
	}
	fp.Close();
	sprintf(szMsg, "%sFalcon4.ocd", KoreaObjFolder); // Load Objects 
	fp.Open(szMsg,CFile::modeRead);
	for(c=0;c<ctNumber;c++)
	{
		if(ct[c].ftype == 3)
		{
			fp.Seek(ct[c].foffset*54+4,CFile::begin);
			fp.Read(ct[c].name,20);
			if(strlen(ct[c].name)){
				strcpy(Names, ct[c].name);
				CompileNewName(Names);
				strcpy(CTNames[c], Names);
			}
		}
	}
	fp.Close();
	sprintf(szMsg, "%sFalcon4.ucd", KoreaObjFolder); // Load Units
	fp.Open(szMsg,CFile::modeRead);
	for(c=0;c<ctNumber;c++)
	{
		if(ct[c].ftype == 4)
		{
			fp.Seek((ct[c].foffset)*336+232,CFile::begin);
			fp.Read(ct[c].name,22);
			if(strlen(ct[c].name)){
				strcpy(Names, ct[c].name);
				CompileNewName(Names);
				strcpy(CTNames[c], Names);
			}
		}
	}
	fp.Close();
	sprintf(szMsg, "%sFalcon4.vcd", KoreaObjFolder); // Load Vehicles
	fp.Open(szMsg,CFile::modeRead);
	for(c=0;c<ctNumber;c++)
	{
		if(ct[c].ftype == 5)
		{
//			if (bLP)
//				fp.Seek(ct[c].foffset*176+16,CFile::begin);  //LP
//			else
				fp.Seek(ct[c].foffset*160+10,CFile::begin);	//FF
			fp.Read(ct[c].name,15);
			fp.Read(nctr,5);
			if(strlen(ct[c].name)){
				strcpy(Names, ct[c].name);
				CompileNewName(Names);
				strcpy(CTNames[c], Names);
			}
		}
	}
	fp.Close();
	sprintf(szMsg, "%sFalcon4.wcd", KoreaObjFolder); // Load Weapons
	fp.Open(szMsg,CFile::modeRead);
	for(c=0;c<ctNumber;c++)
	{
		if(ct[c].ftype == 6)
		{
			fp.Seek(ct[c].foffset*60+14,CFile::begin);
			fp.Read(ct[c].name,16);
			if(strlen(ct[c].name)){
				strcpy(Names, ct[c].name);
				CompileNewName(Names);
				strcpy(CTNames[c], Names);
			}
		}
	}
	fp.Close();
	return(ctNumber);
} 
Ejemplo n.º 19
0
BOOL CWriteBitmap::CTWrite()
   {
	RECT              rSave;
	FRMTYPEINFO       inType, outType;
	LPFRAME           lpFrame;
	CFrameTypeConvert TypeConvert;
	LPOBJECT          lpObject;
	CFile 	         theFile;
	CFile*	         pTheFile = NULL;
	BOOL              fRet = FALSE;
	LPTR              lpTH, lp, lp2,lpBuffer, lpImgScanline;
	int               i,x,j,y, LineSize, npix, nlin;
   double            dbl;
   int               NumOfChannels = 4;

	if (m_lpObjList)
	   {
		lpObject = m_lpObjList->lpHead;
		if (lpObject)
			lpFrame = ObjGetEditFrame(lpObject);
	   }
	else
	   {
		lpFrame = m_lpFrame;
		lpObject = NULL;
	   }

	ASSERT(lpFrame);

	if (m_fSrcArea)
		rSave = m_rSrcArea;
	else
	   {
		rSave.top    = rSave.left = 0;
		rSave.bottom = FrameYSize(lpFrame)-1;
		rSave.right  = FrameXSize(lpFrame)-1;
	   }

	npix = RectWidth(&rSave);
	nlin = RectHeight(&rSave);
	inType = FrameTypeInfo(lpFrame);
	// cause FramePointer never returns line art
	if (inType.DataType == FDT_LINEART)
		inType.DataType = FDT_GRAYSCALE;
   
	if (inType.DataType == FDT_GRAYSCALE)
      {
      NumOfChannels = 1;
	   FrameSetTypeInfo(&outType, FDT_GRAYSCALE);
      }
   else
	   FrameSetTypeInfo(&outType, FDT_CMYKCOLOR);
		// initialize stuff to do the type conversion
	ProgressBegin(1);
	if ((pTheFile = OpenFile()) == NULL)
	{
		ProgressEnd();
		return(FALSE);
	}

   if (npix & 1) // odd pixels
      LineSize = npix + 1;
   else
      LineSize = npix;

	AllocLines(&lpBuffer, 1, max(LineSize*NumOfChannels, FrameByteWidth(lpFrame)), 1);
	AllocLines(&lpImgScanline, 1, max(LineSize*NumOfChannels, FrameByteWidth(lpFrame)), 1);
	if (!lpBuffer || !lpImgScanline)
	   {
	   SetError(BEC_errMemory);
		goto Exit;
	   }

   if (!(lpTH = Alloc(1024)))
	   {
	   SetError(BEC_errMemory);
	   return(NULL);
	   }

   clr( (LPTR)lpTH, 1024);
   
   set(lpTH, 80, ' ');
   lstrcpy((LPSTR)lpTH, m_lpFileName);
   lpTH[lstrlen(m_lpFileName)] = ' ';
   lpTH[80] = 'C';
   lpTH[81] = 'T';
	pTheFile->Write(lpTH, 1024);  // write first cluster

   clr( (LPTR)lpTH, 84);
   lpTH[0] = 1;               // inches
   lpTH[1] = NumOfChannels;   // 
   if (NumOfChannels == 1)
      *((LPWORD)&lpTH[2]) = 0x0800;
   else
      *((LPWORD)&lpTH[2]) = 0x0F00;
   dbl = nlin / (double)lpFrame->Resolution;
   sprintf((LPSTR)&lpTH[4], "%+.7E",dbl);
   lpTH[6] = lpTH[5];
   lpTH[5] = '.';
   if (lpTH[15] == '+')
      lpTH[17] = lpTH[18] + 1;
   else
      {
      lpTH[17] = lpTH[18] - 1;
      lpTH[15] = '+';
      }
   dbl = npix / (double)lpFrame->Resolution;
   sprintf((LPSTR)&lpTH[18], "%+.7E",dbl);
   lpTH[20] = lpTH[19];
   lpTH[19] = '.';
   if (lpTH[29] == '+')
      lpTH[31] = lpTH[32] + 1;
   else
      {
      lpTH[31] = lpTH[32] - 1;
      lpTH[29] = '+';
      }
   sprintf((LPSTR)&lpTH[32], "%+12d",nlin);
   lpTH[32] = '+';
   for (i=33; i < 44;i++)
      if (lpTH[i] == ' ' || lpTH[i] == '+')
         lpTH[i] = '0';
   sprintf((LPSTR)&lpTH[44], "%+12d",npix);
   lpTH[44] = '+';
   for (i=45; i < 56;i++)
      if (lpTH[i] == ' ' || lpTH[i] == '+')
         lpTH[i] = '0';
   lpTH[56] = 0;                 // scan direction
	pTheFile->Write(lpTH, 1024);  // write second cluster, Parameter Block
	TRY
	   {
	   if (!TypeConvert.Init(inType, outType, npix, DT_DEFAULT))
	      {
		   SetError(BEC_errMemory);
		   goto Exit;
		   }
		for( y=rSave.top; y <= rSave.bottom; y++)
		   {
			if (Progress( y-rSave.top, nlin, m_bEscapable ))
				goto Cancelled;
			if (lpObject)
			   {
				if (!ObjGetLine( lpObject, rSave.left, y,
					(rSave.right - rSave.left) + 1, lpImgScanline))
					goto BadRead;
				lp = lpImgScanline;
			   }
			else
			   {
				if ( !(lp = FramePointer( lpFrame, rSave.left, y, NO )) )
					goto BadRead;
			   }
			// convert the data to the new type
			TypeConvert.ConvertData(lp, lpBuffer, y, npix);
         lp2 = lpBuffer;
         for (x=0; x < npix; x++)
            for (j=0; j < NumOfChannels; j++)
               *(lpImgScanline + j * LineSize + x) = 255 - *lp2++;
			pTheFile->Write( lpImgScanline, LineSize*NumOfChannels);
         }
		fRet = TRUE;
		goto Exit;
	   }
	CATCH_ALL(e)
	   {
		goto BadWrite;
	   }
	END_CATCH_ALL


BadWrite:
   SetError(BEC_errWriteFile);
	goto Exit;

BadRead:
	SetError(BEC_errFrameRead);

Cancelled:
Exit:
	CloseFile(pTheFile, fRet);

	if (lpTH)
		FreeUp (lpTH);
	if (lpBuffer)
		FreeUp(lpBuffer);
	if (lpImgScanline)
		FreeUp(lpImgScanline);
	ProgressEnd();

	return( fRet );
   }
Ejemplo n.º 20
0
BOOL CTxtDropTarget::OnDrop(CWnd* pWnd, COleDataObject* pDataObject,
                           DROPEFFECT dropEffect, CPoint point)
{

	try{

    HGLOBAL hData=pDataObject->GetGlobalData(CF_TEXT);
    if (hData)
	{

	/*	pDataObject->BeginEnumFormats();
		FORMATETC fc;
		char tmp[20];
		while(pDataObject->GetNextFormat(&fc))
		{
			if(pDataObject->IsDataAvailable(fc.cfFormat))
			{
				GetClipboardFormatName(fc.cfFormat, tmp, 20);
				AfxMessageBox(tmp);
				itoa(fc.cfFormat, tmp, 10);
				AfxMessageBox(tmp);
			}
		}*/

		LPCSTR lpcszData=(LPCSTR)GlobalLock(hData);
	//	ms_pCtl->SetWindowText(lpcszData);
	//	SendMessage(pMainFrame->GetSafeHwnd(), WM_COMMAND, IDOK, 0);

		CString str2(lpcszData);
		GlobalUnlock(hData);

		//if it is a link?
		HGLOBAL hLinkData=pDataObject->GetGlobalData(RegisterClipboardFormat("FileGroupDescriptor"));
		LPCSTR lpcszLink;
		if(hLinkData)
		{
		   lpcszLink=((LPCSTR)GlobalLock(hLinkData)) + 76;
		   str2 += "\r\n";
		   str2 += lpcszLink;
		   str2 = str2.Left(str2.GetLength()-4);
	/*	int si = GlobalSize(hLinkData);
		CFile f;
		f.Open("d:\\tmp.txt", CFile::modeCreate|CFile::modeWrite);
		f.Write(lpcszLink-76, si);
		f.Close();*/
		   GlobalUnlock(hLinkData);
		}




		str2+="\r\n\r\n";
		if(((CMainFrame*)pMainFrame)->pCollectDlg)
		{
			int len = ((CMainFrame*)pMainFrame)->pCollectDlg->m_Editor.GetWindowTextLength( );
			((CMainFrame*)pMainFrame)->pCollectDlg->m_Editor.SetSel(len, len);
			((CMainFrame*)pMainFrame)->pCollectDlg->m_Editor.ReplaceSel(str2);
		}
		else
		{
			CFile f;
			if(f.Open(((CMyIEApp*)AfxGetApp())->m_strSaveTxtFile, CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite|CFile::shareDenyNone))
			{
				f.SeekToEnd();
				f.Write((void*)(LPCSTR)str2, str2.GetLength());
				f.Close();
			}
		}
	}
	else
	{
		hData=pDataObject->GetGlobalData(CF_HDROP);
		if (!hData) {
			TRACE("Fail in getting data\n");
			return FALSE;
		}

		HDROP hdrop =(HDROP)GlobalLock(hData);

		DragQueryFile(hdrop, 0, lpfiles, 1024);
		GlobalUnlock(hData);

		CString filename, rfile;
		filename = lpfiles;
		int l = filename.ReverseFind('\\');
		filename = filename.Mid(l+1);
		//fix filename, remove [x]
		l = filename.ReverseFind('[');
		int i = filename.ReverseFind(']');
		CString ext = filename.Mid(i+1);
		filename = filename.Left(l);
		filename = ((CMyIEApp*)AfxGetApp())->m_strImagePath + filename;
//		if(((CMyIEApp*)AfxGetApp())->m_bNeedCreateDir)
		{
			CreateDirectory(((CMyIEApp*)AfxGetApp())->m_strImagePath, NULL);
//			((CMyIEApp*)AfxGetApp())->m_bNeedCreateDir = FALSE;
		}
		
		//compare file size
		DWORD sz1, sz2=0;
		HANDLE hfile = INVALID_HANDLE_VALUE;
		hfile = CreateFile(lpfiles, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if(hfile != INVALID_HANDLE_VALUE)
			sz1 = GetFileSize(hfile, NULL);
		CloseHandle(hfile);
		hfile = INVALID_HANDLE_VALUE;
		hfile = CreateFile(filename+ext, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if(hfile != INVALID_HANDLE_VALUE)
			sz2 = GetFileSize(hfile, NULL);
		CloseHandle(hfile);

		rfile = filename + ext;
		if(sz1!=sz2 && sz2!=0)
		{
			char tmp[4];
			l = 0;
			HFILE hf; OFSTRUCT of;
			hf = OpenFile(rfile, &of, OF_EXIST);
			while(hf!=HFILE_ERROR)
			{
				l++;
				rfile = filename;
				rfile += '[';
				itoa(l, tmp, 10);
				rfile += tmp;
				rfile += ']';
				rfile += ext;
				hf = OpenFile(rfile, &of, OF_EXIST);
			}
		}

		if(!CopyFile(lpfiles, rfile, FALSE))
		{
			DWORD dwError = GetLastError();
			if(dwError == ERROR_PATH_NOT_FOUND)
				AfxMessageBox(IDS_SAVEIMAGEFAIL);
		}

	}

	}catch(...)
	{
	}

    return TRUE;
}
Ejemplo n.º 21
0
CString CBlokRtf::GetStrBuf(int& iBlk, CFile &inF,int& curPos, bool& bEnd)
{
// Читает в буфер
// переводит в стринг
// /*перемещает указатель в файле на велечину блока  iBlk*/
	int bPos,ePos;
	int iEnd=0;
//	int iCnt;
	CString strBuf,s;
	bPos=ePos=0;
	char* buf = new char[iBlk];

	bPos = curPos; // Запоминаю поз Входа

	iEnd = inF.Read(buf,iBlk); // Сколько считали на самом деле
		if(iEnd==0){
	//		s.Format("iEnd = %i",iEnd);
	//AfxMessageBox(s+"  iEnd==0");
			inF.Seek(bPos,CFile::begin);
			bEnd = false;
			return "";
		}
		if(iEnd<iBlk){	//******************* Прошли конец файла				   
			delete [] buf;
	/*		for(int i=0;i<iBlk;i++){
				*(buf+i)=_T('');
			}
	*/
	//		strBuf = _T("");

			iBlk = iEnd;				   // Поменял размер блока	
			char* bufE = new char[iBlk];
			inF.Seek(bPos,CFile::begin);  // вернулись на старое место

			curPos = inF.GetPosition();
//			s.Format("После возврата на стар место curPos = %i",curPos);
//AfxMessageBox(s);

			inF.Read(bufE,iBlk);		   // прочитал с новым iBlk
	//		bPos = curPos+iBlk;
//			s.Format("iBlk = %i curPos = %i, bPos = %i",iBlk,curPos,bPos);
//	AfxMessageBox(s+"  iEnd<iBlk");
			for(int i=0;i<iBlk;i++){
				strBuf+=*(bufE+i);
			}
//			s.Format("iBlk = %i curPos = %i, bPos = %i",iBlk,curPos,bPos);
//	AfxMessageBox(s+"  iEnd<iBlk"+'\n'+"strBuf = "+strBuf);
			inF.Seek(curPos,CFile::begin);	// Вернулся на старое место
			curPos = inF.GetPosition();
			delete [] bufE;
			return strBuf;
		}
//	iBlk = iEnd; // Контроль блок такой сколько считано
	for(int i=0;i<iBlk;i++){
		strBuf+=*(buf+i);
	}
	inF.Seek(bPos,CFile::begin);	// Вернулся на старое место
//	curPos = inF.GetPosition();
/*	s.Format("curPos = %i, bPos = %i",curPos,bPos);
AfxMessageBox(s);
*/
	delete [] buf;
	return strBuf;
}
Ejemplo n.º 22
0
BOOL CBADO::OnInitADOConn()
{
	CString StrTips;
	HANDLE hFind;//
	WIN32_FIND_DATA wfd;//
	hFind = FindFirstFile(m_dbfilepath, &wfd);//
	if (hFind == INVALID_HANDLE_VALUE)//说明当前目录下无t3000.mdb
	{
		// 	StrTips.Format(_T("%s\n The datebase file disappeared.T3000 help you create a default datebase of your current building."),m_dbfilepath);
		// 	AfxMessageBox(StrTips);
		CStringArray ArrayFileName;
		SplitCStringA(ArrayFileName, m_dbfilepath, L"\\");
		CString filename = L"";
		for (int i = 0; i < ArrayFileName.GetSize() - 1; i++)
		{
			filename += ArrayFileName[i];
			filename += L"\\";
		}
		CreateDirectory(filename,NULL);
		m_dbImgeFolder = filename + _T("image");
		CreateDirectory(m_dbImgeFolder,NULL);

		hFind = FindFirstFile(m_dbfilepath, &wfd);//
		if (hFind == INVALID_HANDLE_VALUE)//说明当前目录下没有building数据库的话,就创建一个
		{
#if 0
		HRSRC hrSrc = FindResource(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_BUILDING_DB2), _T("BUILDING_DB"));   
		HGLOBAL hGlobal = LoadResource(AfxGetResourceHandle(), hrSrc);   


		LPVOID lpExe = LockResource(hGlobal);   
		CFile file;
		if(file.Open(m_dbfilepath, CFile::modeCreate | CFile::modeWrite))    
			file.Write(lpExe, (UINT)SizeofResource(AfxGetResourceHandle(), hrSrc));    
		file.Close();    
		::UnlockResource(hGlobal);   
		::FreeResource(hGlobal);
#endif
		}//
		FindClose(hFind);

		//return FALSE;
	}
	::CoInitialize(NULL);
	try
	{
		////////////////////////////////////////////////////////////////////////////////////////////


		m_ConnectString = (CString)FOR_DATABASE_CONNECT + m_dbfilepath;

		// 		CStringArray  ArrayFileName;
		// 		SplitCStringA(ArrayFileName,m_dbfilepath,L"\\");
		// 		CString filename=L"";
		// 		for (int i=0;i<ArrayFileName.GetSize()-1;i++)
		// 		{
		// 			filename+=ArrayFileName[i];
		// 			filename+=L"\\";
		// 		}
		// 		m_dbImgeFolder=filename+_T("image");
		// 		CreateDirectory(m_dbImgeFolder,NULL);

		/////////////////////////////////////////////////////////////////////////////////////////////////
		//连接数据库


		m_pConnection.CreateInstance("ADODB.Connection");

		m_pConnection->Open(m_ConnectString.GetString(), "", "", adModeUnknown);
	}
	catch (_com_error e)
	{
		//AfxMessageBox(e.Description());
		return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 23
0
/**
**  Save a game to file.
**
**  @param filename  File name to be stored.
**  @return  -1 if saving failed, 0 if all OK
**
**  @note  Later we want to store in a more compact binary format.
*/
int SaveGame(const std::string &filename)
{
	CFile file;
	std::string fullpath(GetSaveDir());

	fullpath += "/";
	fullpath += filename;
	if (file.open(fullpath.c_str(), CL_WRITE_GZ | CL_OPEN_WRITE) == -1) {
		fprintf(stderr, "Can't save to `%s'\n", filename.c_str());
		return -1;
	}

	time_t now;
	char dateStr[64];

	time(&now);
	const struct tm *timeinfo = localtime(&now);
	strftime(dateStr, sizeof(dateStr), "%c", timeinfo);

	// Load initial level // Without units
	file.printf("local oldCreateUnit = CreateUnit\n");
	file.printf("local oldSetResourcesHeld = SetResourcesHeld\n");
	file.printf("local oldSetTile = SetTile\n");
	file.printf("function CreateUnit() end\n");
	file.printf("function SetResourcesHeld() end\n");
	file.printf("function SetTile() end\n");
	file.printf("Load(\"%s\")\n", Map.Info.Filename.c_str());
	file.printf("CreateUnit = oldCreateUnit\n");
	file.printf("SetResourcesHeld = oldSetResourcesHeld\n");
	file.printf("SetTile = oldSetTile\n");
	//
	// Parseable header
	//
	file.printf("SavedGameInfo({\n");
	file.printf("---  \"comment\", \"Generated by Stratagus Version " VERSION "\",\n");
	file.printf("---  \"comment\", \"Visit https://launchpad.net/stratagus for more informations\",\n");
	file.printf("---  \"type\",    \"%s\",\n", "single-player");
	file.printf("---  \"date\",    \"%s\",\n", dateStr);
	file.printf("---  \"map\",     \"%s\",\n", Map.Info.Description.c_str());
	file.printf("---  \"media-version\", \"%s\"", "Undefined");
	file.printf("---  \"engine\",  {%d, %d, %d},\n",
				StratagusMajorVersion, StratagusMinorVersion, StratagusPatchLevel);
	file.printf("  SyncHash = %d, \n", SyncHash);
	file.printf("  SyncRandSeed = %d, \n", SyncRandSeed);
	file.printf("  SaveFile = \"%s\"\n", CurrentMapPath);
	file.printf("\n---  \"preview\", \"%s.pam\",\n", filename.c_str());
	file.printf("} )\n\n");

	// FIXME: probably not the right place for this
	file.printf("GameCycle = %lu\n", GameCycle);

	file.printf("SetGodMode(%s)\n", GodMode ? "true" : "false");

	SaveUnitTypes(file);
	SaveUpgrades(file);
	SavePlayers(file);
	Map.Save(file);
	UnitManager.Save(file);
	SaveUserInterface(file);
	SaveAi(file);
	SaveSelections(file);
	SaveGroups(file);
	SaveMissiles(file);
	SaveReplayList(file);
	// FIXME: find all state information which must be saved.
	const std::string s = SaveGlobal(Lua);
	if (!s.empty()) {
		file.printf("-- Lua state\n\n %s\n", s.c_str());
	}
	SaveTriggers(file); //Triggers are saved in SaveGlobal, so load it after Global
	file.close();
	return 0;
}
Ejemplo n.º 24
0
void TorrentCreator::WriteOutputToFile(void)
{
    string torrentFilename = "C:\\BTTorrentGenerator\\";
    torrentFilename += m_pIPData->GetTorrentFileName();

    CFile torrentFile;
    if( !torrentFile.Open( torrentFilename.c_str(), CFile::modeCreate | CFile::modeWrite ) )
    {
        TRACE( "Error opening output file to write torrent\n" );
        return;
    }
    torrentFile.SetLength(0);

    BDictionary torrentDict;

    vector<BString *> v_trackers = m_pIPData->GetTrackerURLs();
    BDictionaryItem *announce_item = new BDictionaryItem();
    string key = "announce";
    announce_item->addStringItem(v_trackers[0], key);
    torrentDict.addItem(announce_item);

    BDictionaryItem *pAnnounceListDictItem = NULL;
    vector<BList *> vpUsedLists;
    if( v_trackers.size() > 1 )
    {
        pAnnounceListDictItem = new BDictionaryItem();
        BList *pAnnounceList = new BList();
        vpUsedLists.push_back( pAnnounceList );
        key = "announce-list";

        BList *pAnnounceListItem = new BList();
        vpUsedLists.push_back( pAnnounceListItem );
        pAnnounceListItem->addItem( v_trackers[0] );
        pAnnounceList->addItem( pAnnounceListItem );

        pAnnounceListItem = new BList();
        vpUsedLists.push_back( pAnnounceListItem );
        pAnnounceListItem->addItem( v_trackers[1] );
        pAnnounceList->addItem( pAnnounceListItem );

        if( v_trackers.size() == 3 )
        {
            pAnnounceListItem = new BList();
            vpUsedLists.push_back( pAnnounceListItem );
            pAnnounceListItem->addItem( v_trackers[2] );
            pAnnounceList->addItem( pAnnounceListItem );
        }

        pAnnounceListDictItem->addListItem( pAnnounceList, key );
        torrentDict.addItem( pAnnounceListDictItem );
    }
    v_trackers.clear();

    BInteger *creation_date = m_pIPData->GetCreationTime();
    BDictionaryItem * creation_date_item = new BDictionaryItem();
    key = "creation date";
    creation_date_item->addIntegerItem(creation_date, key);
    torrentDict.addItem(creation_date_item);

    torrentDict.WritePartialEncodedData( &torrentFile );
    unsigned int pos = (unsigned int)torrentFile.GetPosition();

    char buffer[7] = { '4', ':', 'i', 'n', 'f', 'o', '\0' };
    torrentFile.Write( buffer, 6 );
    pos = (unsigned int)torrentFile.GetPosition();

    //Write the info dictionary from the buffer.
    torrentFile.Write( m_pInfoBuffer, m_nInfoBufferSize );

    //end the torrentDict
    char end = 'e';
    torrentFile.Write( &end, 1 );
    torrentFile.Close();

    delete announce_item;
    delete creation_date_item;
    if( pAnnounceListDictItem != NULL )
    {
        delete pAnnounceListDictItem;
        pAnnounceListDictItem = NULL;
    }
    for( size_t i = 0; i < vpUsedLists.size(); i++ )
        delete vpUsedLists[i];
    vpUsedLists.clear();
}
Ejemplo n.º 25
0
//用户消息
bool CPlazaViewItem::OnSocketMainUser(CMD_Command Command, void * pBuffer, WORD wDataSize)
{
	ASSERT(Command.wMainCmdID == MDM_GP_USER);
	switch(Command.wSubCmdID)
	{
	case SUB_GP_USER_DOWNLOAD_FACE:			//下载头像
		{
			//类型转换
			CMD_GP_DownloadFaceSuccess *pDownloadFaceSuccess = (CMD_GP_DownloadFaceSuccess*)pBuffer;

			//参数验证
			WORD wSendSize = WORD(pDownloadFaceSuccess->dwCurrentSize + sizeof(CMD_GP_DownloadFaceSuccess) - sizeof(pDownloadFaceSuccess->bFaceData));
			ASSERT(wDataSize == wSendSize);
			if ( wDataSize != wSendSize ) return false;

			//第一次判断
			if ( m_CustomFace.pFaceData == NULL )
			{
				if ( m_CustomFace.pFaceData != NULL ) delete[] m_CustomFace.pFaceData;
				m_CustomFace.pFaceData = new BYTE[pDownloadFaceSuccess->dwToltalSize];
				if ( m_CustomFace.pFaceData == NULL ) return true;
				m_CustomFace.dwFaceSize = pDownloadFaceSuccess->dwToltalSize;
				m_CustomFace.dwUserID = pDownloadFaceSuccess->dwUserID;
			}

			//拷贝数据
			CopyMemory(m_CustomFace.pFaceData+m_CustomFace.dwCurrentSize, pDownloadFaceSuccess->bFaceData, pDownloadFaceSuccess->dwCurrentSize);
			m_CustomFace.dwCurrentSize += pDownloadFaceSuccess->dwCurrentSize;

			//下载完毕
			if ( m_CustomFace.dwFaceSize == m_CustomFace.dwCurrentSize )
			{
				tagDownloadInfo &DownloadInfo = m_DownloadInfoArrary[0];

				//创建目录
				CString strDirName = CString(g_GlobalUnits.GetWorkDirectory()) + TEXT("\\CustomFace");
				CreateDirectory(strDirName, NULL) ;

				//写入文件
				CFile fileFace;
				CString strZipFileName, strBmpFileName;
				strZipFileName.Format(TEXT("\\%ld_%d.zip"), DownloadInfo.dwUserID, DownloadInfo.bFaceVer);
				strBmpFileName.Format(TEXT("\\%ld_%d.bmp"), DownloadInfo.dwUserID, DownloadInfo.bFaceVer);
				if ( fileFace.Open(strDirName + strZipFileName, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary) )
				{
					fileFace.Write(m_CustomFace.pFaceData, m_CustomFace.dwFaceSize);
					fileFace.Close();

					//解压文件
					CUnzip oUnzip( strDirName + strZipFileName );
					oUnzip.SwapSize( strDirName + strBmpFileName );

					//删除文件
					CFile::Remove(strDirName + strZipFileName);
				}

				//自己判断
				tagGlobalUserData &GlobalUserData = g_GlobalUnits.GetGolbalUserData();
				if ( GlobalUserData.dwUserID ==  DownloadInfo.dwUserID )
				{
					//更新界面
					((CGameFrame*)AfxGetMainWnd())->m_UserInfoView.UpdateUserInfo();
				}

				//重置变量
				m_CustomFace.Clear();

				//删除元素
				m_DownloadInfoArrary.RemoveAt(0);

				//继续判断
				if ( 0 < m_DownloadInfoArrary.GetCount() )
				{
					//状态判断
					if ( m_ClientSocket->GetSocketStatus() != SOCKET_STATUS_CONNECT )
					{
						//链接网络
						if ( ! ConnectServer() ) return true;

						//设置标识
						m_bDownloadConnect = true;
					}

					//投递请求
					tagDownloadInfo &DownloadInfo = m_DownloadInfoArrary[0];

					CMD_GP_DownloadFace DownloadFace;
					DownloadFace.dwUserID = DownloadInfo.dwUserID;
					m_ClientSocket->SendData(MDM_GP_USER, SUB_GP_USER_DOWNLOAD_FACE, &DownloadFace, sizeof(DownloadFace));
				}
				else
				{
					//关闭链接
					m_ClientSocket->CloseSocket();

					//设置变量
					m_bStartDownloadFace=false;
				}
			}
			return true;
		}
	case SUB_GP_UPLOAD_FACE_RESULT:		//上传结果
		{
			ASSERT(sizeof(CMD_GP_UploadFaceResult) == wDataSize);
			if ( sizeof(CMD_GP_UploadFaceResult) != wDataSize) return true;

			//显示消息
			CMD_GP_UploadFaceResult *pUploadFaceResult = (CMD_GP_UploadFaceResult*)pBuffer;
			ShowMessageBox(pUploadFaceResult->szDescribeMsg, MB_ICONINFORMATION);

			//成功判断
			if ( pUploadFaceResult->bOperateSuccess )
			{
				//头像目录
				CString strDirName = CString(g_GlobalUnits.GetWorkDirectory()) + TEXT("\\CustomFace");
				CString strOldFileName;
				strOldFileName = TEXT("\\MyFace.bmp");

				//命名文件
				tagGlobalUserData &GlobalUserData = g_GlobalUnits.GetGolbalUserData();
				CString strNemFileName;
				strNemFileName.Format(TEXT("\\%ld_%d.bmp"), GlobalUserData.dwUserID, pUploadFaceResult->dwFaceVer);

				//删除文件
				try
				{
				CFile::Remove(strDirName + strNemFileName);
				}
				catch(...){}

				//删除文件
				CString strOldFile;
				strOldFile.Format(TEXT("\\%ld_%ld.bmp"), GlobalUserData.dwUserID, GlobalUserData.dwCustomFaceVer);
				try
				{
					CFile::Remove(strDirName + strOldFile);
				}
				catch(...){}

				try
				{
					CFile::Rename(strDirName + strOldFileName, strDirName + strNemFileName);

					//设置版本号
					GlobalUserData.dwCustomFaceVer = pUploadFaceResult->dwFaceVer;
					ASSERT(GlobalUserData.dwCustomFaceVer!=0);

					//投递消息
					for ( INT nIndex = 0; nIndex < MAX_SERVER; nIndex++ ) 
					{
						CRoomViewItem *pRoomViewItem = ((CGameFrame*)AfxGetMainWnd())->m_pRoomViewItem[nIndex];
						if ( pRoomViewItem == NULL ) continue;
						pRoomViewItem->SendMessage(WM_UPDATE_FACE, GlobalUserData.dwCustomFaceVer, GlobalUserData.dwUserID);
					}
				}
				catch(...)
				{
					ShowMessageBox(TEXT("头像文件命名失败,需要重新登录才可以显示新头像!"), MB_ICONINFORMATION);
				}

				//更新界面
				((CGameFrame*)AfxGetMainWnd())->m_UserInfoView.UpdateUserInfo();

				//设置界面
				CGameFrame *pGameFrame = (CGameFrame *)AfxGetMainWnd() ;
				CDlgCustomFace &DlgCustomFace = pGameFrame->m_DlgCustomFace;
				if ( DlgCustomFace.m_hWnd != NULL && DlgCustomFace.IsWindowVisible() )
				{
					DlgCustomFace.UpdateControls();
					DlgCustomFace.SetFocus();
				}
			}

			//关闭链接
			m_ClientSocket->CloseSocket();

			return true;
		}
	case SUB_GP_DELETE_FACE_RESULT:		//删除结果
		{
			ASSERT(sizeof(CMD_GP_DeleteFaceResult) == wDataSize);
			if ( sizeof(CMD_GP_DeleteFaceResult) != wDataSize) return true;

			//显示消息
			CMD_GP_DeleteFaceResult *pDeleteFaceResult = (CMD_GP_DeleteFaceResult*)pBuffer;
			ShowMessageBox(pDeleteFaceResult->szDescribeMsg, MB_ICONINFORMATION);

			//成功判断
			if ( pDeleteFaceResult->bOperateSuccess )
			{
				//获取信息
				tagGlobalUserData &GlobalUserData = g_GlobalUnits.GetGolbalUserData();

				//文件目录
				CString strDirName = CString(g_GlobalUnits.GetWorkDirectory()) + TEXT("\\CustomFace");

				//文件名字
				CString strFileName;
				strFileName.Format(TEXT("\\%ld_%d.bmp"), GlobalUserData.dwUserID, pDeleteFaceResult->dwFaceVer);

				//删除文件
				try
				{
				CFile::Remove(strDirName + strFileName);
				}
				catch(...){}
				
				//更新界面
				((CGameFrame*)AfxGetMainWnd())->m_UserInfoView.UpdateUserInfo();

				//设置界面
				CGameFrame *pGameFrame = (CGameFrame *)AfxGetMainWnd() ;
				CDlgCustomFace &DlgCustomFace = pGameFrame->m_DlgCustomFace;
				if ( DlgCustomFace.m_hWnd != NULL && DlgCustomFace.IsWindowVisible() )
				{
					DlgCustomFace.UpdateControls();
					DlgCustomFace.SetFocus();
				}
				
				//投递消息
				for ( INT nIndex = 0; nIndex < MAX_SERVER; nIndex++ ) 
				{
					CRoomViewItem *pRoomViewItem = ((CGameFrame*)AfxGetMainWnd())->m_pRoomViewItem[nIndex];
					if ( pRoomViewItem == NULL ) continue;
					pRoomViewItem->SendMessage(WM_UPDATE_FACE, GlobalUserData.dwCustomFaceVer, GlobalUserData.dwUserID);
				}
			}
			
			//关闭链接
			m_ClientSocket->CloseSocket();

			return true;
		}
	case SUB_GP_MODIFY_INDIVIDUAL_RESULT:	//修改结果
		{
			return true;
		}
	default:
		{
			ASSERT(FALSE);
			return false;
		}
	}
	return true;
}
Ejemplo n.º 26
0
BOOL CGIB::CreateGIBInputFile(CFile& file, CPlayer* pPlayer, CHandHoldings* pHand, CHandHoldings* pDummyHand, CString& strContents) const
{
	// format the input
	CString strInput;
	CEasyBDoc* pDoc = pDOC;

	// indicate player
	strInput.Format("%c\n",PositionToChar(pPlayer->GetPosition()));
	strContents += strInput;
	file.Write((LPCTSTR)strInput, strInput.GetLength());

	// indicate hand
	strInput = pHand->GetInitialHand().GetGIBFormatHoldingsString();
	strInput += '\n';
	strContents += strInput;
	file.Write((LPCTSTR)strInput, strInput.GetLength());

	// indicate dealer
	strInput.Format("%c\n",PositionToChar(pDoc->GetDealer()));
	strContents += strInput;
	file.Write((LPCTSTR)strInput, strInput.GetLength());

	// indicate vulnerability
	strInput = "n\n";	// TEMP
	strContents += strInput;
	file.Write((LPCTSTR)strInput, strInput.GetLength());

	// indicate auction
	strInput.Empty();
	int numBids = pDoc->GetNumBidsMade();
	for(int i=0;i<numBids;i++)
	{
		strInput += BidToBriefString(pDoc->GetBidByIndex(i));
		if (i < numBids)
			strInput += ' ';
	}
	strInput += '\n';
	strContents += strInput;
	file.Write((LPCTSTR)strInput, strInput.GetLength());

	// indicate opening lead
	int nLeadCard = pDoc->GetPlayRecord(0);
	strInput.Format("%s\n",CardToShortString(nLeadCard));
	strContents += strInput;
	file.Write((LPCTSTR)strInput, strInput.GetLength());
	
	// indicate dummy's (ORIGINAL) hand
	strInput = pDummyHand->GetInitialHand().GetGIBFormatHoldingsString();
	strInput += '\n';
	strContents += strInput;
	file.Write((LPCTSTR)strInput, strInput.GetLength());

	// and enter any plays so far
	strInput.Empty();
	int numCardsPlayed = pDoc->GetNumCardsPlayedInGame();
	for(i=1;i<numCardsPlayed;i++)
	{
		strInput += CardToShortString(pDoc->GetPlayRecord(i));
		strInput += ' ';
		if (((i % 3) == 0) || (i == numCardsPlayed-1))
		{
			// flush the line
			strInput += '\n';
			file.Write((LPCTSTR)strInput, strInput.GetLength());
			strInput.Empty();
		}
	}

	// end the file with a # sign
	strInput = "#\n";
	strContents += strInput;
	file.Write((LPCTSTR)strInput, strInput.GetLength());

	// done
	return TRUE;
}
Ejemplo n.º 27
0
void CDfuFileMgrDlgExtract::OnButtonextract() 
{
	if (m_hFile==0)
		return;

	int Sel=m_ListFiles.GetCurSel();

	if (Sel==-1)
		return;

	UpdateData(TRUE);

	HANDLE Image;

	if (STDFUFILES_ReadImageFromDFUFile(m_hFile, Sel, &Image)==STDFUFILES_NOERROR)
	{
		BYTE Alt;

		STDFUFILES_GetImageAlternate(Image, &Alt);

		CString FileName;
		FileName.Format("%s_%02i", m_FileBaseName, Alt);
		CString sFile;

		if (m_ExtractFormat==2) 
		{
			DWORD NbEl;

			if (STDFUFILES_GetImageNbElement(Image, &NbEl)==STDFUFILES_NOERROR)
			{
				CString Status;
				BOOL bSuccess=TRUE;

				for (DWORD i=0;i<NbEl;i++)
				{
					DFUIMAGEELEMENT Element={0};

					if (STDFUFILES_GetImageElement(Image, i, &Element)==STDFUFILES_NOERROR)
					{
						Element.Data=new BYTE[Element.dwDataLength];

						if (STDFUFILES_GetImageElement(Image, i, &Element)==STDFUFILES_NOERROR)
						{
							CFile File;
							CFileException ex;

							sFile.Format("%s_%08X.bin", FileName, Element.dwAddress);
							if (File.Open(sFile, CFile::modeCreate | CFile::modeWrite, &ex))
							{
								File.Write(Element.Data, Element.dwDataLength);
								File.Close();
								Status=Status+sFile;
								Status+=" was created !\n";
							}
							else
							{
								CString Err;
								bSuccess=FALSE;
								Err.Format("IoError %08xh", ex.m_lOsError);
								AfxMessageBox(Err);
								delete[]Element.Data;
								break;
							}
						}
						else
						{
							AfxMessageBox("Unable to access element in image...");
							bSuccess=FALSE;
							delete[]Element.Data;
							break;
						}
						delete[]Element.Data;
					}
					else
					{
						AfxMessageBox("Unable to access element in image...");
						bSuccess=FALSE;
						break;
					}
				}
				if (bSuccess)
					AfxMessageBox(Status);
			}
			else
				AfxMessageBox("Unable to access element in image...");
		}
		else
		{
			if (m_ExtractFormat==0) 
				FileName+=".s19";
			else
			if (m_ExtractFormat==1)
				FileName+=".hex";
			if (STDFUFILES_ImageToFile((LPSTR)(LPCSTR)FileName, Image)==STDFUFILES_NOERROR)
			{
				FileName+=" was created !";
				AfxMessageBox(FileName);
			}
			else
				AfxMessageBox("Error while creating file...");
		}
		STDFUFILES_DestroyImage(&Image);
	}
	else
		AfxMessageBox("Unable to read file...");
}
Ejemplo n.º 28
0
//
// Invoke()
//
// invoke the GIB program and return the recommended play
//
int CGIB::Invoke(CPlayer* pPlayer, CHandHoldings* pHand, CHandHoldings* pDummyHand, CPlayerStatusDialog* pStatusDlg)
{
	SECURITY_ATTRIBUTES saAttr; 
	
	//
	// create the GIB monitor dialog
	//
	CGIBDialog	gibDialog(pMAINFRAME);
	int nProcessingTime = theApp.GetValue(tnGIBAnalysisTime);
	gibDialog.m_nProcessTime = nProcessingTime;
//	gibDialog.m_hEventCancel = m_hEventCancel;

	
	// Set the bInheritHandle flag so pipe handles are inherited. 
	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
	saAttr.bInheritHandle = TRUE; 
	saAttr.lpSecurityDescriptor = NULL; 
	
	//
	// create input and output pipes for the child process
	//

	// Create a pipe for the child process's STDOUT. 
	if (!CreatePipe(&m_hChildStdoutRd,	// returns the pipe's input handle
				    &m_hChildStdoutWr, 	// returns the pipe's output handle
					&saAttr, 
					0)) 
	{
		CString strError = "Stdout pipe creation failed\n"; 
		TRACE(strError); 
		pMAINFRAME->SetGIBMonitorText(strError);
		return ExitGracefully(-5);
	}
	// then create a pipe for the child process's STDIN. 
	if (!CreatePipe(&m_hChildStdinRd, 
					&m_hChildStdinWr, 
					&saAttr, 
					0)) 
	{
		CString strError = "Stdin pipe creation failed\n"; 
		TRACE(strError); 
		pMAINFRAME->SetGIBMonitorText(strError);
		return ExitGracefully(-5);
	}

	//
	// Now create the child process (GIB)
	//
	PROCESS_INFORMATION piProcInfo; 
	if (!LaunchProgram(piProcInfo)) 
	{
		TRACE("Create process failed"); 
		return ExitGracefully(-1);
	}
	HANDLE hGIBProcess = piProcInfo.hProcess;
	DWORD nGIBProcessID = piProcInfo.dwProcessId;

	// now close the readable handle to the child's stdin
	SafeCloseHandle(m_hChildStdinRd);
	// and the writable handle to the child's stdout
	SafeCloseHandle(m_hChildStdoutWr);

	//
	//------------------------------------------------------------------
	//
	// create the GIB input file
	//
	CFile file;
	CFileException fileException;
	CString strTempFile, strTempPath;
	GetTempPath(1024, strTempPath.GetBuffer(1024));
	strTempPath.ReleaseBuffer();
	GetTempFileName(strTempPath, "ezb", 0, strTempFile.GetBuffer(2048));
	strTempFile.ReleaseBuffer();
//	strTempFile.Format("%s\\%s", theApp.GetValueString(tszProgramDirectory), tszGIBTempFilename);
/*
	LPTSTR szBuffer = strTempFile.GetBuffer(MAX_PATH);
	GetTempFileName(theApp.GetValueString(tszProgramDirectory), "ezb", 0, szBuffer);
	strTempFile.ReleaseBuffer();
*/
//	CString strInput;
//	strInput.Format("-T %d %s\n",theApp.GetValue(tnGIBAnalysisTime),strTempFile);
	int nCode = file.Open(strTempFile, 
			  			  CFile::modeWrite | CFile::modeCreate | CFile::shareDenyWrite, 
						  &fileException);
	if (nCode == 0) 
	{
		CString strError = "Error opening temporary input file for GIB"; 
		TRACE(strError); 
		pMAINFRAME->SetGIBMonitorText(strError);
		return ExitGracefully(-2);
	}
	//
	CString strFileContents;
	CreateGIBInputFile(file, pPlayer, pHand, pDummyHand, strFileContents);
	file.Close();

	// then send the parameters line
	CString strParameters, strShortParameters;
	strParameters.Format("-T %d %s\n",nProcessingTime,strTempFile);
	strShortParameters.Format("-T %d",nProcessingTime);
	DWORD dwWritten;
	int nErrCode;
	if (!WriteFile(m_hChildStdinWr, (LPCTSTR)strParameters, strParameters.GetLength(), &dwWritten, NULL)) 
	{
		CString strError = "Error providing parameters to GIB"; 
		TRACE(strError); 
		pMAINFRAME->SetGIBMonitorText(strError);
		nErrCode = GetLastError();
		return ExitGracefully(-3);
	}

	//
	// update the GIB monitor window
	//
	CString strGIBText = "========================================\n";
	strGIBText += FormString("Launching %s %s\n",
							 theApp.GetValueString(tszGIBPath),
							 strShortParameters);
//	strGIBText += FormString("Input file contents:\n%s", strFileContents);
	strGIBText += "Awaiting Responses...\n";
	strGIBText += "----------------------------------------\n";
//	pMAINFRAME->SetGIBMonitorText(strGIBText);
	pMAINFRAME->AppendGIBMonitorText(strGIBText);
	

	//
	//------------------------------------------------------------
	//
	// now set up the wait loop and the cancel dialog,
	// then sit and wait for the process to run or for a cancel message
	//

/*
	//
	// create the "Cancel GIB" dialog thread
	// (this is a user interface thread)
	//
	CGIBMonitorThread* pMonitorThread = new CGIBMonitorThread(m_hEventFinished, m_hEventCancel, nProcessingTime);
	pMonitorThread->CreateThread(CREATE_SUSPENDED);
	pMonitorThread->SetThreadPriority(THREAD_PRIORITY_ABOVE_NORMAL);
	pMonitorThread->ResumeThread();

	// wait for the monitor thread to initialize
	DWORD nCode0 = WaitForSingleObject(m_hEventFinished,
									   INFINITE);		
*/

	//
	// create the wait thread
	// (this is a worker thread)
	//
	GIBStruct gibData;
	gibData.hReadHandle = m_hChildStdoutRd;
	gibData.pGIBDialog = &gibDialog;
	CWinThread* pWaitThread = AfxBeginThread(CGIB::ReadGIBOutput, &gibData, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);

	// copy its handle se that we can check its exit code later
  	HANDLE hWaitThread;
	BOOL bCode = ::DuplicateHandle(GetCurrentProcess(), pWaitThread->m_hThread, 
								   GetCurrentProcess(), &hWaitThread, 
								   0, FALSE, DUPLICATE_SAME_ACCESS);
	// and launch the threads
//	MonitorThread->ResumeThread();
	pWaitThread->ResumeThread();


	//
	// Show the Wait/Cancel dialog
	//
	m_bGIBPending = TRUE;		// mark dialog as active
	bCode = gibDialog.DoModal();

	// see if the user cancelled
	if (!bCode) 
	{
/*
		// lock out the wait thread and cancel operations
		if (ClearGIBPending())
		{
*/
		//
		pMAINFRAME->SetStatusText("GIB cancelled.");
		//
		TerminateProcess(hGIBProcess, 0);
		TerminateThread(hWaitThread, 0);
		// wait for the read thread to end
		WaitForSingleObject(hWaitThread, INFINITE);
		// close the wait thread handle
		CloseHandle(hWaitThread);
		CloseHandle(hGIBProcess);
		// and delete the thread object
		delete pWaitThread;
		// close pipe handles 
		SafeCloseHandle(m_hChildStdinWr);
		SafeCloseHandle(m_hChildStdoutRd);
		// and throw an exception
		throw CGIBException();
//		}
	}

/*
	// set up events
	HANDLE eventArray[2];
	eventArray[0] = m_hEventCancel;
	eventArray[1] = pWaitThread->m_hThread;

	//
	// then sit back and wait for the thread(s)
	//
	for(;;)
	{
		// wait for the cancelled or finished messages
		DWORD nCode = WaitForMultipleObjects(2,				// 2 events to wait for
											 eventArray,	// events array
											 FALSE,			// not all at once
											 INFINITE);		// wait 4-ever
		//
		if (nCode == WAIT_FAILED)
		{
			ASSERT(FALSE);
			break;
		}
		else if (nCode == WAIT_OBJECT_0) 
		{
			// got the cancel message, so kill GIB & the wait thread
			// the following is very dangersous --
			// so kids, don't try this at home
			TerminateThread(pWaitThread, 0);
			TerminateProcess(hGIBProcess, 0);
			return GIB_CANCEL;
		}
		else if (nCode == WAIT_OBJECT_0 + 1)
		{
			// GIB finished message
			// signal the GIB monitor that GIB has finished
			SetEvent(m_hEventFinished);
			break;
		}
	}

*/

	//
	//------------------------------------------------------------
	//
	// presumably, GIB has finished running
	//

	// wait for the GIB thread to exit, then get the card code
	DWORD nCardPlayed, nErrorCode;
	bCode = WaitForSingleObject(hWaitThread, INFINITE);
	bCode = GetExitCodeThread(hWaitThread, &nCardPlayed);
	if (!bCode)
		nErrorCode = GetLastError();

	// close the wait thread handle
	CloseHandle(hWaitThread);

	// delete the temporary file
	DeleteFile(strTempFile);
 
	// and kill the child process
	// first send a Ctrl-C to the app 
	// (this doesn't seem to do anything)
	CString strInput = "\03";	// Ctrl-C
	if (!WriteFile(m_hChildStdinWr, (LPCTSTR)strInput, strInput.GetLength(), &dwWritten, NULL)) 
	{
		CString strError = "Error stopping GIB"; 
		TRACE(strError); 
		pMAINFRAME->SetGIBMonitorText(strError);
		nErrCode = GetLastError();
		return ExitGracefully(-4);
	}

	// close the writable handle to the child's stdin
	SafeCloseHandle(m_hChildStdinWr);

	// then call terminateProcess
	TerminateProcess(hGIBProcess, 0);
	CloseHandle(hGIBProcess);

	// then close the readable handle to the child's stdout
	SafeCloseHandle(m_hChildStdoutRd);

	//
	// done
	//
	return nCardPlayed; 
} 
Ejemplo n.º 29
0
bool CZipManager::GetZipList(const CURL& url, vector<SZipEntry>& items)
{
  CLog::Log(LOGDEBUG, "%s - Processing %s", __FUNCTION__, url.GetRedacted().c_str());

  struct __stat64 m_StatData = {};

  CStdString strFile = url.GetHostName();

  if (CFile::Stat(strFile,&m_StatData))
  {
    CLog::Log(LOGDEBUG,"CZipManager::GetZipList: failed to stat file %s", url.GetRedacted().c_str());
    return false;
  }

  map<CStdString,vector<SZipEntry> >::iterator it = mZipMap.find(strFile);
  if (it != mZipMap.end()) // already listed, just return it if not changed, else release and reread
  {
    map<CStdString,int64_t>::iterator it2=mZipDate.find(strFile);
    CLog::Log(LOGDEBUG,"statdata: %" PRId64" new: %" PRIu64, it2->second, (uint64_t)m_StatData.st_mtime);

      if (m_StatData.st_mtime == it2->second)
      {
        items = it->second;
        return true;
      }
      mZipMap.erase(it);
      mZipDate.erase(it2);
  }

  CFile mFile;
  if (!mFile.Open(strFile))
  {
    CLog::Log(LOGDEBUG,"ZipManager: unable to open file %s!",strFile.c_str());
    return false;
  }

  unsigned int hdr;
  mFile.Read(&hdr, 4);
  if( Endian_SwapLE32(hdr) != ZIP_LOCAL_HEADER )
  {
    CLog::Log(LOGDEBUG,"ZipManager: not a zip file!");
    mFile.Close();
    return false;
  }
  // push date for update detection
  mZipDate.insert(make_pair(strFile,m_StatData.st_mtime));


  // Look for end of central directory record
  // Zipfile comment may be up to 65535 bytes
  // End of central directory record is 22 bytes (ECDREC_SIZE)
  // -> need to check the last 65557 bytes
  int64_t fileSize = mFile.GetLength();
  // Don't need to look in the last 18 bytes (ECDREC_SIZE-4)
  // But as we need to do overlapping between blocks (3 bytes),
  // we start the search at ECDREC_SIZE-1 from the end of file
  int searchSize = (int) min(65557, fileSize-ECDREC_SIZE+1);
  int blockSize = (int) min(1024, searchSize);
  int nbBlock = searchSize / blockSize;
  int extraBlockSize = searchSize % blockSize;
  // Signature is on 4 bytes
  // It could be between 2 blocks, so we need to read 3 extra bytes
  char *buffer = new char[blockSize+3];
  bool found = false;

  // Loop through blocks starting at the end of the file (minus ECDREC_SIZE-1)
  for (int nb=1; !found && (nb <= nbBlock); nb++)
  {
    mFile.Seek(fileSize-ECDREC_SIZE+1-(blockSize*nb),SEEK_SET);
    mFile.Read(buffer,blockSize+3);
    for (int i=blockSize-1; !found && (i >= 0); i--)
    {
      if ( Endian_SwapLE32(*((unsigned int*)(buffer+i))) == ZIP_END_CENTRAL_HEADER )
      {
        // Set current position to start of end of central directory
        mFile.Seek(fileSize-ECDREC_SIZE+1-(blockSize*nb)+i,SEEK_SET);
        found = true;
      }
    }
  }

  // If not found, look in the last block left...
  if ( !found && (extraBlockSize > 0) )
  {
    mFile.Seek(fileSize-ECDREC_SIZE+1-searchSize,SEEK_SET);
    mFile.Read(buffer,extraBlockSize+3);
    for (int i=extraBlockSize-1; !found && (i >= 0); i--)
    {
      if ( Endian_SwapLE32(*((unsigned int*)(buffer+i))) == ZIP_END_CENTRAL_HEADER )
      {
        // Set current position to start of end of central directory
        mFile.Seek(fileSize-ECDREC_SIZE+1-searchSize+i,SEEK_SET);
        found = true;
      }
    }
  }

  delete [] buffer;

  if ( !found )
  {
    CLog::Log(LOGDEBUG,"ZipManager: broken file %s!",strFile.c_str());
    mFile.Close();
    return false;
  }

  unsigned int cdirOffset, cdirSize;
  // Get size of the central directory
  mFile.Seek(12,SEEK_CUR);
  mFile.Read(&cdirSize,4);
  cdirSize = Endian_SwapLE32(cdirSize);
  // Get Offset of start of central directory with respect to the starting disk number
  mFile.Read(&cdirOffset,4);
  cdirOffset = Endian_SwapLE32(cdirOffset);

  // Go to the start of central directory
  mFile.Seek(cdirOffset,SEEK_SET);

  char temp[CHDR_SIZE];
  while (mFile.GetPosition() < cdirOffset + cdirSize)
  {
    SZipEntry ze;
    mFile.Read(temp,CHDR_SIZE);
    readCHeader(temp, ze);
    if (ze.header != ZIP_CENTRAL_HEADER)
    {
      CLog::Log(LOGDEBUG,"ZipManager: broken file %s!",strFile.c_str());
      mFile.Close();
      return false;
    }

    // Get the filename just after the central file header
    CStdString strName;
    mFile.Read(strName.GetBuffer(ze.flength), ze.flength);
    strName.ReleaseBuffer();
    g_charsetConverter.unknownToUTF8(strName);
    ZeroMemory(ze.name, 255);
    strncpy(ze.name, strName.c_str(), strName.size()>254 ? 254 : strName.size());

    // Jump after central file header extra field and file comment
    mFile.Seek(ze.eclength + ze.clength,SEEK_CUR);

    items.push_back(ze);
  }

  /* go through list and figure out file header lengths */
  for(vector<SZipEntry>::iterator it = items.begin(); it != items.end(); ++it)
  {
    SZipEntry& ze = *it;
    // Go to the local file header to get the extra field length
    // !! local header extra field length != central file header extra field length !!
    mFile.Seek(ze.lhdrOffset+28,SEEK_SET);
    mFile.Read(&(ze.elength),2);
    ze.elength = Endian_SwapLE16(ze.elength);

    // Compressed data offset = local header offset + size of local header + filename length + local file header extra field length
    ze.offset = ze.lhdrOffset + LHDR_SIZE + ze.flength + ze.elength;

  }

  mZipMap.insert(make_pair(strFile,items));
  mFile.Close();
  return true;
}
Ejemplo n.º 30
0
float	dogetfloat(CFile f)
{
	float	x;
	f.Read(&x, sizeof(x));
	return x;
}