Exemple #1
0
/* This function returns FALSE if the destination is not free. */
BOOL RelocateCluster(RDWRHandle handle, CLUSTER source, CLUSTER destination)
{
   int labelsize, value;
   CLUSTER fatpos=0, freecluster, dircluster, label;
   struct DirectoryPosition dirpos;
   struct DirectoryEntry entry;
   BOOL IsInFAT = FALSE;
   SECTOR srcsector, destsector;
   unsigned long sectorspercluster;
   CLUSTER clustervalue;
   BOOL found, DOTSprocessed=FALSE;
   struct FSInfoStruct FSInfo;

   if (!FatReferedMap)
   {
	if (!CreateFatReferedMap(handle))
	    return FALSE;
   }

   /* See wether the destination is actually free. */
   if (!GetNthCluster(handle, destination, &label))
      RETURN_FTEERROR(FALSE);
   if (!FAT_FREE(label)) 
      RETURN_FTEERROR(FALSE);
   
   /* Do some preliminary calculations. */
   srcsector = ConvertToDataSector(handle, source);
   if (!srcsector)
      RETURN_FTEERROR(FALSE);
   destsector = ConvertToDataSector(handle, destination);
   if (!destsector)
      RETURN_FTEERROR(FALSE);
   sectorspercluster = GetSectorsPerCluster(handle);
   if (!sectorspercluster)
      RETURN_FTEERROR(FALSE);
         
   /* Get the value that is stored at the source position in the FAT */
   if (!ReadFatLabel(handle, source, &clustervalue))
      RETURN_FTEERROR(FALSE);
   
   /* See where the cluster is refered */
   if (!GetVFSBitfieldBit(FatReferedMap, source, &value))
      return FALSE;

   if (value)
   {//CLUSTER fatpos1;

	if (!FindClusterInFAT(handle, source, &fatpos))
	    RETURN_FTEERROR(FALSE);
/*
        if (!FindClusterInFAT1(handle, source, &fatpos1))
            RETURN_FTEERROR(FALSE);

        if (fatpos != fatpos1)
            printf("hola");
*/
   }
      
   if (!fatpos)
   {
      if (!FindClusterInDirectories(handle, source, &dirpos, &found))
         RETURN_FTEERROR(FALSE);
      if (!found)
      {
          /* Note: on FAT32 this cluster may be pointing to the root directory.
                   We do not support relocating the root cluster at this time.          
          */
          
          
          RETURN_FTEERROR(FALSE);                /* Non valid cluster! */
      }
      else
      {
         /*
            This is the first cluster of some file. See if it is a directory
            and if it is, adjust the '.' entry of this directory and all
            of the '..' entries of all the (direct) subdirectories to point
            to the new cluster.
         */
         if (!GetDirectory(handle, &dirpos, &entry))
            RETURN_FTEERROR(FALSE);
            
         if (entry.attribute & FA_DIREC)
         {
            dircluster = GetFirstCluster(&entry);
            if (!AdaptCurrentAndPreviousDirs(handle, dircluster, destination))
            {
               RETURN_FTEERROR(FALSE);
            }
            DOTSprocessed = TRUE;
         }
      }
   }
   else
   {
      IsInFAT = TRUE;
   }

   /* Copy all sectors in this cluster to the new position */
   if (!CopySectors(handle, srcsector, destsector, sectorspercluster))
   {
      if (DOTSprocessed)
         AdaptCurrentAndPreviousDirs(handle, dircluster, source);
      RETURN_FTEERROR(FALSE);
   }
   
   /* Write the entry in the FAT */
   if (!WriteFatReference(handle, destination, clustervalue))
   {
      if (DOTSprocessed)
         AdaptCurrentAndPreviousDirs(handle, dircluster, source);
      RETURN_FTEERROR(FALSE);
   }

   if (!WriteFatLabel(handle, destination, clustervalue))
   {
      if (DOTSprocessed)
         AdaptCurrentAndPreviousDirs(handle, dircluster, source);
      RETURN_FTEERROR(FALSE);
   }

   /* Adjust the pointer to the relocated cluster */
   if (IsInFAT)
   {
      if (!WriteFatReference(handle, fatpos, destination))
      {
         RETURN_FTEERROR(FALSE);
      }

      if (!WriteFatLabel(handle, fatpos, destination))
      {
         RETURN_FTEERROR(FALSE);
      }

      if (!ClearVFSBitfieldBit(FatReferedMap, source))
	  return FALSE;
      if (!SetVFSBitfieldBit(FatReferedMap, destination))
	  return FALSE;
      //if (!IndicateFatClusterMoved(fatpos, source, destination))
      //   return FALSE;
   }
   else
   {
      CLUSTER label;

      if (!GetDirectory(handle, &dirpos, &entry))
      {
         if (DOTSprocessed)
            AdaptCurrentAndPreviousDirs(handle, dircluster, source);
      
         RETURN_FTEERROR(FALSE);
      }
      
      SetFirstCluster(destination, &entry);
      if (!WriteDirectory(handle, &dirpos, &entry))
      {
         if (DOTSprocessed)
            AdaptCurrentAndPreviousDirs(handle, dircluster, source);
      
         RETURN_FTEERROR(FALSE);
      }

      if (!IndicateDirEntryMoved(source, destination))
	  return FALSE;

     if (!GetNthCluster(handle, source, &label))
         return FALSE;

     //if (!IndicateFatClusterMoved(label, source, destination))
     //   return FALSE;
   }

   if (!WriteFatReference(handle, source, FAT_FREE_LABEL))
   {
      if (DOTSprocessed)
         AdaptCurrentAndPreviousDirs(handle, dircluster, source);
   
      RETURN_FTEERROR(FALSE);
   }

   if (!WriteFatLabel(handle, source, FAT_FREE_LABEL))
   {
      if (DOTSprocessed)
         AdaptCurrentAndPreviousDirs(handle, dircluster, source);
   
      RETURN_FTEERROR(FALSE);
   }

   if (!IndicateDirClusterMoved(handle, source, destination))
      RETURN_FTEERROR(FALSE);
      
   /* Adjust FSInfo on FAT32 */
   labelsize = GetFatLabelSize(handle);
   if (labelsize == FAT32)
   {
      if (!GetFreeClusterSearchStart(handle, &freecluster))
         RETURN_FTEERROR(FALSE);
         
      if (source < freecluster) /* source cluster became available */
      {
         if (!ReadFSInfo(handle, &FSInfo))
            RETURN_FTEERROR(FALSE);
    
         WriteFreeClusterStart(&FSInfo, source);
    
         if (!WriteFSInfo(handle, &FSInfo))
            RETURN_FTEERROR(FALSE);          
      }
      
      if ((freecluster == destination) && /* We are relocating to the first */
	  (destination < source))         /* free cluster */
      {
         CLUSTER dummy;     
 
         if (!FindFirstFreeSpace(handle, &dummy, &dummy))
            RETURN_FTEERROR(FALSE);
      }
   }
   
   return TRUE;
}
Exemple #2
0
void CMatch::UnitTests()
{
	CEStr szDir;
	GetDirectory(szDir);

	CMatch match(NULL);
	struct TestMatch {
		LPCWSTR src; ExpandTextRangeType etr;
		bool bMatch; LPCWSTR matches[5];
		LPCWSTR pszTestCurDir;
	} Tests[] = {
		// Hyperlinks
		// RA layer request failed: PROPFIND request failed on '/svn': PROPFIND of '/svn': could
		// not connect to server (http://farmanager.googlecode.com) at /usr/lib/perl5/site_perl/Git/SVN.pm line 148
		// 1. Must not match last bracket, dot, comma, semicolon, etc.
		// 2. If url exceeds the line, must request from owner additional data
		//    if it is Far editor - the line must match the screen (no "tab" chars)
		{L"\t" L"(http://abc.com) <http://qwe.com> [http://rty.com] {http://def.com}" L"\t",
			etr_AnyClickable, true, {L"http://abc.com", L"http://qwe.com", L"http://rty.com", L"http://def.com"}},
		{L"\t" L"(http://abc.com) http://qwe.com; http://rty.com, http://def.com." L"\t",
			etr_AnyClickable, true, {L"http://abc.com", L"http://qwe.com", L"http://rty.com", L"http://def.com"}},
		{L"\t" L"text··http://www.abc.com/q?q··text" L"\t", // this line contains '·' which are visualisations of spaces in Far editor
			etr_AnyClickable, true, {L"http://www.abc.com/q?q"}},
		{L"\t" L"file://*****:*****@assembler.d(1239): test.asasm(1,1):" L"\t",
			etr_AnyClickable, true, {L"[email protected](1239)", L"test.asasm(1,1)"}},
		// Issue 1594
		{L"\t" L"/src/class.c:123:m_func(...)" L"\t",
			etr_AnyClickable, true, {L"/src/class.c:123"}},
		{L"\t" L"/src/class.c:123: m_func(...)" L"\t",
			etr_AnyClickable, true, {L"/src/class.c:123"}},

		// -- False detects
		{L"\t" L"29.11.2011 18:31:47" L"\t",
			etr_AnyClickable, false, {}},
		{L"\t" L"C:\\VC\\unicode_far\\macro.cpp  1251 Ln 5951/8291 Col 51 Ch 39 0043h 13:54" L"\t",
			etr_AnyClickable, true, {L"C:\\VC\\unicode_far\\macro.cpp"}},
		{L"\t" L"InfoW1900->SettingsControl(sc.Handle, SCTL_FREE, 0, 0);" L"\t",
			etr_AnyClickable, false, {}},
		{L"\t" L"m_abc.func(1,2,3)" L"\t",
			etr_AnyClickable, false, {}},
		{NULL}
	};

	for (INT_PTR i = 0; Tests[i].src; i++)
	{
		INT_PTR nStartIdx;
		int iSrcLen = lstrlen(Tests[i].src) - 1;
		_ASSERTE(Tests[i].src && Tests[i].src[iSrcLen] == L'\t');

		// Loop through matches
		int iMatchNo = 0, iPrevStart = 0;
		while (true)
		{
			if (Tests[i].bMatch)
			{
				int iMatchLen = lstrlen(Tests[i].matches[iMatchNo]);
				LPCWSTR pszFirst = wcsstr(Tests[i].src, Tests[i].matches[iMatchNo]);
				_ASSERTE(pszFirst);
				nStartIdx = (pszFirst - Tests[i].src);

				match.UnitTestNoMatch(Tests[i].etr, Tests[i].src, iSrcLen, iPrevStart, nStartIdx-1);
				iPrevStart = nStartIdx+iMatchLen;
				match.UnitTestMatch(Tests[i].etr, Tests[i].src, iSrcLen, nStartIdx, iPrevStart-1, Tests[i].matches[iMatchNo]);
			}
			else
			{
				nStartIdx = 0;
				match.UnitTestNoMatch(Tests[i].etr, Tests[i].src, iSrcLen, 0, iSrcLen);
				break;
			}

			// More matches waiting?
			if (Tests[i].matches[++iMatchNo] == NULL)
			{
				match.UnitTestNoMatch(Tests[i].etr, Tests[i].src, iSrcLen, iPrevStart, iSrcLen);
				break;
			}
		}
		//_ASSERTE(iRc == lstrlen(p->txtMatch));
		//_ASSERTE(match.m_Type == p->etrMatch);
	}

	::SetCurrentDirectoryW(szDir);
}
Exemple #3
0
/*******************************************************************************
          Name:        FileSelect
          Description: Pops up window in center of the Dialog Window for file
                       selection by user
          Arguments:  None
          Returns:     None
          Contrubuting Programmers:  Albert Leigh - MacDonnell Douglas
                                     Stan Smith - Barrios
                                     some guy upstairs
******************************************************************************/
void FileSelect()
  {
  Widget file_form, file_dialog, view;
    

  /*XDefineCursor(XtDisplay(toplevel),toplevel,XC_watch);*/
  file = XtCreatePopupShell("File",
                            topLevelShellWidgetClass,
                            toplevel,
                            NULL, 0);

  file_form = XtCreateManagedWidget("file_form",
                                    formWidgetClass,
                                    file,
                                    NULL, 0);

  XtSetArg(args[0], XtNforceBars, True);
  XtSetArg(args[1], XtNbottom, XtChainBottom);
  XtSetArg(args[2], XtNheight,150);
  XtSetArg(args[3], XtNallowHoriz,True);
  XtSetArg(args[4],XtNallowVert,True);
  view = XtCreateManagedWidget("view",
                               viewportWidgetClass,
                               file_form,
                               args, 5);

  /* =============================================================== *
   *  Create the Select/Cancel dialog box in the file selection      *
   *  dialog box.                                                    *
   * =============================================================== */

  XtSetArg(args[0], XtNresizable, True);
  XtSetArg(args[1], XtNlabel, "Enter File Name");
  XtSetArg(args[2], XtNvalue, "");
  XtSetArg(args[3], XtNfromVert, view);
  XtSetArg(args[4], XtNicon, clips_logo);
  XtSetArg(args[5], XtNleft, XtChainLeft);
  XtSetArg(args[6], XtNright, XtChainRight);
  XtSetArg(args[7], XtNtop, XtChainBottom);
  XtSetArg(args[8], XtNbottom, XtChainBottom);
  file_dialog = XtCreateManagedWidget("file_dialog",
                                      dialogWidgetClass,
                                      file_form,
                                      args, 9);
  XawDialogAddButton(file_dialog, "SELECT", MenuFunc, (XtPointer) file_dialog);
  XawDialogAddButton(file_dialog, "CANCEL", CancelPopupSelect,
                     (XtPointer) file_form);

  XtSetArg(args[0], XtNfromHoriz, file_dialog);
  XtSetArg(args[1], XtNfromVert, view);

  /* =============================================================== *
   *  Get the path of the current dirrectory                         *
   * =============================================================== */

  if(getwd(path) == NULL)
    printf("Error getting current working directory '%s'\n", path);

  if(path[strlen(path) - 1] != '/')
    strcat(path, "/");

  /* =============================================================== *
   *  Create the file dialog list box                                *
   * =============================================================== */

  XtSetArg(args[0], XtNdefaultColumns, 4);
  XtSetArg(args[1], XtNlist, GetDirectory());
  XtSetArg(args[2], XtNforceColumns, False);
  XtSetArg(args[3], XtNverticalList, True);
  XtSetArg(args[4], XtNinternalWidth, 10);
  file_list = XtCreateManagedWidget("file_dialog",
                                    listWidgetClass,
                                    view,
                                    args, 5);
  XtAddCallback(file_list, XtNcallback, FileToDialog, (XtPointer) file_dialog);

  XtPopup(file, XtGrabNonexclusive);
  /*XDefineCursor(XtDisplay(toplevel),toplevel,None);*/
  }
Exemple #4
0
BOOL WalkDirectoryTree(RDWRHandle handle,
		      int (*func) (RDWRHandle handle,
				   struct DirectoryPosition* position,
				   void** structure),
		      void** structure)
{
    int top = 0;
    struct StackElement* stack;
    CLUSTER cluster = 0, temp;
    unsigned long current = 0;
    struct DirectoryPosition pos;
    struct DirectoryEntry* entry;
    struct StackElement element;
        
    struct PipeStruct pipe, *ppipe = &pipe;

    pipe.func      = func;
    pipe.structure = structure;
    pipe.stop      = FALSE;

    if (!TraverseRootDir(handle, ActionWalker, (void**)&ppipe, TRUE))
       return FALSE;
    if (pipe.stop)
       return TRUE;

    stack = (struct StackElement*)FTEAlloc(DIR_STACK_DEPTH * sizeof(struct StackElement));
    if (!stack)
       return FALSE;

    for (;;)
    {
         /* If there still are sub directories in this directory, 
            push the cluster of that directory. */
         pos.sector = 0;
         pos.offset = 0;
         if (!GetNthSubDirectoryPosition(handle, cluster, current, &pos))
	 {
            FTEFree(stack);
            return FALSE;
         }

	 if ((pos.sector != 0) || (pos.offset != 0))
	 {
	    entry = AllocateDirectoryEntry();
	    if (!entry)
	    {
	       FTEFree(stack);
	       return FALSE;
	    }

	    if (top < DIR_STACK_DEPTH)
	    {
	       element.cluster = cluster;
	       element.index   = current;

	       PushDirectoryEntry(stack, &top, &element);
	    }
	    else
	    {
	       FreeDirectoryEntry(entry);   /* Directory level to deep!? */
	       FTEFree(stack);
	       return FALSE;
	    }

	    if (!GetDirectory(handle, &pos, entry))
	    {
	       FreeDirectoryEntry(entry);
	       FTEFree(stack);
	       return FALSE;
	    }

	    /* Descend in the directory tree and call the function
               for every directory entry in that directory. */
            temp = GetFirstCluster(entry);
            
            /* Don't descend in any directory that is invalid. */
            if (temp && FAT_NORMAL(temp) && IsLabelValid(handle, temp))
            {
	       current = 0;
               cluster = temp;

	       if (!TraverseSubdir(handle, cluster, ActionWalker, (void**) &ppipe, TRUE))
	       {
	          FreeDirectoryEntry(entry);
	          FTEFree(stack);
                  return FALSE;
	       }

	       if (pipe.stop)
	       {
	          FreeDirectoryEntry(entry);
                  FTEFree(stack);
	          return TRUE;
	       }
            }
            else /* cluster not valid, leave this directory */
            {   
	       if (top-1 > 0) /* Be carefull when there are no sub directories
		                 in the volume. */
	       {
	          PopDirectoryEntry(stack, &top, &element);
                  PopDirectoryEntry(stack, &top, &element);

	          current = element.index+1; /* Then find the next sub directory. */
	          cluster = element.cluster;
	       }
	       else
	       {
                  FreeDirectoryEntry(entry);     
	          break;
	       }
            }
            
	    FreeDirectoryEntry(entry);
	 }
	 /* If there are no more sub directories in the current directory,
	    pop the current directory from the stack.                 */
	 else
	 {
	    if (top) /* Be carefull when there are no sub directories
			in the volume. */
	    {
	       PopDirectoryEntry(stack, &top, &element);

	       current = element.index+1; /* Then find the next sub directory. */
	       cluster = element.cluster;
	    }
	    else
	    {
	       break;
	    }
         }
    }

    FTEFree(stack);        
    return TRUE;
}
Exemple #5
0
void Matchmaker::GetTitanServerList()
{
#ifdef DLLSAMPLE
	mNewAuthServers.clear();
	mNewContestServers.clear();
	mNewEventServers.clear();
	mNewFirewallServers.clear();
	mNewProfileServers.clear();
	
	HWONDATAOBJECT aDataObjectH = WONDataObjectCreate(OBJ_VALIDVERSIONS.c_str(), OBJ_VALIDVERSIONS.size(), NULL, 0);
	WONError aError = WONDirGetDirectoryW(NULL, mDirServers, mNumDirServers,
	                                      DIR_TITANSERVER, NULL, NULL,
	                                      WONDir_GF_DECOMPROOT | WONDir_GF_DECOMPRECURSIVE | WONDir_GF_DECOMPSERVICES | WONDir_GF_ADDTYPE | WONDir_GF_SERVADDNAME | WONDir_GF_SERVADDNETADDR | WONDir_GF_ADDDOTYPE | WONDir_GF_ADDDODATA,
	                                      &aDataObjectH, 1, TitanServerEntityCallback, this, gRequestTimeout);

	CopySTLAddressListToArray(mNewAuthServers,     &mAuthServers,     &mNumAuthServers);
	CopySTLAddressListToArray(mNewContestServers,  &mContestServers,  &mNumContestServers);
	CopySTLAddressListToArray(mNewEventServers,    &mEventServers,    &mNumEventServers);
	CopySTLAddressListToArray(mNewFirewallServers, &mFirewallServers, &mNumFirewallServers);
	CopySTLAddressListToArray(mNewProfileServers,  &mProfileServers,  &mNumProfileServers);
#else
	DataObjectTypeSet aDataObjectSet;
	aDataObjectSet.insert(WONCommon::DataObject(OBJ_VALIDVERSIONS));
	WONMsg::DirEntityList entityList;
	Error aError = GetDirectory(NULL, // no identity needed to get TitanServers (after all, the AuthServers are listed in there)
								mDirServers, mNumDirServers,
								NULL,
								DIR_TITANSERVER, 
								&entityList,
								WONMsg::GF_DECOMPROOT | WONMsg::GF_DECOMPRECURSIVE | WONMsg::GF_DECOMPSERVICES | WONMsg::GF_ADDTYPE | WONMsg::GF_SERVADDNAME | WONMsg::GF_SERVADDNETADDR | WONMsg::GF_ADDDOTYPE | WONMsg::GF_ADDDODATA,
								aDataObjectSet,
								0, 0,
								gRequestTimeout);

	switch(aError) 
	{
		case Error_Success:
		{
			delete[] mAuthServers; mNumAuthServers = 0;
			mAuthServers = new IPSocket::Address[entityList.size()];
			delete[] mContestServers; mNumContestServers = 0;
			mContestServers = new IPSocket::Address[entityList.size()];
			delete[] mEventServers; mNumEventServers = 0;
			mEventServers = new IPSocket::Address[entityList.size()];
			delete[] mFirewallServers; mNumFirewallServers = 0;
			mFirewallServers = new IPSocket::Address[entityList.size()];
			delete[] mProfileServers; mNumProfileServers = 0;
			mProfileServers = new IPSocket::Address[entityList.size()];

			DirEntityList::const_iterator aDirEntityListItr = entityList.begin();
			for( ; aDirEntityListItr != entityList.end(); ++aDirEntityListItr)
			{
				if (aDirEntityListItr->mType == WONMsg::DirEntity::ET_DIRECTORY)
				{
					DataObjectTypeSet::const_iterator aDataObjectSetItr = aDirEntityListItr->mDataObjects.begin();
					for( ; aDataObjectSetItr != aDirEntityListItr->mDataObjects.end(); ++aDataObjectSetItr)
					{
						if (aDataObjectSetItr->GetDataType() == OBJ_VALIDVERSIONS)
							mValidVersions = reinterpret_cast<const char*>(aDataObjectSetItr->GetData().c_str());
					}
				}
				else if (aDirEntityListItr->mName == SERVERNAME_AUTH)
					mAuthServers[mNumAuthServers++] = IPSocket::Address(*aDirEntityListItr);
				else if (aDirEntityListItr->mName == SERVERNAME_CONTEST)
					mContestServers[mNumContestServers++] = IPSocket::Address(*aDirEntityListItr);
				else if (aDirEntityListItr->mName == SERVERNAME_EVENT)
					mEventServers[mNumEventServers++] = IPSocket::Address(*aDirEntityListItr);
				else if (aDirEntityListItr->mName == SERVERNAME_FIREWALL)
					mFirewallServers[mNumFirewallServers++] = IPSocket::Address(*aDirEntityListItr);
				else if (aDirEntityListItr->mName == SERVERNAME_PROFILE)
					mProfileServers[mNumProfileServers++] = IPSocket::Address(*aDirEntityListItr);
			}
			break;
		}

		case StatusDir_DirNotFound:
			OutputError("Directory containing Titan servers not found");
			break;
		default:
			OutputError("Failed to get list of Titan servers!", aError);
			break;
	}
#endif // DLLSAMPLE
}
Exemple #6
0
bool CVirtualDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
  return GetDirectory(strPath,items,true);
}
bool LEVELSELECT::PrevDirectoryAvailable()
{
    return (GetDirectory() != NULL && GetDirectory()->prev != NULL);
}
Exemple #8
0
void CModelConverter::SaveOBJ(const tstring& sFilename)
{
	tstring sMaterialFileName = tstring(GetDirectory(sFilename).c_str()) + _T("/") + GetFilename(sFilename).c_str() + _T(".mtl");

	std::wofstream sMaterialFile(convertstring<tchar, char>(sMaterialFileName).c_str());
	if (!sMaterialFile.is_open())
		return;

	if (m_pWorkListener)
	{
		m_pWorkListener->BeginProgress();
		m_pWorkListener->SetAction(_T("Writing materials file"), 0);
	}

	for (size_t i = 0; i < m_pScene->GetNumMaterials(); i++)
	{
		CConversionMaterial* pMaterial = m_pScene->GetMaterial(i);
		sMaterialFile << "newmtl " << pMaterial->GetName().c_str() << std::endl;
		sMaterialFile << "Ka " << pMaterial->m_vecAmbient.x << _T(" ") << pMaterial->m_vecAmbient.y << _T(" ") << pMaterial->m_vecAmbient.z << std::endl;
		sMaterialFile << "Kd " << pMaterial->m_vecDiffuse.x << _T(" ") << pMaterial->m_vecDiffuse.y << _T(" ") << pMaterial->m_vecDiffuse.z << std::endl;
		sMaterialFile << "Ks " << pMaterial->m_vecSpecular.x << _T(" ") << pMaterial->m_vecSpecular.y << _T(" ") << pMaterial->m_vecSpecular.z << std::endl;
		sMaterialFile << "d " << pMaterial->m_flTransparency << std::endl;
		sMaterialFile << "Ns " << pMaterial->m_flShininess << std::endl;
		sMaterialFile << "illum " << pMaterial->m_eIllumType << std::endl;
		if (pMaterial->GetDiffuseTexture().length() > 0)
			sMaterialFile << "map_Kd " << pMaterial->GetDiffuseTexture().c_str() << std::endl;
		sMaterialFile << std::endl;
	}

	sMaterialFile.close();

	for (size_t i = 0; i < m_pScene->GetNumMeshes(); i++)
	{
		CConversionMesh* pMesh = m_pScene->GetMesh(i);

		// Find the default scene for this mesh.
		CConversionSceneNode* pScene = NULL;
		for (size_t j = 0; j < m_pScene->GetNumScenes(); j++)
		{
			if (m_pScene->GetScene(j)->GetName() == pMesh->GetName() + _T(".obj"))
			{
				pScene = m_pScene->GetScene(j);
				break;
			}
		}

		tstring sNodeName = pMesh->GetName();

		tstring sOBJFilename = tstring(GetDirectory(sFilename).c_str()) + _T("/") + GetFilename(sNodeName).c_str() + _T(".obj");
		tstring sMTLFilename = tstring(GetFilename(sFilename).c_str()) + _T(".mtl");

		if (m_pScene->GetNumMeshes() == 1)
			sOBJFilename = sFilename;

		std::wofstream sOBJFile(convertstring<tchar, char>(sOBJFilename).c_str());
		sOBJFile.precision(8);
		sOBJFile.setf(std::ios::fixed, std::ios::floatfield);

		sOBJFile << _T("mtllib ") << sMTLFilename.c_str() << std::endl;
		sOBJFile << std::endl;

		sOBJFile << _T("o ") << sNodeName.c_str() << std::endl;

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" vertices...")).c_str(), pMesh->GetNumVertices());

		for (size_t iVertices = 0; iVertices < pMesh->GetNumVertices(); iVertices++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iVertices);

			Vector vecVertex = pMesh->GetVertex(iVertices);
			sOBJFile << _T("v ") << vecVertex.x << _T(" ") << vecVertex.y << _T(" ") << vecVertex.z << std::endl;
		}

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" normals...")).c_str(), pMesh->GetNumNormals());

		for (size_t iNormals = 0; iNormals < pMesh->GetNumNormals(); iNormals++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iNormals);

			Vector vecNormal = pMesh->GetNormal(iNormals);
			sOBJFile << _T("vn ") << vecNormal.x << _T(" ") << vecNormal.y << _T(" ") << vecNormal.z << std::endl;
		}

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" UVs...")).c_str(), pMesh->GetNumUVs());

		for (size_t iUVs = 0; iUVs < pMesh->GetNumUVs(); iUVs++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iUVs);

			Vector vecUV = pMesh->GetUV(iUVs);
			sOBJFile << _T("vt ") << vecUV.x << _T(" ") << vecUV.y << std::endl;
		}

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" faces...")).c_str(), pMesh->GetNumFaces());

		size_t iLastMaterial = ~0;

		for (size_t iFaces = 0; iFaces < pMesh->GetNumFaces(); iFaces++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iFaces);

			CConversionFace* pFace = pMesh->GetFace(iFaces);

			if (pFace->m != iLastMaterial)
			{
				iLastMaterial = pFace->m;

				CConversionSceneNode* pNode = m_pScene->GetDefaultSceneMeshInstance(pScene, pMesh, false);
				if (!pNode || pNode->GetNumMeshInstances() != 1)
					sOBJFile << "usemtl " << iLastMaterial << std::endl;
				else
				{
					CConversionMaterialMap* pMap = pNode->GetMeshInstance(0)->GetMappedMaterial(iLastMaterial);
					if (!pMap)
						sOBJFile << "usemtl " << iLastMaterial << std::endl;
					else
						sOBJFile << "usemtl " << m_pScene->GetMaterial(pMap->m_iMaterial)->GetName().c_str() << std::endl;
				}
			}

			sOBJFile << _T("f");
			for (size_t iVertsInFace = 0; iVertsInFace < pFace->GetNumVertices(); iVertsInFace++)
			{
				CConversionVertex* pVertex = pFace->GetVertex(iVertsInFace);
				sOBJFile << _T(" ") << pVertex->v+1 << _T("/") << pVertex->vu+1 << _T("/") << pVertex->vn+1;
			}
			sOBJFile << std::endl;
		}

		sOBJFile << std::endl;

		sOBJFile.close();
	}

	if (m_pWorkListener)
		m_pWorkListener->EndProgress();
}
Exemple #9
0
void CModelConverter::ReadOBJ(const tstring& sFilename)
{
	if (m_pWorkListener)
		m_pWorkListener->BeginProgress();

	FILE* fp = tfopen(sFilename, _T("r"));

	if (!fp)
	{
		printf("No input file. Sorry!\n");
		return;
	}

	CConversionSceneNode* pScene = m_pScene->GetScene(m_pScene->AddScene(GetFilename(sFilename).append(_T(".obj"))));

	CConversionMesh* pMesh = m_pScene->GetMesh(m_pScene->AddMesh(GetFilename(sFilename)));
	// Make sure it exists.
	CConversionSceneNode* pMeshNode = m_pScene->GetDefaultSceneMeshInstance(pScene, pMesh);

	size_t iCurrentMaterial = ~0;
	size_t iSmoothingGroup = ~0;

	bool bSmoothingGroups = false;

	tstring sLastTask;

	int iTotalVertices = 0;
	int iTotalFaces = 0;
	int iVerticesComplete = 0;
	int iFacesComplete = 0;

	if (m_pWorkListener)
		m_pWorkListener->SetAction(_T("Reading file into memory..."), 0);

	fseek(fp, 0L, SEEK_END);
	long iOBJSize = ftell(fp);
	fseek(fp, 0L, SEEK_SET);

	// Make sure we allocate more than we need just in case.
	size_t iFileSize = (iOBJSize+1) * (sizeof(tchar)+1);
	tchar* pszEntireFile = (tchar*)malloc(iFileSize);
	tchar* pszCurrent = pszEntireFile;
	pszCurrent[0] = _T('\0');

	// Read the entire file into an array first for faster processing.
	tstring sLine;
	while (fgetts(sLine, fp))
	{
		tstrncpy(pszCurrent, iFileSize-(pszCurrent-pszEntireFile), sLine.c_str(), sLine.length());
		size_t iLength = sLine.length();

		tchar cLastChar = pszCurrent[iLength-1];
		while (cLastChar == _T('\n') || cLastChar == _T('\r'))
		{
			pszCurrent[iLength-1] = _T('\0');
			iLength--;
			cLastChar = pszCurrent[iLength-1];
		}

		pszCurrent += iLength;
		pszCurrent++;

		if (m_pWorkListener)
			m_pWorkListener->WorkProgress(0);
	}

	pszCurrent[0] = _T('\0');

	fclose(fp);

	const tchar* pszLine = pszEntireFile;
	const tchar* pszNextLine = NULL;
	while (pszLine < pszCurrent)
	{
		if (pszNextLine)
			pszLine = pszNextLine;

		pszNextLine = pszLine + tstrlen(pszLine) + 1;

		// This code used to call StripWhitespace() but that's too slow for very large files w/ millions of lines.
		// Instead we'll just cut the whitespace off the front and deal with whitespace on the end when we come to it.
		while (*pszLine && IsWhitespace(*pszLine))
			pszLine++;

		if (tstrlen(pszLine) == 0)
			continue;

		if (pszLine[0] == '#')
		{
			// ZBrush is kind enough to notate exactly how many vertices and faces we have in the comments at the top of the file.
			if (tstrncmp(pszLine, _T("#Vertex Count"), 13) == 0)
			{
				iTotalVertices = stoi(pszLine+13);
				pMesh->SetTotalVertices(iTotalVertices);
			}

			if (tstrncmp(pszLine, _T("#Face Count"), 11) == 0)
			{
				iTotalFaces = stoi(pszLine+11);
				pMesh->SetTotalFaces(iTotalFaces);

				// Don't kill the video card while we're loading the faces.
				if (iTotalFaces > 10000)
					pMeshNode->GetMeshInstance(0)->SetVisible(false);
			}

			continue;
		}

		tchar szToken[1024];
		tstrncpy(szToken, 1024, pszLine, 1024);
		tchar* pszState = NULL;
		tchar* pszToken = strtok<tchar>(szToken, " ", &pszState);

		if (tstrncmp(pszToken, _T("mtllib"), 6) == 0)
		{
			tstring sDirectory = GetDirectory(sFilename);
			tstring sMaterial = sprintf(tstring("%s/%s"), sDirectory.c_str(), pszLine + 7);
			ReadMTL(sMaterial);
		}
		else if (tstrncmp(pszToken, _T("o"), 1) == 0)
		{
			// Dunno what this does.
		}
		else if (tstrncmp(pszToken, _T("v"), 2) == 0)
		{
			if (m_pWorkListener)
			{
				if (tstrncmp(sLastTask.c_str(), pszToken, sLastTask.length()) == 0)
					m_pWorkListener->WorkProgress(iVerticesComplete++);
				else
				{
					m_pWorkListener->SetAction(_T("Reading vertex data"), iTotalVertices);
					sLastTask = tstring(pszToken);
				}
			}

			// A vertex.
			float v[3];
			// scanf is pretty slow even for such a short string due to lots of mallocs.
			const tchar* pszToken = pszLine+1;
			int iDimension = 0;
			while (*pszToken)
			{
				while (pszToken[0] == _T(' '))
					pszToken++;

				v[iDimension++] = (float)stof(pszToken);
				if (iDimension >= 3)
					break;

				while (pszToken[0] != _T(' '))
					pszToken++;
			}
			pMesh->AddVertex(v[0], v[1], v[2]);
		}
		else if (tstrncmp(pszToken, _T("vn"), 3) == 0)
		{
			if (m_pWorkListener)
			{
				if (tstrncmp(sLastTask.c_str(), pszToken, sLastTask.length()) == 0)
					m_pWorkListener->WorkProgress(0);
				else
					m_pWorkListener->SetAction(_T("Reading vertex normal data"), 0);
			}
			sLastTask = tstring(pszToken);

			// A vertex normal.
			float x, y, z;
			eastl::vector<tstring> asTokens;
			tstrtok(pszLine, asTokens, _T(" "));
			if (asTokens.size() == 4)
			{
				x = stof(asTokens[1]);
				y = stof(asTokens[2]);
				z = stof(asTokens[3]);
				pMesh->AddNormal(x, y, z);
			}
		}
		else if (tstrncmp(pszToken, _T("vt"), 3) == 0)
		{
			if (m_pWorkListener)
			{
				if (tstrncmp(sLastTask.c_str(), pszToken, sLastTask.length()) == 0)
					m_pWorkListener->WorkProgress(0);
				else
					m_pWorkListener->SetAction(_T("Reading texture coordinate data"), 0);
			}
			sLastTask = tstring(pszToken);

			// A UV coordinate for a vertex.
			float u, v;
			eastl::vector<tstring> asTokens;
			tstrtok(pszLine, asTokens, _T(" "));
			if (asTokens.size() == 3)
			{
				u = stof(asTokens[1]);
				v = stof(asTokens[2]);
				pMesh->AddUV(u, v);
			}
		}
		else if (tstrncmp(pszToken, _T("g"), 1) == 0)
		{
			// A group of faces.
			pMesh->AddBone(pszLine+2);
		}
		else if (tstrncmp(pszToken, _T("usemtl"), 6) == 0)
		{
			// All following faces should use this material.
			tstring sMaterial = tstring(pszLine+7);
			size_t iMaterial = pMesh->FindMaterialStub(sMaterial);
			if (iMaterial == ((size_t)~0))
			{
				size_t iSceneMaterial = m_pScene->FindMaterial(sMaterial);
				if (iSceneMaterial == ((size_t)~0))
					iCurrentMaterial = m_pScene->AddDefaultSceneMaterial(pScene, pMesh, sMaterial);
				else
				{
					size_t iMaterialStub = pMesh->AddMaterialStub(sMaterial);
					m_pScene->GetDefaultSceneMeshInstance(pScene, pMesh)->GetMeshInstance(0)->AddMappedMaterial(iMaterialStub, iSceneMaterial);
					iCurrentMaterial = iMaterialStub;
				}
			}
			else
				iCurrentMaterial = iMaterial;
		}
		else if (tstrncmp(pszToken, _T("s"), 1) == 0)
		{
			if (tstrncmp(pszLine, _T("s off"), 5) == 0)
			{
				iSmoothingGroup = ~0;
			}
			else
			{
				bSmoothingGroups = true;
				eastl::vector<tstring> asTokens;
				tstrtok(pszLine, asTokens, _T(" "));
				if (asTokens.size() == 2)
					iSmoothingGroup = stoi(asTokens[1]);
			}
		}
		else if (tstrncmp(pszToken, _T("f"), 1) == 0)
		{
			if (m_pWorkListener)
			{
				if (tstrncmp(sLastTask.c_str(), pszToken, sLastTask.length()) == 0)
					m_pWorkListener->WorkProgress(iFacesComplete++);
				else
				{
					m_pWorkListener->SetAction(_T("Reading polygon data"), iTotalFaces);
					sLastTask = tstring(pszToken);
				}
			}

			if (iCurrentMaterial == ~0)
				iCurrentMaterial = m_pScene->AddDefaultSceneMaterial(pScene, pMesh, pMesh->GetName());

			// A face.
			size_t iFace = pMesh->AddFace(iCurrentMaterial);

			// If we get to 10k faces force the mesh off so it doesn't kill the video card.
			if (iFace == 10000)
				pMeshNode->GetMeshInstance(0)->SetVisible(false);

			pMesh->GetFace(iFace)->m_iSmoothingGroup = iSmoothingGroup;

			while (pszToken = strtok<tchar>(NULL, _T(" "), &pszState))
			{
				if (tstrlen(pszToken) == 0)
					continue;

				// We don't use size_t because SOME EXPORTS put out negative numbers.
				long f[3];
				bool bValues[3];
				bValues[0] = false;
				bValues[1] = false;
				bValues[2] = false;

				// scanf is pretty slow even for such a short string due to lots of mallocs.
				const tchar* pszValues = pszToken;
				int iValue = 0;
				do
				{
					if (!pszValues)
						break;

					if (!bValues[0] || pszValues[0] == _T('/'))
					{
						if (pszValues[0] == _T('/'))
							pszValues++;

						bValues[iValue] = true;
						f[iValue++] = (long)stoi(pszValues);
						if (iValue >= 3)
							break;
					}

					// Don't advance if we're on a slash, because that means empty slashes. ie, 11//12 <-- the 12 would get skipped.
					if (pszValues[0] != _T('/'))
						pszValues++;
				}
				while (*pszValues);

				if (bValues[0])
				{
					if (f[0] < 0)
						f[0] = (long)pMesh->GetNumVertices()+f[0]+1;
					TAssert ( f[0] >= 1 && f[0] < (long)pMesh->GetNumVertices()+1 );
				}

				if (bValues[1] && pMesh->GetNumUVs())
				{
					if (f[1] < 0)
						f[1] = (long)pMesh->GetNumUVs()+f[1]+1;
					TAssert ( f[1] >= 1 && f[1] < (long)pMesh->GetNumUVs()+1 );
				}

				if (bValues[2] && pMesh->GetNumNormals())
				{
					if (f[2] < 0)
						f[2] = (long)pMesh->GetNumNormals()+f[2]+1;
					TAssert ( f[2] >= 1 && f[2] < (long)pMesh->GetNumNormals()+1 );
				}

				// OBJ uses 1-based indexing.
				// Convert to 0-based indexing.
				f[0]--;
				f[1]--;
				f[2]--;

				if (!pMesh->GetNumUVs())
					f[1] = ~0;
				if (bValues[2] == false || !pMesh->GetNumNormals())
					f[2] = ~0;

				pMesh->AddVertexToFace(iFace, f[0], f[1], f[2]);
			}
		}
	}

	free(pszEntireFile);

	m_pScene->SetWorkListener(m_pWorkListener);

	m_pScene->CalculateExtends();

	for (size_t i = 0; i < m_pScene->GetNumMeshes(); i++)
	{
		m_pScene->GetMesh(i)->CalculateEdgeData();

		if (bSmoothingGroups || m_pScene->GetMesh(i)->GetNumNormals() == 0)
			m_pScene->GetMesh(i)->CalculateVertexNormals();

		m_pScene->GetMesh(i)->CalculateVertexTangents();
	}

	if (m_pWorkListener)
		m_pWorkListener->EndProgress();
}
Exemple #10
0
static BOOL LFNRemover(RDWRHandle handle, struct DirectoryPosition* pos,
                       void** structure)
{
    struct RemovePipe* pipe = *((struct RemovePipe**) structure);
    struct DirectoryEntry entry;

    if (!GetDirectory(handle, pos, &entry))
       return FAIL;

    /* Check the range in which we have to delete the long file name entries */
    if (!pipe->hasstarted) /* Outside the interval */
    {  /* Check wether the starting position was found. */
       if (memcmp(pos, pipe->begin, sizeof(struct DirectoryPosition)) == 0)
          pipe->hasstarted = TRUE;
    }
    
    if (!IsLFNEntry(&entry))
       return TRUE;
       
    if (pipe->hasstarted)   /* Inside the interval, first create a dummy
                               file name entry. */
    {
       struct tm* tmp;
       time_t now;
   
       /* file name and extension, 0xe5 indicates file removed.    */
       memcpy(entry.filename, "å" "LFNRMVD", 8);
       memset(entry.extension, ' ', 3);

       /* attribute */
       entry.attribute = 0;

       /* first cluster */
       SetFirstCluster(2, &entry);

       /* file size */
       entry.filesize = 0;

       /* NT reserved field */
       entry.NTReserved = 0;

       /* Mili second stamp */
       entry.MilisecondStamp = 0;

       /* Last access date */
       memset(&entry.LastAccessDate, 0, sizeof(struct PackedDate));
    
       /* Time last modified */
       memset(&entry.timestamp, 0, sizeof(struct PackedTime));

       /* Date last modified */
       memset(&entry.datestamp, 0, sizeof(struct PackedDate));

       /* Get the current date and time and store it in the last write
          time and date. */
       time(&now);
       tmp = localtime(&now);

       entry.LastWriteTime.second = tmp->tm_sec / 2;
       if (entry.LastWriteTime.second == 30) /* DJGPP help says range is [0..60] */
          entry.LastWriteTime.second--;
    
       entry.LastWriteTime.minute = tmp->tm_min;
       entry.LastWriteTime.hours  = tmp->tm_hour;

       entry.LastWriteDate.day   = tmp->tm_mday;
       entry.LastWriteDate.month = tmp->tm_mon + 1;

       if (tmp->tm_year < 80)
          entry.LastWriteDate.year = 0;
       else
          entry.LastWriteDate.year = (tmp->tm_year+1900)-1980;

       if (!WriteDirectory(handle, pos, &entry))
          return FAIL;
          
       /* Check wether the ending position was found. */
       if ((pipe->end != NULL) &&
           (memcmp(pos, pipe->end, sizeof(struct DirectoryPosition)) == 0))
       {
          return FALSE;       
       }           
    }    
    
    return TRUE;
}
Exemple #11
0
void CModelConverter::ReadMTL(const tstring& sFilename)
{
	FILE* fp = tfopen(sFilename, _T("r"));

	if (!fp)
		return;

	if (m_pWorkListener)
		m_pWorkListener->SetAction(_T("Reading materials"), 0);

	size_t iCurrentMaterial = ~0;

	tstring sLine;
	while (fgetts(sLine, fp))
	{
		sLine = StripWhitespace(sLine);

		if (sLine.length() == 0)
			continue;

		if (sLine[0] == '#')
			continue;

		eastl::vector<tstring> asTokens;
		tstrtok(sLine, asTokens, _T(" "));
		const tchar* pszToken = NULL;
		pszToken = asTokens[0].c_str();

		CConversionMaterial* pMaterial = NULL;
		if (iCurrentMaterial != ~0)
			pMaterial = m_pScene->GetMaterial(iCurrentMaterial);

		if (tstrncmp(pszToken, _T("newmtl"), 6) == 0)
		{
			pszToken = asTokens[1].c_str();
			CConversionMaterial oMaterial(pszToken, Vector(0.2f,0.2f,0.2f), Vector(0.8f,0.8f,0.8f), Vector(1,1,1), Vector(0,0,0), 1.0, 0);
			iCurrentMaterial = m_pScene->AddMaterial(oMaterial);
		}
		else if (tstrncmp(pszToken, _T("Ka"), 2) == 0)
		{
			eastl::vector<tstring> asTokens;
			tstrtok(sLine, asTokens, _T(" "));
			if (asTokens.size() == 4)
			{
				pMaterial->m_vecAmbient.x = stof(asTokens[1]);
				pMaterial->m_vecAmbient.y = stof(asTokens[2]);
				pMaterial->m_vecAmbient.z = stof(asTokens[3]);
			}
		}
		else if (tstrncmp(pszToken, _T("Kd"), 2) == 0)
		{
			eastl::vector<tstring> asTokens;
			tstrtok(sLine, asTokens, _T(" "));
			if (asTokens.size() == 4)
			{
				pMaterial->m_vecDiffuse.x = stof(asTokens[1]);
				pMaterial->m_vecDiffuse.y = stof(asTokens[2]);
				pMaterial->m_vecDiffuse.z = stof(asTokens[3]);
			}
		}
		else if (tstrncmp(pszToken, _T("Ks"), 2) == 0)
		{
			eastl::vector<tstring> asTokens;
			tstrtok(sLine, asTokens, _T(" "));
			if (asTokens.size() == 4)
			{
				pMaterial->m_vecSpecular.x = stof(asTokens[1]);
				pMaterial->m_vecSpecular.y = stof(asTokens[2]);
				pMaterial->m_vecSpecular.z = stof(asTokens[3]);
			}
		}
		else if (tstrncmp(pszToken, _T("d"), 1) == 0 || tstrncmp(pszToken, _T("Tr"), 2) == 0)
		{
			pMaterial->m_flTransparency = (float)stof(asTokens[1]);
		}
		else if (tstrncmp(pszToken, _T("Ns"), 2) == 0)
		{
			pMaterial->m_flShininess = (float)stof(asTokens[1])*128/1000;
		}
		else if (tstrncmp(pszToken, _T("illum"), 5) == 0)
		{
			pMaterial->m_eIllumType = (IllumType_t)stoi(asTokens[1]);
		}
		else if (tstrncmp(pszToken, _T("map_Kd"), 6) == 0)
		{
			pszToken = asTokens[1].c_str();

			FILE* fpTest = tfopen(pszToken, _T("r"));

			if (fpTest)
			{
				fclose(fpTest);

				pMaterial->m_sDiffuseTexture = tstring(pszToken);
			}
			else
			{
				tstring sDirectory = GetDirectory(sFilename);

				pMaterial->m_sDiffuseTexture = sprintf(tstring("%s/%s"), sDirectory.c_str(), pszToken);
			}
		}
	}

	fclose(fp);
}
Exemple #12
0
void FilePath::ReplaceFilename(const String &filename)
{
    DVASSERT(!IsEmpty());
    
    absolutePathname = NormalizePathname((GetDirectory() + filename).absolutePathname);
}
Exemple #13
0
FilePath FilePath::GetDirectory() const
{
    return GetDirectory(absolutePathname, pathType);
}
Exemple #14
0
bool DebugFrontend::Start(const char* command, const char* commandArguments, const char* currentDirectory, const char* symbolsDirectory, bool debug, bool startBroken)
{

    Stop(false);

    STARTUPINFO startUpInfo = { 0 };
    startUpInfo.cb = sizeof(startUpInfo);

    char commandLine[8191];
    _snprintf(commandLine, sizeof(commandLine), "\"%s\" %s", command, commandArguments);

    // If no directory was specified, then use the directory from the exe.
    
    std::string directory = TrimSpaces(currentDirectory);

    if (directory.empty())
    {
        directory = GetDirectory(command);
    }

    PROCESS_INFORMATION processInfo;

    if (debug)
    {
        if (!StartProcessAndRunToEntry(command, commandLine, directory.c_str(), processInfo))
        {
            return false;
        }
    }
    else
    {

        if (!CreateProcess(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, directory.c_str(), &startUpInfo, &processInfo))
        {
            OutputError(GetLastError());
            return false;
        }

        // We're not debugging, so no need to proceed.
        CloseHandle(processInfo.hThread);
        CloseHandle(processInfo.hProcess);
        return true;
    
    }

    DWORD exitCode;

    if (GetExitCodeProcess(processInfo.hProcess, &exitCode) && exitCode != STILL_ACTIVE)
    {
        MessageEvent("The process has terminated unexpectedly", MessageType_Error);
        return false;
    }

    m_process   = processInfo.hProcess;
    m_processId = processInfo.dwProcessId;

    if (!InitializeBackend(symbolsDirectory))
    {
        Stop(true);
        return false;
    }

    if (startBroken)
    {
        Break(0);
    }

    // Now that our initialization is complete, let the process run.
    ResumeThread(processInfo.hThread);
    CloseHandle(processInfo.hThread);

    return true;

}
nsresult nsAbManager::AppendLDIFForMailList(nsIAbCard *aCard, nsIAbLDAPAttributeMap *aAttrMap, nsACString &aResult)
{
  nsresult rv;
  nsString attrValue;

  rv = AppendDNForCard("dn", aCard, aAttrMap, aResult);
  NS_ENSURE_SUCCESS(rv,rv);

  aResult += MSG_LINEBREAK \
             "objectclass: top" MSG_LINEBREAK \
             "objectclass: groupOfNames" MSG_LINEBREAK;

  rv = aCard->GetDisplayName(attrValue);
  NS_ENSURE_SUCCESS(rv,rv);

  nsCAutoString ldapAttributeName;

  rv = aAttrMap->GetFirstAttribute(NS_LITERAL_CSTRING(kDisplayNameProperty),
                                  ldapAttributeName);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = AppendProperty(ldapAttributeName.get(), attrValue.get(), aResult);
  NS_ENSURE_SUCCESS(rv,rv);
  aResult += MSG_LINEBREAK;

  rv = aAttrMap->GetFirstAttribute(NS_LITERAL_CSTRING(kNicknameProperty),
                                  ldapAttributeName);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aCard->GetPropertyAsAString(kNicknameProperty, attrValue);
  if (NS_SUCCEEDED(rv) && !attrValue.IsEmpty()) {
    rv = AppendProperty(ldapAttributeName.get(), attrValue.get(), aResult);
    NS_ENSURE_SUCCESS(rv,rv);
    aResult += MSG_LINEBREAK;
  }

  rv = aAttrMap->GetFirstAttribute(NS_LITERAL_CSTRING(kNotesProperty),
                                  ldapAttributeName);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aCard->GetPropertyAsAString(kNotesProperty, attrValue);
  if (NS_SUCCEEDED(rv) && !attrValue.IsEmpty()) {
    rv = AppendProperty(ldapAttributeName.get(), attrValue.get(), aResult);
    NS_ENSURE_SUCCESS(rv,rv);
    aResult += MSG_LINEBREAK;
  }

  nsCString mailListURI;
  rv = aCard->GetMailListURI(getter_Copies(mailListURI));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr <nsIAbDirectory> mailList;
  rv = GetDirectory(mailListURI, getter_AddRefs(mailList));
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr<nsIMutableArray> addresses;
  rv = mailList->GetAddressLists(getter_AddRefs(addresses));
  if (addresses) {
    PRUint32 total = 0;
    addresses->GetLength(&total);
    if (total) {
      PRUint32 i;
      for (i = 0; i < total; i++) {
        nsCOMPtr <nsIAbCard> listCard = do_QueryElementAt(addresses, i, &rv);
        NS_ENSURE_SUCCESS(rv,rv);

        rv = AppendDNForCard("member", listCard, aAttrMap, aResult);
        NS_ENSURE_SUCCESS(rv,rv);

        aResult += MSG_LINEBREAK;
      }
    }
  }

  aResult += MSG_LINEBREAK;
  return NS_OK;
}
Exemple #16
0
void digitsSPD(Int_t nevents, Int_t nfiles)
{

  TH1F * hadc = new TH1F ("hadc", "hadc",100, 0, 2);   
  TH1F * hadclog = new TH1F ("hadclog", "hadclog",100, -1, 1);   

  TDirectoryFile *tdf[100];      
  TDirectoryFile *tdfKine[100] ; 

  TTree *ttree[100];      
  TTree *ttreeKine[100];  


  TClonesArray *arr= NULL; // 

  //Run loader------------
  TString name;
  name = "galice.root";
  AliRunLoader* rlSig = AliRunLoader::Open(name.Data());

  // gAlice
  rlSig->LoadgAlice();
  gAlice = rlSig->GetAliRun();

  // Now load kinematics and event header
  rlSig->LoadKinematics();
  rlSig->LoadHeader();
  cout <<  rlSig->GetNumberOfEvents()<< endl;
  //----------------------

  
     //loop over events in the files
    for(Int_t event=0; event<nevents; event++){
      //printf("###event= %d\n", event + file*100);
      printf("###event= %d\n", event);

    tdf[event] = GetDirectory(event, "ITS", nfiles);
    if ( ! tdf[event] ) {
      cerr << "Event directory not found in " << nfiles <<  " files" << endl;
      exit(1);
    }      
    
      ttree[event] = (TTree*)tdf[event]->Get("TreeD");
          
      arr = NULL;
      ttree[event]->SetBranchAddress("ITSDigitsSPD", &arr);
   

      // Runloader -> gives particle Stack
      rlSig->GetEvent(event);
      AliStack * stack = rlSig->Stack(); 
      //stack->DumpPStack();


      // loop over tracks
      Int_t NumberPrim=0;
      for(Int_t iev=0; iev<ttree[event]->GetEntries(); iev++){
	ttree[event]->GetEntry(iev);

	
	for (Int_t j = 0; j < arr->GetEntries(); j++) {
	  AliITSdigit* digit = dynamic_cast<AliITSdigit*> (arr->At(j));
	  if (digit){
	    hadc->Fill(digit->GetSignal());
	    hadclog->Fill(TMath::Log10(digit->GetSignal()));
	
	  }
	}
      }

    }

  TFile fc("digits.ITS.SPD.root","RECREATE");
  fc.cd();
   
  hadc->Write();
  hadclog->Write();

  fc.Close();

}
Exemple #17
0
void MythSystemUnix::Fork(time_t timeout)
{
    QString LOC_ERR = QString("myth_system('%1'): Error: ").arg(GetLogCmd());

    // For use in the child
    char locerr[MAX_BUFLEN];
    strncpy(locerr, (const char *)LOC_ERR.toUtf8().constData(), MAX_BUFLEN);
    locerr[MAX_BUFLEN-1] = '\0';

    LOG(VB_SYSTEM, LOG_DEBUG, QString("Launching: %1").arg(GetLogCmd()));

    GetBuffer(0)->setBuffer(0);
    GetBuffer(1)->setBuffer(0);
    GetBuffer(2)->setBuffer(0);

    int p_stdin[]  = {-1,-1};
    int p_stdout[] = {-1,-1};
    int p_stderr[] = {-1,-1};

    /* set up pipes */
    if( GetSetting("UseStdin") )
    {
        if( pipe(p_stdin) == -1 )
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdin pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
            fcntl(p_stdin[1], F_SETFL, O_NONBLOCK);
    }
    if( GetSetting("UseStdout") )
    {
        if( pipe(p_stdout) == -1 )
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdout pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
            fcntl(p_stdout[0], F_SETFL, O_NONBLOCK);
    }
    if( GetSetting("UseStderr") )
    {
        if( pipe(p_stderr) == -1 )
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stderr pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
            fcntl(p_stderr[0], F_SETFL, O_NONBLOCK);
    }

    // set up command args
    if (GetSetting("UseShell"))
    {
        QStringList args = QStringList("-c");
        args << GetCommand() + " " + GetArgs().join(" ");
        SetArgs( args );
        QString cmd = "/bin/sh";
        SetCommand( cmd );
    }
    QStringList args = GetArgs();
    args.prepend(GetCommand().split('/').last());
    SetArgs( args );

    QByteArray cmdUTF8 = GetCommand().toUtf8();
    const char *command = strdup(cmdUTF8.constData());

    char **cmdargs = (char **)malloc((args.size() + 1) * sizeof(char *));
    int i;
    QStringList::const_iterator it;

    for( i = 0, it = args.constBegin(); it != args.constEnd(); it++, i++ )
    {
        cmdargs[i] = strdup( it->toUtf8().constData() );
    }
    cmdargs[i] = NULL;

    const char *directory = NULL;
    QString dir = GetDirectory();
    if (GetSetting("SetDirectory") && !dir.isEmpty())
        directory = strdup(dir.toUtf8().constData());

    // check before fork to avoid QString use in child
    bool setpgidsetting = GetSetting("SetPGID");

    /* Do this before forking in case the child miserably fails */
    m_timeout = timeout;
    if( timeout )
        m_timeout += time(NULL);

    pid_t child = fork();

    if (child < 0)
    {
        /* Fork failed, still in parent */
        LOG(VB_SYSTEM, LOG_ERR, "fork() failed: " + ENO);
        SetStatus( GENERIC_EXIT_NOT_OK );
    }
    else if( child > 0 )
    {
        /* parent */
        m_pid = child;
        SetStatus( GENERIC_EXIT_RUNNING );

        LOG(VB_SYSTEM, LOG_INFO,
                    QString("Managed child (PID: %1) has started! "
                            "%2%3 command=%4, timeout=%5")
                        .arg(m_pid) .arg(GetSetting("UseShell") ? "*" : "")
                        .arg(GetSetting("RunInBackground") ? "&" : "")
                        .arg(GetLogCmd()) .arg(timeout));

        /* close unused pipe ends */
        CLOSE(p_stdin[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[1]);

        // store the rest
        m_stdpipe[0] = p_stdin[1];
        m_stdpipe[1] = p_stdout[0];
        m_stdpipe[2] = p_stderr[0];
    }
    else if (child == 0)
    {
        /* Child - NOTE: it is not safe to use LOG or QString between the 
         * fork and execv calls in the child.  It causes occasional locking 
         * issues that cause deadlocked child processes. */

        /* handle standard input */
        if( p_stdin[0] >= 0 )
        {
            /* try to attach stdin to input pipe - failure is fatal */
            if( dup2(p_stdin[0], 0) < 0 )
            {
                cerr << locerr
                     << "Cannot redirect input pipe to standard input: "
                     << strerror(errno) << endl;
                _exit(GENERIC_EXIT_PIPE_FAILURE);
            }
        }
        else
        {
            /* try to attach stdin to /dev/null */
            int fd = open("/dev/null", O_RDONLY);
            if( fd >= 0 )
            {
                if( dup2(fd, 0) < 0)
                {
                    cerr << locerr
                         << "Cannot redirect /dev/null to standard input,"
                            "\n\t\t\tfailed to duplicate file descriptor: " 
                         << strerror(errno) << endl;
                }
            }
            else
            {
                cerr << locerr
                     << "Cannot redirect /dev/null to standard input, "
                        "failed to open: "
                     << strerror(errno) << endl;
            }
        }

        /* handle standard output */
        if( p_stdout[1] >= 0 )
        {
            /* try to attach stdout to output pipe - failure is fatal */
            if( dup2(p_stdout[1], 1) < 0)
            {
                cerr << locerr
                     << "Cannot redirect output pipe to standard output: "
                     << strerror(errno) << endl;
                _exit(GENERIC_EXIT_PIPE_FAILURE);
            }
        }

        /* handle standard err */
        if( p_stderr[1] >= 0 )
        {
            /* try to attach stderr to error pipe - failure is fatal */
            if( dup2(p_stderr[1], 2) < 0)
            {
                cerr << locerr
                     << "Cannot redirect error pipe to standard error: " 
                     << strerror(errno) << endl;
                _exit(GENERIC_EXIT_PIPE_FAILURE);
            }
        }

        /* Close all open file descriptors except stdin/stdout/stderr */
        for( int i = sysconf(_SC_OPEN_MAX) - 1; i > 2; i-- )
            close(i);

        /* set directory */
        if( directory && chdir(directory) < 0 )
        {
            cerr << locerr
                 << "chdir() failed: "
                 << strerror(errno) << endl;
        }

        /* Set the process group id to be the same as the pid of this child
         * process.  This ensures that any subprocesses launched by this
         * process can be killed along with the process itself. */ 
        if (setpgidsetting && setpgid(0,0) < 0 ) 
        {
            cerr << locerr
                 << "setpgid() failed: "
                 << strerror(errno) << endl;
        }

        /* run command */
        if( execv(command, cmdargs) < 0 )
        {
            // Can't use LOG due to locking fun.
            cerr << locerr
                 << "execv() failed: "
                 << strerror(errno) << endl;
        }

        /* Failed to exec */
        _exit(GENERIC_EXIT_DAEMONIZING_ERROR); // this exit is ok
    }

    /* Parent */

    // clean up the memory use
    if( command )
        free((void *)command);

    if( directory )
        free((void *)directory);

    if( cmdargs )
    {
        for (i = 0; cmdargs[i]; i++)
            free( cmdargs[i] );
        free( cmdargs );
    }

    if( GetStatus() != GENERIC_EXIT_RUNNING )
    {
        CLOSE(p_stdin[0]);
        CLOSE(p_stdin[1]);
        CLOSE(p_stdout[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[0]);
        CLOSE(p_stderr[1]);
    }
}
Exemple #18
0
const tchar* CModelConverter::ReadSIAMat(const tchar* pszLine, const tchar* pszEnd, CConversionSceneNode* pScene, const tstring& sFilename)
{
	if (m_pWorkListener)
		m_pWorkListener->SetAction(_T("Reading materials"), 0);

	size_t iCurrentMaterial = m_pScene->AddMaterial(_T(""));
	CConversionMaterial* pMaterial = m_pScene->GetMaterial(iCurrentMaterial);

	const tchar* pszNextLine = NULL;
	while (pszLine < pszEnd)
	{
		if (pszNextLine)
			pszLine = pszNextLine;

		pszNextLine = pszLine + tstrlen(pszLine) + 1;

		// This code used to call StripWhitespace() but that's too slow for very large files w/ millions of lines.
		// Instead we'll just cut the whitespace off the front and deal with whitespace on the end when we come to it.
		while (*pszLine && IsWhitespace(*pszLine))
			pszLine++;

		if (tstrlen(pszLine) == 0)
			continue;

		eastl::vector<tstring> aTokens;
		tstrtok(pszLine, aTokens, _T(" "));
		const tchar* pszToken = aTokens[0].c_str();

		if (tstrncmp(pszToken, _T("-name"), 5) == 0)
		{
			tstring sName = pszLine+6;
			eastl::vector<tstring> aName;
			tstrtok(sName, aName, _T("\""));	// Strip out the quotation marks.

			pMaterial->m_sName = aName[0];
		}
		else if (tstrncmp(pszToken, _T("-dif"), 4) == 0)
		{
			eastl::vector<tstring> asTokens;
			tstrtok(pszLine, asTokens, _T(" "));
			if (asTokens.size() == 4)
			{
				pMaterial->m_vecDiffuse.x = stof(asTokens[1]);
				pMaterial->m_vecDiffuse.y = stof(asTokens[2]);
				pMaterial->m_vecDiffuse.z = stof(asTokens[3]);
			}
		}
		else if (tstrncmp(pszToken, _T("-amb"), 4) == 0)
		{
			eastl::vector<tstring> asTokens;
			tstrtok(pszLine, asTokens, _T(" "));
			if (asTokens.size() == 4)
			{
				pMaterial->m_vecAmbient.x = stof(asTokens[1]);
				pMaterial->m_vecAmbient.y = stof(asTokens[2]);
				pMaterial->m_vecAmbient.z = stof(asTokens[3]);
			}
		}
		else if (tstrncmp(pszToken, _T("-spec"), 5) == 0)
		{
			eastl::vector<tstring> asTokens;
			tstrtok(pszLine, asTokens, _T(" "));
			if (asTokens.size() == 4)
			{
				pMaterial->m_vecSpecular.x = stof(asTokens[1]);
				pMaterial->m_vecSpecular.y = stof(asTokens[2]);
				pMaterial->m_vecSpecular.z = stof(asTokens[3]);
			}
		}
		else if (tstrncmp(pszToken, _T("-emis"), 5) == 0)
		{
			eastl::vector<tstring> asTokens;
			tstrtok(pszLine, asTokens, _T(" "));
			if (asTokens.size() == 4)
			{
				pMaterial->m_vecEmissive.x = stof(asTokens[1]);
				pMaterial->m_vecEmissive.y = stof(asTokens[2]);
				pMaterial->m_vecEmissive.z = stof(asTokens[3]);
			}
		}
		else if (tstrncmp(pszToken, _T("-shin"), 5) == 0)
		{
			eastl::vector<tstring> asTokens;
			tstrtok(pszLine, asTokens, _T(" "));
			if (asTokens.size() == 2)
				pMaterial->m_flShininess = stof(asTokens[1]);
		}
		else if (tstrncmp(pszToken, _T("-tex"), 4) == 0)
		{
			const tchar* pszTexture = pszLine+5;

			tstring sName = pszTexture;
			eastl::vector<tstring> aName;
			tstrtok(sName, aName, _T("\""));	// Strip out the quotation marks.

			tstring sDirectory = GetDirectory(sFilename);

			pMaterial->m_sDiffuseTexture = sprintf(tstring("%s/%s"), sDirectory.c_str(), aName[0].c_str());
		}
		else if (tstrncmp(pszToken, _T("-endMat"), 7) == 0)
		{
			return pszNextLine;
		}
	}

	return pszNextLine;
}
bool LEVELSELECT::NextDirectoryAvailable()
{
    return (GetDirectory() != NULL && GetDirectory()->next != NULL);
}
Exemple #20
0
void CModelConverter::SaveSIA(const tstring& sFilename)
{
	tstring sSIAFileName = tstring(GetDirectory(sFilename).c_str()) + _T("/") + GetFilename(sFilename).c_str() + _T(".sia");

	std::wofstream sFile(convertstring<tchar, char>(sSIAFileName).c_str());
	if (!sFile.is_open())
		return;

	sFile.precision(8);
	sFile.setf(std::ios::fixed, std::ios::floatfield);

	if (m_pWorkListener)
	{
		m_pWorkListener->BeginProgress();
		m_pWorkListener->SetAction(_T("Writing materials..."), 0);
	}

	sFile << _T("-Version 1.0") << std::endl;

	for (size_t i = 0; i < m_pScene->GetNumMaterials(); i++)
	{
		sFile << _T("-Mat") << std::endl;

		CConversionMaterial* pMaterial = m_pScene->GetMaterial(i);

		sFile << "-amb " << pMaterial->m_vecAmbient.x << _T(" ") << pMaterial->m_vecAmbient.y << _T(" ") << pMaterial->m_vecAmbient.z << _T(" 0") << std::endl;
		sFile << "-dif " << pMaterial->m_vecDiffuse.x << _T(" ") << pMaterial->m_vecDiffuse.y << _T(" ") << pMaterial->m_vecDiffuse.z << _T(" 0") << std::endl;
		sFile << "-spec " << pMaterial->m_vecSpecular.x << _T(" ") << pMaterial->m_vecSpecular.y << _T(" ") << pMaterial->m_vecSpecular.z << _T(" 0") << std::endl;
		sFile << "-emis " << pMaterial->m_vecEmissive.x << _T(" ") << pMaterial->m_vecEmissive.y << _T(" ") << pMaterial->m_vecEmissive.z << _T(" 0") << std::endl;
		sFile << "-shin " << pMaterial->m_flShininess << std::endl;
		sFile << "-name \"" << pMaterial->GetName().c_str() << _T("\"") << std::endl;
		if (pMaterial->GetDiffuseTexture().length() > 0)
			sFile << "-tex \"" << pMaterial->GetDiffuseTexture().c_str() << _T("\"") << std::endl;
		sFile << _T("-endMat") << std::endl;
	}

	for (size_t i = 0; i < m_pScene->GetNumMeshes(); i++)
	{
		CConversionMesh* pMesh = m_pScene->GetMesh(i);

		size_t iAddV = pMesh->GetNumVertices();
		size_t iAddE = pMesh->GetNumEdges();
		size_t iAddUV = pMesh->GetNumUVs();
		size_t iAddN = pMesh->GetNumNormals();

		// Find the default scene for this mesh.
		CConversionSceneNode* pScene = NULL;
		for (size_t j = 0; j < m_pScene->GetNumScenes(); j++)
		{
			if (m_pScene->GetScene(j)->GetName() == pMesh->GetName() + _T(".sia"))
			{
				pScene = m_pScene->GetScene(j);
				break;
			}
		}

		tstring sNodeName = pMesh->GetName();

		sFile << _T("-Shape") << std::endl;
		sFile << _T("-snam \"") << sNodeName.c_str() << _T("\"") << std::endl;
		sFile << _T("-shad 0") << std::endl;
		sFile << _T("-shadw 1") << std::endl;

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" vertices...")).c_str(), pMesh->GetNumVertices());

		for (size_t iVertices = 0; iVertices < pMesh->GetNumVertices(); iVertices++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iVertices);

			Vector vecVertex = pMesh->GetVertex(iVertices);
			sFile << _T("-vert ") << vecVertex.x << _T(" ") << vecVertex.y << _T(" ") << vecVertex.z << std::endl;
		}

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" edges...")).c_str(), pMesh->GetNumEdges());

		tstring sCreases;

		for (size_t iEdges = 0; iEdges < pMesh->GetNumEdges(); iEdges++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iEdges);

			CConversionEdge* pEdge = pMesh->GetEdge(iEdges);
			sFile << _T("-edge ") << pEdge->v1 << _T(" ") << pEdge->v2 << std::endl;

			if (pEdge->m_bCreased)
				sCreases += sprintf(tstring(" %d"), iEdges);
		}

		if (sCreases.length())
			sFile << _T("-creas") << sCreases.c_str() << std::endl;

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" faces...")).c_str(), pMesh->GetNumFaces());

		size_t iMaterial = 0;

		for (size_t iFaces = 0; iFaces < pMesh->GetNumFaces(); iFaces++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iFaces);

			CConversionFace* pFace = pMesh->GetFace(iFaces);

			if (iFaces == 0 || iMaterial != pFace->m)
			{
				iMaterial = pFace->m;

				if (iMaterial == ~0)
					sFile << _T("-setmat -1") << std::endl;
				else
				{
					CConversionSceneNode* pNode = m_pScene->GetDefaultSceneMeshInstance(pScene, pMesh, false);

					if (!pNode || pNode->GetNumMeshInstances() != 1)
						sFile << _T("-setmat -1") << std::endl;
					else
					{
						CConversionMaterialMap* pMap = pNode->GetMeshInstance(0)->GetMappedMaterial(iMaterial);
						if (pMap)
							sFile << _T("-setmat -1") << std::endl;
						else
							sFile << _T("-setmat ") << pMap->m_iMaterial << std::endl;
					}
				}
			}

			sFile << _T("-face ") << pFace->GetNumVertices();

			TAssert(pFace->GetNumEdges() == pFace->GetNumVertices());

			for (size_t iVertsInFace = 0; iVertsInFace < pFace->GetNumVertices(); iVertsInFace++)
			{
				CConversionVertex* pVertex = pFace->GetVertex(iVertsInFace);
				CConversionVertex* pNextVertex = pFace->GetVertex((iVertsInFace+1)%pFace->GetNumVertices());

				// Find the edge that heads in a counter-clockwise direction.
				size_t iEdge = ~0;
				for (size_t i = 0; i < pFace->GetNumEdges(); i++)
				{
					size_t iEdgeCandidate = pFace->GetEdge(i);
					CConversionEdge* pEdge = pMesh->GetEdge(iEdgeCandidate);
					if ((pEdge->v1 == pVertex->v && pEdge->v2 == pNextVertex->v) || (pEdge->v2 == pVertex->v && pEdge->v1 == pNextVertex->v))
					{
						iEdge = iEdgeCandidate;
						break;
					}
				}
				TAssert(iEdge != ~0);

				Vector vecUV = pMesh->GetUV(pVertex->vu);
				sFile << _T(" ") << pVertex->v << _T(" ") << iEdge << _T(" ") << vecUV.x << _T(" ") << vecUV.y;
			}

			sFile << std::endl;
		}

		sFile << _T("-axis 0 0.5 0 1 0 0 0 1 0 0 0 1") << std::endl;
		sFile << _T("-mirp 0 0 0 1 0 0") << std::endl;
		sFile << _T("-endShape") << std::endl;
	}

	if (m_pWorkListener)
		m_pWorkListener->EndProgress();
}
int LEVELSELECT::Select()
{
    const char noDirectoryName[] = "[kein Verzeichnis]";

    BUTTON prevDirButton ({{10, windY - 100}, {90, windY - 50}}, 0, 3, 10, CYAN, "<", 20, YELLOW);
    BUTTON nextDirButton ({{windX - 100, windY - 100}, {windX - 10, windY - 50}}, 0, 3, 10, CYAN, ">", 20, YELLOW);
    BUTTON dirCaption ({{100, windY - 100}, {windX - 110, windY - 50}}, 3, 3, 10, CYAN, "(Directory)", 20, YELLOW);
    BUTTON prevButton ({{10, windY - 180}, {90, windY - 130}}, 0, 3, 10, CYAN, "<", 20, YELLOW);
    BUTTON nextButton ({{windX - 100, windY - 180}, {windX - 10, windY - 130}}, 0, 3, 10, CYAN, ">", 20, YELLOW);
    BUTTON selectButton ({{windX - 200, 10}, {windX - 10, 60}}, 0, 3, 10, CYAN, "Spiel starten", 20, YELLOW);
    BUTTON cancelButton ({{10, 10}, {190, 60}}, 0, 3, 10, CYAN, "Zurück", 20, YELLOW);
    BUTTON levelCaption ({{100, windY - 180}, {windX - 110, windY - 130}}, 3, 3, 10, CYAN, "(Levelname)", 20, YELLOW);
    AREA highscoreOutput {{100, 140}, {windX / 2 - 100, windY - 240}};
    prevDirButton.assignKeyboardButton(0,'Q');
    nextDirButton.assignKeyboardButton(0,'E');
    prevButton   .assignKeyboardButton(0,GLFW_KEY_LEFT ,'A');
    nextButton   .assignKeyboardButton(0,GLFW_KEY_RIGHT,'D');
    levelCaption .assignKeyboardButton(0,'S');
    cancelButton .assignKeyboardButton(0,GLFW_KEY_ESC);
    selectButton .assignKeyboardButton(0,GLFW_KEY_ENTER,GLFW_KEY_SPACE);

    ReloadHighscore();

    prepare_GameLoop();

    do
    {
        prepare_graphics();

        char levelText[MAX_PATH];
        if (GetLevel() != NULL)
            sprintf(levelText, "%s (%d/%d)", GetLevel()->name, GetLevel()->index + 1, GetLevelCount());
        else
            strcpy(levelText, "[Kein Level vorhanden]");

        levelCaption.setText(levelText);

        const char* directoryName;
        if (strlen(GetDirectory()->name) > 0)
            directoryName = GetDirectory()->name;
        else
            directoryName = noDirectoryName;

        char directoryText[strlen(directoryName) + 9];

        sprintf(directoryText, "%s (%d/%d)", directoryName, GetDirectory()->index + 1, GetDirectoryCount());
        dirCaption.setText(directoryText);

        //handle clicks
        if (cancelButton.clicked())
            break;
        else if (selectButton.clicked() && isInputValid())
        {
            currentLevel->score.setTimesPlayed(currentLevel->score.getTimesPlayed() + 1);
            return true;
        }
        else if (prevButton.clicked() || levelCaption.clicked() == 2)
            SwitchLevel(-1);
        else if (nextButton.clicked() || levelCaption.clicked() == 1)
            SwitchLevel(1);
        else if (prevDirButton.clicked() || dirCaption.clicked() == 2)
            SwitchDirectory(-1);
        else if (nextDirButton.clicked() || dirCaption.clicked() == 1)
            SwitchDirectory(1);

        //output
        prevDirButton.print();
        nextDirButton.print();
        dirCaption.print();
        prevButton.print();
        nextButton.print();
        selectButton.print();
        cancelButton.print();
        levelCaption.print();

        if (currentLevel != NULL)
        {
            drawBox({{windX/2 + 80, 140}, {windX - 110, windY - 240}}, 10, 3, WHITE);
            currentLevel->level->printPreview();

            TIME time = currentLevel->score.getTime();
            drawBox(highscoreOutput,10,3,WHITE);
            normalFont.printf({highscoreOutput.a.x + 20, highscoreOutput.b.y - 40}, taLEFT, "Highscore");
            normalFont.printf({highscoreOutput.a.x + 20, highscoreOutput.b.y - 80}, taLEFT, "Züge: %d", currentLevel->score.getMoves());
            normalFont.printf({highscoreOutput.a.x + 20, highscoreOutput.b.y - 120}, taLEFT, "Zeit: %02d:%02d:%05.2f", time.Hours, time.Minutes, time.Seconds);
            normalFont.printf({highscoreOutput.a.x + 20, highscoreOutput.b.y - 160}, taLEFT, "%d mal gespielt", currentLevel->score.getTimesPlayed());
        }
    } while (complete_graphics());

    logger(true, "LEVELSELECT: Cancelled, Returning false.");
    return false;
}
void MythSystemLegacyWindows::Fork(time_t timeout)
{
    BOOL bInherit = FALSE;

    QString LOC_ERR = QString("myth_system('%1'): Error: ").arg(GetLogCmd());

    LOG(VB_SYSTEM, LOG_DEBUG, QString("Launching: %1").arg(GetLogCmd()));

    HANDLE p_stdin[2] = { nullptr, nullptr };
    HANDLE p_stdout[2] = { nullptr, nullptr };
    HANDLE p_stderr[2] = { nullptr, nullptr };

    SECURITY_ATTRIBUTES saAttr;
    STARTUPINFO si;

    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);

    // Set the bInheritHandle flag so pipe handles are inherited.
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = true;
    saAttr.lpSecurityDescriptor = nullptr;

    /* set up pipes */
    if( GetSetting("UseStdin") )
    {
        bInherit = TRUE;

        if (!CreatePipe(&p_stdin[0], &p_stdin[1], &saAttr, 0))
        {
            LOG(VB_GENERAL, LOG_ERR, LOC_ERR + "stdin pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the write handle to the pipe for STDIN is not inherited.
            if (!SetHandleInformation(p_stdin[1], HANDLE_FLAG_INHERIT, 0))
            {
                LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdin inheritance error");
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdInput = p_stdin[0];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    if( GetSetting("UseStdout") )
    {
        bInherit = TRUE;

        if (!CreatePipe(&p_stdout[0], &p_stdout[1], &saAttr, 0))
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdout pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the read handle to the pipe for STDOUT is not inherited.
            if (!SetHandleInformation(p_stdout[0], HANDLE_FLAG_INHERIT, 0))
            {
                LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdout inheritance error");
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdOutput = p_stdout[1];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    if( GetSetting("UseStderr") )
    {
        bInherit = TRUE;

        if (!CreatePipe(&p_stderr[0], &p_stderr[1], &saAttr, 0))
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stderr pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the read handle to the pipe for STDERR is not inherited.
            if (!SetHandleInformation(p_stderr[0], HANDLE_FLAG_INHERIT, 0))
            {
                LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stderr inheritance error");
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdError = p_stderr[1];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    // set up command args
    QString cmd = GetCommand() + " " + GetArgs().join(" ");

    if (GetSetting("UseShell"))
        cmd.prepend("cmd.exe /c ");

    SetCommand( cmd );

    QString sCmd = GetCommand();

    QString dir = GetDirectory();

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));

    m_timeout = timeout;
    if( timeout )
        m_timeout += time(nullptr);

    LPCWSTR pDir = nullptr;
    if (dir.length() > 0)
        pDir = (LPCWSTR)dir.utf16();

    bool success = CreateProcess( nullptr,
                          (LPWSTR)sCmd.utf16(),       // command line
                          nullptr,       // process security attributes
                          nullptr,       // primary thread security attributes
                          bInherit,      // handles are inherited
                          0,             // creation flags
                          nullptr,       // use parent's environment
                          pDir,          // use parent's current directory
                          &si,            // STARTUPINFO pointer
                          &pi);           // receives PROCESS_INFORMATION

    if (!success)
    {
        DWORD dwErr = GetLastError();
        LOG(VB_SYSTEM, LOG_ERR,
                QString( "%1 CreateProcess() failed (%2)")
                    .arg( LOC_ERR )
                    .arg( dwErr ));
        SetStatus( GENERIC_EXIT_NOT_OK );
    }
    else
    {
        /* parent */
        m_child = pi.hProcess;
        SetStatus( GENERIC_EXIT_RUNNING );

        LOG(VB_SYSTEM, LOG_INFO,
                QString("Managed child (Handle: %1) has started! "
                        "%2%3 command=%4, timeout=%5")
                    .arg((long long)m_child)
                    .arg(GetSetting("UseShell") ? "*" : "")
                    .arg(GetSetting("RunInBackground") ? "&" : "")
                    .arg(GetLogCmd()) .arg(timeout));

        /* close unused pipe ends */
        CLOSE(p_stdin[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[1]);

        // store the rest
        m_stdpipe[0] = p_stdin[1];
        m_stdpipe[1] = p_stdout[0];
        m_stdpipe[2] = p_stderr[0];

    }

    /* Parent */
    if( GetStatus() != GENERIC_EXIT_RUNNING )
    {
        CLOSE(p_stdin[0]);
        CLOSE(p_stdin[1]);
        CLOSE(p_stdout[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[0]);
        CLOSE(p_stderr[1]);
    }
}
Exemple #23
0
tstring PathX::GetDirectory(const tstring& path)
{
	tstring outDirectory;
	GetDirectory(path, outDirectory);
	return outDirectory;
}
Exemple #24
0
INT cmd_move (LPTSTR param)
{
	LPTSTR *arg;
	INT argc, i, nFiles;
	LPTSTR pszDest;
	TCHAR szDestPath[MAX_PATH];
	TCHAR szFullDestPath[MAX_PATH];
	TCHAR szSrcDirPath[MAX_PATH];
	TCHAR szSrcPath[MAX_PATH];
	TCHAR szFullSrcPath[MAX_PATH];
	DWORD dwFlags = 0;
	INT nOverwrite = 0;
	WIN32_FIND_DATA findBuffer;
	HANDLE hFile;
	
	/* used only when source and destination  directories are on different volume*/
	HANDLE hDestFile;
	WIN32_FIND_DATA findDestBuffer;
	TCHAR szMoveDest[MAX_PATH];
	TCHAR szMoveSrc[MAX_PATH];
	LPTSTR pszDestDirPointer;
	LPTSTR pszSrcDirPointer;
	INT nDirLevel = 0;
	
	LPTSTR pszFile;
	BOOL OnlyOneFile;
	BOOL FoundFile;
	BOOL MoveStatus;
	DWORD dwMoveFlags = 0;
	DWORD dwMoveStatusFlags = 0;


	if (!_tcsncmp (param, _T("/?"), 2))
	{
#if 0
		ConOutPuts (_T("Moves files and renames files and directories.\n\n"
			"To move one or more files:\n"
			"MOVE [/N][/Y|/-Y][drive:][path]filename1[,...] destination\n"
			"\n"
			"To rename a directory:\n"
			"MOVE [/N][/Y|/-Y][drive:][path]dirname1 dirname2\n"
			"\n"
			"  [drive:][path]filename1  Specifies the location and name of the file\n"
			"                           or files you want to move.\n"
			"  /N                       Nothing. Don everthing but move files or direcories.\n"
			"  /Y\n"
			"  /-Y\n"
			"..."));
#else
		ConOutResPaging(TRUE,STRING_MOVE_HELP2);
#endif
		return 0;
	}

	nErrorLevel = 0;
	arg = splitspace(param, &argc);

	/* read options */
	for (i = 0; i < argc; i++)
	{
		if (!_tcsicmp(arg[i], _T("/N")))
			dwFlags |= MOVE_NOTHING;
		else if (!_tcsicmp(arg[i], _T("/Y")))
			dwFlags |= MOVE_OVER_YES;
		else if (!_tcsicmp(arg[i], _T("/-Y")))
			dwFlags |= MOVE_OVER_NO;
		else
			break;
	}
	nFiles = argc - i;

	if (nFiles < 1)
	{
		/* there must be at least one pathspec */
		error_req_param_missing();
		freep(arg);
		return 1;
	}

	if (nFiles > 2)
	{
		/* there are more than two pathspecs */
		error_too_many_parameters(param);
		freep(arg);
		return 1;
	}

	/* If no destination is given, default to current directory */
	pszDest = (nFiles == 1) ? _T(".") : arg[i + 1];

	/* check for wildcards in source and destination */
	if (_tcschr(pszDest, _T('*')) != NULL || _tcschr(pszDest, _T('?')) != NULL)
	{
		/* '*'/'?' in dest, this doesnt happen.  give folder name instead*/
		error_invalid_parameter_format(pszDest);
		freep(arg);
		return 1;
	}
	if (_tcschr(arg[i], _T('*')) != NULL || _tcschr(arg[i], _T('?')) != NULL)
	{
		dwMoveStatusFlags |= MOVE_SOURCE_HAS_WILD;
	}
	
	
	/* get destination */
	GetFullPathName (pszDest, MAX_PATH, szDestPath, NULL);
	TRACE ("Destination: %s\n", debugstr_aw(szDestPath));
	
	/* get source folder */
	GetFullPathName(arg[i], MAX_PATH, szSrcDirPath, &pszFile);
	if (pszFile != NULL)
		*pszFile = _T('\0');
	TRACE ("Source Folder: %s\n", debugstr_aw(szSrcDirPath));
	
	hFile = FindFirstFile (arg[i], &findBuffer);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		ErrorMessage (GetLastError (), arg[i]);
		freep (arg);
		return 1;
		
	}

	/* check for special cases "." and ".." and if found skip them */
	FoundFile = TRUE;
	while(FoundFile &&
		  (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
		   _tcscmp(findBuffer.cFileName,_T("..")) == 0))
		FoundFile = FindNextFile (hFile, &findBuffer);
	
	if (!FoundFile)
	{
		/* what? we don't have anything to move? */
		error_file_not_found();
		FindClose(hFile);
		freep(arg);
		return 1;
	}
	
	OnlyOneFile = TRUE;
	/* check if there can be found files as files have first priority */
	if (findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		dwMoveStatusFlags |= MOVE_SOURCE_IS_DIR;
	else
		dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
	while(OnlyOneFile && FindNextFile(hFile,&findBuffer))
	{
		if (!(findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
		{
			ConOutPrintf(_T(""));
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) OnlyOneFile = FALSE;
			else
			{	/* this has been done this way so that we don't disturb other settings if they have been set before this */
				dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
				dwMoveStatusFlags &= ~MOVE_SOURCE_IS_DIR;
			}
		}
	}
	FindClose(hFile);

	TRACE ("Do we have only one file: %s\n", OnlyOneFile ? "TRUE" : "FALSE");

	/* we have to start again to be sure we don't miss any files or folders*/
	hFile = FindFirstFile (arg[i], &findBuffer);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		ErrorMessage (GetLastError (), arg[i]);
		freep (arg);
		return 1;
		
	}
	
	/* check for special cases "." and ".." and if found skip them */
	FoundFile = TRUE;
	while(FoundFile &&
		  (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
		   _tcscmp(findBuffer.cFileName,_T("..")) == 0))
		FoundFile = FindNextFile (hFile, &findBuffer);
	
	if (!FoundFile)
	{
		/* huh? somebody removed files and/or folders which were there */
		error_file_not_found();
		FindClose(hFile);
		freep(arg);
		return 1;
	}
	
	/* check if source and destination paths are on different volumes */
	if (szSrcDirPath[0] != szDestPath[0])
		dwMoveStatusFlags |= MOVE_PATHS_ON_DIF_VOL;
	
	/* move it */
	do
	{
		TRACE ("Found file/directory: %s\n", debugstr_aw(findBuffer.cFileName));
		nOverwrite = 1;
		dwMoveFlags = 0;
		dwMoveStatusFlags &= ~MOVE_DEST_IS_FILE &
							~MOVE_DEST_IS_DIR &
							~MOVE_SRC_CURRENT_IS_DIR &
							~MOVE_DEST_EXISTS;
		_tcscpy(szFullSrcPath,szSrcDirPath);
		if(szFullSrcPath[_tcslen(szFullSrcPath) -  1] != _T('\\'))
			_tcscat (szFullSrcPath, _T("\\"));
		_tcscat(szFullSrcPath,findBuffer.cFileName);
		_tcscpy(szSrcPath, szFullSrcPath);
		
		if (IsExistingDirectory(szSrcPath))
		{
			/* source is directory */
			
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE)
			{
				dwMoveStatusFlags |= MOVE_SRC_CURRENT_IS_DIR; /* source is file but at the current round we found a directory */
				continue;
			}
			TRACE ("Source is dir: %s\n", debugstr_aw(szSrcPath));
			dwMoveFlags = MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
		}
		
		/* if source is file we don't need to do anything special */
		
		if (IsExistingDirectory(szDestPath))
		{
			/* destination is existing directory */
			TRACE ("Destination is directory: %s\n", debugstr_aw(szDestPath));
			
			dwMoveStatusFlags |= MOVE_DEST_IS_DIR;
			
			/*build the dest string(accounts for *)*/
			_tcscpy (szFullDestPath, szDestPath);
			/*check to see if there is an ending slash, if not add one*/
			if(szFullDestPath[_tcslen(szFullDestPath) -  1] != _T('\\'))
				_tcscat (szFullDestPath, _T("\\"));
			_tcscat (szFullDestPath, findBuffer.cFileName);
			
			if (IsExistingFile(szFullDestPath) || IsExistingDirectory(szFullDestPath))
				dwMoveStatusFlags |= MOVE_DEST_EXISTS;
			
			dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
			
		}
		if (IsExistingFile(szDestPath))
		{
			/* destination is a file */
			TRACE ("Destination is file: %s\n", debugstr_aw(szDestPath));
			
			dwMoveStatusFlags |= MOVE_DEST_IS_FILE | MOVE_DEST_EXISTS;
			_tcscpy (szFullDestPath, szDestPath);
			
			dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
			
		}
		
		TRACE ("Move Status Flags: 0x%X\n",dwMoveStatusFlags);
		
		if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
			dwMoveStatusFlags & MOVE_DEST_IS_DIR &&
			dwMoveStatusFlags & MOVE_SOURCE_HAS_WILD)
		{
			/* We are not allowed to have existing source and destination dir when there is wildcard in source */
			error_syntax(NULL);
			FindClose(hFile);
			freep(arg);
			return 1;
		}
			
		if (!(dwMoveStatusFlags & (MOVE_DEST_IS_FILE | MOVE_DEST_IS_DIR)))
		{
			/* destination doesn't exist */
			_tcscpy (szFullDestPath, szDestPath);
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) dwMoveStatusFlags |= MOVE_DEST_IS_FILE;
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) dwMoveStatusFlags |= MOVE_DEST_IS_DIR;
			
			dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
		}
		
		if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE &&
			dwMoveStatusFlags & MOVE_DEST_IS_FILE &&
			!OnlyOneFile)
		{
			/*source has many files but there is only one destination file*/
			error_invalid_parameter_format(pszDest);
			FindClose(hFile);
			freep (arg);
			return 1;
		}
		
		/*checks to make sure user wanted/wants the override*/
		if((dwFlags & MOVE_OVER_NO) &&
		   (dwMoveStatusFlags & MOVE_DEST_EXISTS))
			continue;
		if(!(dwFlags & MOVE_OVER_YES) &&
		    (dwMoveStatusFlags & MOVE_DEST_EXISTS))
			nOverwrite = MoveOverwrite (szFullDestPath);
		if (nOverwrite == PROMPT_NO || nOverwrite == PROMPT_BREAK)
			continue;
		if (nOverwrite == PROMPT_ALL)
			dwFlags |= MOVE_OVER_YES;
		
			
		ConOutPrintf (_T("%s => %s "), szSrcPath, szFullDestPath);
		
		/* are we really supposed to do something */
		if (dwFlags & MOVE_NOTHING)
			continue;
		
		/*move the file*/
		if (!(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
			dwMoveStatusFlags & MOVE_PATHS_ON_DIF_VOL))
			/* we aren't moving source folder to different drive */
			MoveStatus = MoveFileEx (szSrcPath, szFullDestPath, dwMoveFlags);
		else
		{	/* we are moving source folder to different drive */
			_tcscpy(szMoveDest, szFullDestPath);
			_tcscpy(szMoveSrc, szSrcPath);
			DeleteFile(szMoveDest);
			MoveStatus = CreateDirectory(szMoveDest, NULL); /* we use default security settings */
			if (MoveStatus)
			{
				_tcscat(szMoveDest,_T("\\"));
				_tcscat(szMoveSrc,_T("\\"));
				nDirLevel = 0;
				pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
				pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
				_tcscpy(pszSrcDirPointer,_T("*.*"));
				hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
				if (hDestFile == INVALID_HANDLE_VALUE)
					MoveStatus = FALSE;
				else
				{
					BOOL FirstTime = TRUE;
					FoundFile = TRUE;
					MoveStatus = FALSE;
					while(FoundFile)
					{
						if (FirstTime)
							FirstTime = FALSE;
						else
							FoundFile = FindNextFile (hDestFile, &findDestBuffer);
						
						if (!FoundFile)
						{	/* Nothing to do in this folder so we stop working on it */
							FindClose(hDestFile);
							(pszSrcDirPointer)--;
							(pszDestDirPointer)--;
							_tcscpy(pszSrcDirPointer,_T(""));
							_tcscpy(pszDestDirPointer,_T(""));
							if (nDirLevel > 0)
							{
								TCHAR szTempPath[MAX_PATH];
								INT nDiff;

								FoundFile = TRUE; /* we need to continue our seek for files */
								nDirLevel--;
								RemoveDirectory(szMoveSrc);
								GetDirectory(szMoveSrc,szTempPath,0);
								nDiff = _tcslen(szMoveSrc) - _tcslen(szTempPath);
								pszSrcDirPointer = pszSrcDirPointer - nDiff;
								_tcscpy(pszSrcDirPointer,_T(""));
								GetDirectory(szMoveDest,szTempPath,0);
								nDiff = _tcslen(szMoveDest) - _tcslen(szTempPath);
								pszDestDirPointer = pszDestDirPointer - nDiff;
								_tcscpy(pszDestDirPointer,_T(""));
								if(szMoveSrc[_tcslen(szMoveSrc) -  1] != _T('\\'))
									_tcscat (szMoveSrc, _T("\\"));
								if(szMoveDest[_tcslen(szMoveDest) -  1] != _T('\\'))
									_tcscat (szMoveDest, _T("\\"));
								pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
								pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
								_tcscpy(pszSrcDirPointer,_T("*.*"));
								hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
								if (hDestFile == INVALID_HANDLE_VALUE)
									continue;
								FirstTime = TRUE;
							}
							else
							{
								MoveStatus = TRUE; /* we moved everything so lets tell user about it */
								RemoveDirectory(szMoveSrc);
							}
							continue;
						}
						
						/* if we find "." or ".." we'll skip them */
						if (_tcscmp(findDestBuffer.cFileName,_T(".")) == 0 ||
							_tcscmp(findDestBuffer.cFileName,_T("..")) == 0)
							continue;
					
						_tcscpy(pszSrcDirPointer, findDestBuffer.cFileName);
						_tcscpy(pszDestDirPointer, findDestBuffer.cFileName);
						if (IsExistingFile(szMoveSrc))
						{
							FoundFile = CopyFile(szMoveSrc, szMoveDest, FALSE);
							if (!FoundFile) continue;
							DeleteFile(szMoveSrc);
						}
						else
						{
							FindClose(hDestFile);
							CreateDirectory(szMoveDest, NULL);
							_tcscat(szMoveDest,_T("\\"));
							_tcscat(szMoveSrc,_T("\\"));
							nDirLevel++;
							pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
							pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
							_tcscpy(pszSrcDirPointer,_T("*.*"));
							hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
							if (hDestFile == INVALID_HANDLE_VALUE)
							{
								FoundFile = FALSE;
								continue;
							}
							FirstTime = TRUE;
						}
					}
				}
			}
		}
		if (MoveStatus)
			ConOutResPrintf(STRING_MOVE_ERROR1);
		else
			ConOutResPrintf(STRING_MOVE_ERROR2);
	}
	while ((!OnlyOneFile || dwMoveStatusFlags & MOVE_SRC_CURRENT_IS_DIR ) &&
			!(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) &&
			FindNextFile (hFile, &findBuffer));
	FindClose (hFile);
	
	freep (arg);
	return 0;
}
Exemple #25
0
bool CGeppetto::BuildFromInputScript(const tstring& sScript)
{
	FILE* fp = tfopen_asset(GetPath(sScript), "r");
	if (!fp)
	{
		TError("Could not read input script '" + sScript + "'\n");
		return false;
	}

	std::shared_ptr<CData> pData(new CData());
	CDataSerializer::Read(fp, pData.get());

	CData* pOutput = pData->FindChild("Output");
	if (!pOutput)
	{
		TError("Could not find Output section in input script '" + sScript + "'\n");
		return false;
	}

	CData* pGame = pData->FindChild("Game");
	if (!pGame)
	{
		TError("Could not find Game section in input script '" + sScript + "'\n");
		return false;
	}

	t.SetGameDirectory(FindAbsolutePath(GetPath(pGame->GetValueString())));

	tstring sOutputDir = ToForwardSlashes(pOutput->GetValueString());
	t.SetOutputDirectory(GetDirectory(sOutputDir));
	t.SetOutputFile(GetFilename(sOutputDir));
	t.SetScriptDirectory(GetDirectory((GetPath(sScript))));

	m_sOutput = FindAbsolutePath(t.GetGameDirectory() + T_DIR_SEP + pOutput->GetValueString());

	CData* pSceneAreas = pData->FindChild("SceneAreas");
	CData* pMesh = pData->FindChild("Mesh");
	CData* pPhysics = pData->FindChild("Physics");
	CData* pPhysicsShapes = pData->FindChild("PhysicsShapes");

	// Find all file modification times.
	time_t iScriptModificationTime = GetFileModificationTime(sScript.c_str());
	time_t iOutputModificationTime = GetFileModificationTime(m_sOutput.c_str());

	tmap<tstring, time_t> aiSceneModificationTimes;

	if (pSceneAreas)
	{
		for (size_t i = 0; i < pSceneAreas->GetNumChildren(); i++)
		{
			CData* pArea = pSceneAreas->GetChild(i);

			if (pArea->GetKey() != "Area")
				continue;

			tstring sFile = pArea->FindChildValueString("File");
			TAssert(sFile.length());
			if (!sFile.length())
				continue;

			auto it = aiSceneModificationTimes.find(sFile);
			if (it == aiSceneModificationTimes.end())
				aiSceneModificationTimes[sFile] = GetFileModificationTime(sFile.c_str());
		}
	}

	time_t iInputModificationTime = 0;
	if (pMesh)
		iInputModificationTime = GetFileModificationTime(pMesh->GetValueString().c_str());
	time_t iPhysicsModificationTime = 0;
	if (pPhysics)
		iPhysicsModificationTime = GetFileModificationTime(pPhysics->GetValueString().c_str());

	bool bRecompile = false;
	if (iScriptModificationTime > iOutputModificationTime)
		bRecompile = true;
	else if (iInputModificationTime > iOutputModificationTime)
		bRecompile = true;
	else if (iPhysicsModificationTime > iOutputModificationTime)
		bRecompile = true;
	else if (m_iBinaryModificationTime > iOutputModificationTime)
		bRecompile = true;
	else
	{
		for (auto it = aiSceneModificationTimes.begin(); it != aiSceneModificationTimes.end(); it++)
		{
			if (it->second > iOutputModificationTime)
			{
				bRecompile = true;
				break;
			}
		}
	}

	if (!bRecompile)
	{
		if (m_bForceCompile)
		{
			TMsg("Forcing rebuild even though no changes detected.\n");
		}
		else
		{
			TMsg("No changes detected. Skipping '" + m_sOutput + "'.\n\n");
			return true;
		}
	}

	CData* pGlobalTransforms = pData->FindChild("UseGlobalTransforms");
	if (pGlobalTransforms)
		t.UseGlobalTransformations();
	else
		t.UseLocalTransformations();

	t.UseUV();
	t.UseNormals();

	if (pMesh)
	{
		tstring sExtension = pMesh->GetValueString().substr(pMesh->GetValueString().length()-4);
		if (sExtension == ".png")
		{
			TUnimplemented();	// Not updated since the switch to materials.
			int x, y, n;
			unsigned char* pData = stbi_load((GetPath(pMesh->GetValueString())).c_str(), &x, &y, &n, 0);

			if (!pData)
			{
				TError("Couldn't load '" + pMesh->GetValueString() + "', reason: " + stbi_failure_reason() + "\n");
				return false;
			}

			stbi_image_free(pData); // Don't need it, just need the dimensions.

			Vector vecUp = Vector(0, 0, 0.5f) * ((float)y/100);
			Vector vecLeft = Vector(0, 0.5f, 0) * ((float)x/100);

			t.UseNormals(false);

			if (IsAbsolutePath(pMesh->GetValueString()))
				t.AddMaterial(GetPath(pMesh->GetValueString()));
			else
				t.AddMaterial(t.GetOutputDirectory() + "/" + pMesh->GetValueString(), GetPath(pMesh->GetValueString()));
			t.AddVertex(0, -vecLeft + vecUp, Vector2D(0.0f, 1.0f));
			t.AddVertex(0, -vecLeft - vecUp, Vector2D(0.0f, 0.0f));
			t.AddVertex(0, vecLeft - vecUp, Vector2D(1.0f, 0.0f));

			t.AddVertex(0, -vecLeft + vecUp, Vector2D(0.0f, 1.0f));
			t.AddVertex(0, vecLeft - vecUp, Vector2D(1.0f, 0.0f));
			t.AddVertex(0, vecLeft + vecUp, Vector2D(1.0f, 1.0f));
		}
		else if (sExtension == ".mat")
		{
			CMaterialHandle hMaterial(pMesh->GetValueString());
			if (!hMaterial.IsValid())
			{
				TError("Input material  '" + pMesh->GetValueString() + "' does not exist or is invalid.\n");
				return false;
			}

			if (!hMaterial->m_ahTextures.size())
			{
				TError("Input material  '" + pMesh->GetValueString() + "' has no textures.\n");
				return false;
			}

			float w = (float)hMaterial->m_ahTextures[0]->m_iWidth;
			float h = (float)hMaterial->m_ahTextures[0]->m_iHeight;

			Vector vecUp = Vector(0, 0.5f, 0) * (h/hMaterial->m_iTexelsPerMeter);
			Vector vecRight = Vector(0, 0, 0.5f) * (w/hMaterial->m_iTexelsPerMeter);

			t.UseNormals(false);

			t.AddMaterial(pMesh->GetValueString());

			t.AddVertex(0, -vecRight + vecUp, Vector2D(0.0f, 1.0f));
			t.AddVertex(0, -vecRight - vecUp, Vector2D(0.0f, 0.0f));
			t.AddVertex(0, vecRight - vecUp, Vector2D(1.0f, 0.0f));

			t.AddVertex(0, -vecRight + vecUp, Vector2D(0.0f, 1.0f));
			t.AddVertex(0, vecRight - vecUp, Vector2D(1.0f, 0.0f));
			t.AddVertex(0, vecRight + vecUp, Vector2D(1.0f, 1.0f));
		}
		else
		{
			TMsg("Reading model '" + GetPath(pMesh->GetValueString()) + "' ...");
			std::shared_ptr<CConversionScene> pScene(new CConversionScene());
			CModelConverter c(pScene.get());

			if (!c.ReadModel(GetPath(pMesh->GetValueString())))
			{
				TError("Couldn't read '" + GetPath(pMesh->GetValueString()) + "'.\n");
				return false;
			}
			TMsg(" Done.\n");

			TMsg("Building toy mesh ...");
			LoadSceneIntoToy(pScene.get(), &t);
			TMsg(" Done.\n");
		}
	}

	if (pPhysics)
	{
		TMsg("Reading physics model '" + GetPath(pPhysics->GetValueString()) + "' ...");
		std::shared_ptr<CConversionScene> pScene(new CConversionScene());
		CModelConverter c(pScene.get());

		if (!c.ReadModel(GetPath(pPhysics->GetValueString())))
		{
			TError("Couldn't read '" + GetPath(pPhysics->GetValueString()) + "'.\n");
			return false;
		}
		TMsg(" Done.\n");

		TMsg("Building toy physics model ...");
		LoadSceneIntoToyPhysics(pScene.get(), &t);
		TMsg(" Done.\n");
	}

	if (pPhysicsShapes)
	{
		for (size_t i = 0; i < pPhysicsShapes->GetNumChildren(); i++)
		{
			CData* pShape = pPhysicsShapes->GetChild(i);

			TAssert(pShape->GetKey() == "Box");
			if (pShape->GetKey() != "Box")
				continue;

			TRS trs = pShape->GetValueTRS();

			t.AddPhysBox(trs);
		}
	}

	if (pSceneAreas)
		LoadSceneAreas(pSceneAreas);

	return Compile();
}
Exemple #26
0
void ElDorito::Initialize()
{
	::CreateDirectoryA(GetDirectory().c_str(), NULL);

	// init our command modules
	Modules::ElModules::Instance();

	// load variables/commands from cfg file
	Modules::CommandMap::Instance().ExecuteCommand("Execute dewrito_prefs.cfg");
	Modules::CommandMap::Instance().ExecuteCommand("Execute autoexec.cfg"); // also execute autoexec, which is a user-made cfg guaranteed not to be overwritten by ElDew

	//This should be removed when we can save binds
	Modules::CommandMap::Instance().ExecuteCommand("Bind CAPITAL +VoIP.Talk");

	// Parse command-line commands
	int numArgs = 0;
	LPWSTR* szArgList = CommandLineToArgvW(GetCommandLineW(), &numArgs);
	bool usingLauncher = Modules::ModuleGame::Instance().VarSkipLauncher->ValueInt == 1;
	bool skipKill = false;
	bool dedicated = false;

	if( szArgList && numArgs > 1 )
	{
		std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;

		for( int i = 1; i < numArgs; i++ )
		{
			std::wstring arg = std::wstring(szArgList[i]);
			if( arg.compare(0, 1, L"-") != 0 ) // if it doesn't start with -
				continue;

#ifndef _DEBUG
			if (arg.compare(L"-launcher") == 0)
				usingLauncher = true;
#endif

#ifdef _DEBUG
			if (arg.compare(L"-dedicated") == 0)
			{
				dedicated = true;
			}
#endif

			if (arg.compare(L"-multiInstance") == 0)
			{
				skipKill = true;
			}

			size_t pos = arg.find(L"=");
			if( pos == std::wstring::npos || arg.length() <= pos + 1 ) // if it doesn't contain an =, or there's nothing after the =
				continue;

			std::string argname = converter.to_bytes(arg.substr(1, pos - 1));
			std::string argvalue = converter.to_bytes(arg.substr(pos + 1));

			Modules::CommandMap::Instance().ExecuteCommand(argname + " \"" + argvalue + "\"", true);
		}
	}

	if (dedicated)
	{
		// Commenting this out for now because it makes testing difficult
		/*DetourRestoreAfterWith();
		DetourTransactionBegin();
		DetourUpdateThread(GetCurrentThread());
		DetourAttach((PVOID*)&Video_InitD3D, &hooked_Video_InitD3D);

		if (DetourTransactionCommit() != NO_ERROR) {
		return;
		}*/
		Patches::Network::ForceDedicated();
	}

	// Language patch
	Patch(0x2333FD, { (uint8_t)Modules::ModuleGame::Instance().VarLanguageID->ValueInt }).Apply();

	setWatermarkText("ElDewrito | Version: " + Utils::Version::GetVersionString() + " | Build Date: " __DATE__);

#ifndef _DEBUG
	if (!usingLauncher) // force release builds to use launcher, simple check so its easy to get around if needed
	{
		MessageBox(GetConsoleWindow(), "Please run Halo Online using the ElDewrito launcher.\nIt should be named DewritoUpdater.exe.", "ElDewrito", MB_OK | MB_ICONINFORMATION);
		TerminateProcess(GetCurrentProcess(), 0);
	}
#endif

	if (!skipKill)
	{
		int ourPid = GetCurrentProcessId();
		killProcessByName("eldorado.exe", ourPid);
		killProcessByName("custom_menu.exe", ourPid);
		killProcessByName("DewritoUpdater.exe", ourPid);
	}

	// Initialize server modules
	Server::Chat::Initialize();
	CreateThread(0, 0, StartRconWebSocketServer, 0, 0, 0);
}
bool CProjectSettings::CloseProjectSettings()
{
	// check bool if settings have changed
	if ( IsChangedSinceLastSave ) 
	{
		// popup to ask if save - yes/no/(cancel)
		int answer = AfxMessageBox( "Do you want to save the changes in the project?", MB_YESNOCANCEL );

		// do what the user clicked
		if (answer == IDCANCEL)
		{
			// Cancel: we dont want to do anything...
			return FALSE;
		}
		else if ( answer == IDYES )
		{
			// get the filename
			StdString fileName = getSaveFileName();

			// check if it is a valid path
			if ( fileName.length() == 0 )
			{
				// Selecting a file
				StdString typeExtension( _T("gdsprj") );
				StdString filterStr = "GDS project files (*." + typeExtension + ")|*." + typeExtension + "||"; 
				CFileDialog myFileDialog(FALSE, typeExtension, NULL, OFN_ENABLESIZING|OFN_EXPLORER|OFN_OVERWRITEPROMPT, filterStr);

				// set the file selector default dir to project dir
				myFileDialog.m_ofn.lpstrInitialDir = GetDirectory();

				// Adding it to the listBox
				if ( myFileDialog.DoModal() == IDOK ) 
				{
					// get the selected file with path
					fileName = myFileDialog.GetPathName();
					
					// saving the filename in the object as well
					setSaveFileName( fileName );
				}
				else
				{
					// the user clicked cancel: exiting save dialog
					return FALSE;
				}
			}

			// send message to make projectloader serialize us.
			CHashString hszProjectLoader(_T("CProjectLoadSave"));
			CHashString hszNewParticleSaveFilepath( fileName );
			static DWORD msgHash_SaveFile = CHashString(_T("SaveFile")).GetUniqueID();
			DWORD result = EngineGetToolBox()->SendMessage(msgHash_SaveFile, sizeof(TCHAR *), (void *)hszNewParticleSaveFilepath.GetString(), 0, &hszProjectLoader);

			// mark settings as saved
			IsChangedSinceLastSave = FALSE;
		}
		else
		{
			// we are here, if the user clicked NO SAVE
			// then we don't save anything, but return TRUE
			// that will lead to close GDS
			return TRUE;
		}
	}
	// Closing project destroys consistency	
	SetSettingsStateConsistency( FALSE );
	
	return TRUE;
}
NS_IMETHODIMP nsAbManager::DeleteAddressBook(const nsACString &aURI)
{
  // Find the address book
  nsresult rv;

  nsCOMPtr<nsIAbDirectory> directory;
  rv = GetDirectory(aURI, getter_AddRefs(directory));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIAbDirectory> rootDirectory;
  rv = GetRootDirectory(getter_AddRefs(rootDirectory));
  NS_ENSURE_SUCCESS(rv, rv);

  // Go through each of the children of the address book
  // (so, the mailing lists) and remove their entries from
  // the look up table.
  nsCOMPtr<nsISimpleEnumerator> enumerator;
  rv = directory->GetChildNodes(getter_AddRefs(enumerator));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsISupports> item;
  nsCOMPtr<nsIAbDirectory> childDirectory;
  bool hasMore = false;
  while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMore)) && hasMore)
  {
    rv = enumerator->GetNext(getter_AddRefs(item));
    NS_ENSURE_SUCCESS(rv, rv);

    childDirectory = do_QueryInterface(item, &rv);
    if (NS_SUCCEEDED(rv))
    {
      nsCString childURI;
      rv = childDirectory->GetURI(childURI);
      NS_ENSURE_SUCCESS(rv, rv);

      mAbStore.Remove(childURI);
    }
  }

  mAbStore.Remove(aURI);

  bool isMailList;
  rv = directory->GetIsMailList(&isMailList);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!isMailList)
    // If we're not a mailing list, then our parent
    // must be the root address book directory.
    return rootDirectory->DeleteDirectory(directory);

  nsCString parentUri;
  parentUri.Append(aURI);
  PRInt32 pos = parentUri.RFindChar('/');

  // If we didn't find a /, we're in trouble.
  if (pos == -1)
    return NS_ERROR_FAILURE;

  parentUri = StringHead(parentUri, pos);
  nsCOMPtr<nsIAbDirectory> parentDirectory;
  rv = GetDirectory(parentUri, getter_AddRefs(parentDirectory));
  NS_ENSURE_SUCCESS(rv, rv);

  return parentDirectory->DeleteDirectory(directory);
}
Exemple #29
0
void MythSystemWindows::Fork(time_t timeout)
{
    QString LOC_ERR = QString("myth_system('%1'): Error: ").arg(GetLogCmd());

    // For use in the child
    char locerr[MAX_BUFLEN];
    strncpy(locerr, (const char *)LOC_ERR.toUtf8().constData(), MAX_BUFLEN);
    locerr[MAX_BUFLEN-1] = '\0';

    VERBOSE(VB_SYSTEM|VB_EXTRA, QString("Launching: %1").arg(GetLogCmd()));

    GetBuffer(0)->setBuffer(0);
    GetBuffer(1)->setBuffer(0);
    GetBuffer(2)->setBuffer(0);

    HANDLE p_stdin[2] = { NULL, NULL };
    HANDLE p_stdout[2] = { NULL, NULL };
    HANDLE p_stderr[2] = { NULL, NULL };

    SECURITY_ATTRIBUTES saAttr; 
    STARTUPINFO si;

    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
        
    // Set the bInheritHandle flag so pipe handles are inherited. 
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
    saAttr.bInheritHandle = TRUE; 
    saAttr.lpSecurityDescriptor = NULL; 

    /* set up pipes */
    if( GetSetting("UseStdin") )
    {
        if (!CreatePipe(&p_stdin[0], &p_stdin[1], &saAttr, 0)) 
        {
            VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stdin pipe() failed"));
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the write handle to the pipe for STDIN is not inherited. 
            if (!SetHandleInformation(p_stdin[1], HANDLE_FLAG_INHERIT, 0))
            {
                VERBOSE(VB_SYSTEM|VB_IMPORTANT,
                            (LOC_ERR + "stdin inheritance error"));
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdInput = p_stdin[0];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }


    if( GetSetting("UseStdout") )
    {
        if (!CreatePipe(&p_stdout[0], &p_stdout[1], &saAttr, 0)) 
        {
            VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stdout pipe() failed"));
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the read handle to the pipe for STDOUT is not inherited.
            if (!SetHandleInformation(p_stdout[0], HANDLE_FLAG_INHERIT, 0))
            {
                VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stdout inheritance error"));
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdOutput = p_stdout[1];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    if( GetSetting("UseStderr") )
    {
        if (!CreatePipe(&p_stderr[0], &p_stderr[1], &saAttr, 0)) 
        {
            VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stderr pipe() failed"));
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the read handle to the pipe for STDERR is not inherited.
            if (!SetHandleInformation(p_stderr[0], HANDLE_FLAG_INHERIT, 0))
            {
                VERBOSE(VB_IMPORTANT|VB_SYSTEM,
                            (LOC_ERR + "stderr inheritance error"));
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdError = p_stderr[2];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    // set up command args
    QString cmd = GetCommand() + " " + GetArgs().join(" ");
    if (GetSetting("UseShell"))
        cmd.prepend("cmd.exe /c ");

    SetCommand( cmd );

    QByteArray cmdUTF8 = GetCommand().toUtf8();
    TCHAR *command = TEXT((char *)cmdUTF8.constData());

    const char *directory = NULL;
    QString dir = GetDirectory();
    if (GetSetting("SetDirectory") && !dir.isEmpty())
        directory = strdup(dir.toUtf8().constData());

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));

    m_timeout = timeout;
    if( timeout )
        m_timeout += time(NULL);

    bool success = CreateProcess(NULL, 
                    command,       // command line 
                    NULL,          // process security attributes 
                    NULL,          // primary thread security attributes 
                    TRUE,          // handles are inherited 
                    0,             // creation flags 
                    NULL,          // use parent's environment 
                    directory,     // use parent's current directory 
                   &si,            // STARTUPINFO pointer 
                   &pi);           // receives PROCESS_INFORMATION 

    if (!success)
    {
        VERBOSE(VB_IMPORTANT|VB_SYSTEM, (LOC_ERR + "CreateProcess() failed"));
        SetStatus( GENERIC_EXIT_NOT_OK );
    }
    else
    {
        /* parent */
        m_child = pi.hProcess;
        SetStatus( GENERIC_EXIT_RUNNING );

        VERBOSE(VB_SYSTEM|VB_EXTRA,
                QString("Managed child (Handle: %1) has started! "
                        "%2%3 command=%4, timeout=%5")
                    .arg((long long)m_child) 
                    .arg(GetSetting("UseShell") ? "*" : "")
                    .arg(GetSetting("RunInBackground") ? "&" : "")
                    .arg(GetLogCmd()) .arg(timeout));

        /* close unused pipe ends */
        CLOSE(p_stdin[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[1]);

        // store the rest
        m_stdpipe[0] = p_stdin[1];
        m_stdpipe[1] = p_stdout[0];
        m_stdpipe[2] = p_stderr[0];

        // clean up the memory use
        if( directory )
            free((void *)directory);
    }

    /* Parent */
    if( GetStatus() != GENERIC_EXIT_RUNNING )
    {
        CLOSE(p_stdin[0]);
        CLOSE(p_stdin[1]);
        CLOSE(p_stdout[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[0]);
        CLOSE(p_stderr[1]);
    }
}
/******************************************************************************************
 * Index ������ �����Ѵ�
 * @param IndexFile �� �ε��� ���ϸ�
 * @param Mode �Ӽ�. "r" �б� ����, "w" ��������(������), "w+" ���� + ���� + �б�, 
 *                   "r+" �б� + ����(���� ����)
 */
bool CVFS_Manager::Open (const char *IndexFile, const char * __Mode)
{
	m_sIdxFileName = IndexFile;
	m_sBasePath = GetDirectory (m_sIdxFileName.c_str ()); /// "\"���ڱ��� ����
    /// Binary Mode�� �����
	_fmode = _O_BINARY;
	/// ���� ���� �������� ���

	char Mode[ 16 ];
	__CheckOpenMode ( __Mode, Mode );

	m_strIdxOpenMode = Mode;

	if(strcmp (Mode, "w+") == 0)
	{
		CFileMode::CheckMode (IndexFile, CFileMode::MODE_READWRITE, true) ;
		if( (m_fpIDX = fopen (IndexFile, Mode)) )	/// "w+"�� ����� ��Ʈ���� �׻� ������
		{
			m_vecVFS.clear ();

			return __WriteBlankIndexFile (); // �׳� �� Ventry�� �ϳ� �����
		}
	}
	else if(strcmp (Mode, "mr") == 0 || strcmp (Mode, "mr+") == 0 )
	{
		/// �б� �۹̼��� �˻��ϰ� ������ �б�� �ٲ۴�
		CFileMode::CheckMode (IndexFile, CFileMode::MODE_READ, true) ;

		if( CFileMode::CheckMode (IndexFile, CFileMode::MODE_EXISTS)  
			&& (m_fpIDX = fopen (IndexFile, Mode + 1)))
		{
			return __ReadVEntry ();
		}
	}
	else if(strcmp (Mode, "r+") == 0)
	{
		CFileMode::CheckMode (IndexFile, CFileMode::MODE_READWRITE, true) ;

		if( CFileMode::CheckMode (IndexFile, CFileMode::MODE_EXISTS) 
			&& (m_fpIDX = fopen (IndexFile, Mode)) )
		{
			return __ReadVEntry ();
		}
	}
	else if(strcmp (Mode, "r") == 0)
	{
		if( !CFileMode::CheckMode (IndexFile, CFileMode::MODE_EXISTS) )
			return false;

		/// �б� �۹̼��� �˻��ϰ� ������ �б�� �ٲ۴�
		CFileMode::CheckMode (IndexFile, CFileMode::MODE_READ, true) ;

		if( (m_fpIDX = fopen (IndexFile, Mode)) )
		{
			return __ReadVEntry ();
		}
	}
	
		
	return false;
}