Beispiel #1
0
static void _stdcall SaveGame2() {
	char buf[MAX_PATH];
	GetSavePath(buf, "gv");

	dlog_f("Saving game: %s\r\n", DL_MAIN, buf);

	DWORD size, unused = 0;
	HANDLE h = CreateFileA(buf, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
	if (h != INVALID_HANDLE_VALUE) {
		SaveGlobals(h);
		WriteFile(h, &unused, 4, &size, 0);
		unused++;
		WriteFile(h, &unused, 4, &size, 0);
		PerksSave(h);
		SaveArrays(h);
		CloseHandle(h);
	} else {
		dlogr("ERROR creating sfallgv!", DL_MAIN);
		DisplayConsoleMessage(SaveSfallDataFailMsg);
		PlaySfx("IISXXXX1");
	}
	GetSavePath(buf, "fs");
	h = CreateFileA(buf, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
	if (h != INVALID_HANDLE_VALUE) {
		FileSystemSave(h);
	}
	CloseHandle(h);
}
Beispiel #2
0
bool TextScanner::SaveFile( const string &fName, bool bAddBasePath /*= true*/ )
{
	string f;

	string lineFeed = "\r\n";
	if (bAddBasePath)
	{
		f = GetSavePath()+fName;
	} else
	{
		f = fName;
	}
	FILE *fp = fopen( f.c_str(), "wb");

	if (!fp)
	{
		LogError("Unable to save data");
		return false;
	}

	for (uint32 i=0; i < m_lines.size(); i++)
	{
		fwrite(m_lines[i].c_str(), m_lines[i].size(), 1, fp);
		fwrite(lineFeed.c_str(), lineFeed.size(), 1, fp);
	}
	
	fclose(fp);
	return true;
}
void RemoveFile( std::string fileName, bool bAddSavePath)
{
	
	if (bAddSavePath)
	{
		fileName = GetSavePath()+fileName;
	}

	if (unlink(fileName.c_str()) == -1)
	{
		switch (errno)
		{
		case EACCES: 
			LogMsg("Warning: Unable to delete file %s, no access", fileName.c_str());
			break;
		case EBUSY: 
			LogError("Warning: Unable to delete file %s, file is being used", fileName.c_str());
			break;
		case EPERM: 
			LogMsg("Warning: Unable to delete file %s, may be a dir", fileName.c_str());
			break;
		case EROFS: 
			LogMsg("Warning: Unable to delete file %s, File system is read only", fileName.c_str());
			break;
		default:
			//LogMsg("Warning: Unable to delete file %s, unknown error", fileName.c_str());
			//file doesn't exist
			break;
		}
	}
}
Beispiel #4
0
	CString GetPath(const CString & sChannel)
	{
		CString sBuffer = m_pUser->GetUserName() + sChannel.AsLower();
		CString sRet = GetSavePath();
		sRet += "/" + CBlowfish::MD5(sBuffer, true);
		return(sRet);
	}
Beispiel #5
0
	CString GetPath()
	{
		CString sBuffer = m_pUser->GetUserName();
		CString sRet = GetSavePath();
		sRet += "/.znc-away-" + CBlowfish::MD5(sBuffer, true);
		return(sRet);
	}
Beispiel #6
0
	virtual void OnModCTCP(const CString& sMessage) {
		if (sMessage.Equals("DCC RESUME ", false, 11)) {
			CString sFile = sMessage.Token(2);
			unsigned short uResumePort = sMessage.Token(3).ToUShort();
			unsigned long uResumeSize = sMessage.Token(4).ToULong();

			set<CSocket*>::const_iterator it;
			for (it = BeginSockets(); it != EndSockets(); ++it) {
				CDCCSock* pSock = (CDCCSock*) *it;

				if (pSock->GetLocalPort() == uResumePort) {
					if (pSock->Seek(uResumeSize)) {
						PutModule("DCC -> [" + pSock->GetRemoteNick() + "][" + pSock->GetFileName() + "] - Attempting to resume from file position [" + CString(uResumeSize) + "]");
						PutUser(":*[email protected] PRIVMSG " + m_pUser->GetNick() + " :\001DCC ACCEPT " + sFile + " " + CString(uResumePort) + " " + CString(uResumeSize) + "\001");
					} else {
						PutModule("DCC -> [" + m_pUser->GetNick() + "][" + sFile + "] Unable to find send to initiate resume.");
					}
				}

			}
		} else if (sMessage.Equals("DCC SEND ", false, 9)) {
			CString sLocalFile = CDir::CheckPathPrefix(GetSavePath(), sMessage.Token(2));
			if (sLocalFile.empty()) {
				PutModule("Bad DCC file: " + sMessage.Token(2));
			}
			unsigned long uLongIP = sMessage.Token(3).ToULong();
			unsigned short uPort = sMessage.Token(4).ToUShort();
			unsigned long uFileSize = sMessage.Token(5).ToULong();
			GetFile(m_pUser->GetCurNick(), CUtils::GetIP(uLongIP), uPort, sLocalFile, uFileSize);
		}
	}
Beispiel #7
0
	void SetLogFilePath(CString sPath) {
		if (sPath.empty()) {
			sPath = GetSavePath() + "/znc.log";
		}

		CFile LogFile(sPath);
		CString sLogDir = LogFile.GetDir();
		struct stat ModDirInfo;
		CFile::GetInfo(GetSavePath(), ModDirInfo);
		if (!CFile::Exists(sLogDir)) {
			CDir::MakeDir(sLogDir, ModDirInfo.st_mode);
		}

		m_sLogFile = sPath;
		SetNV("path", sPath);
	}
/*******************************************************************
 * Function Name: PrintStats
 * Return Type 	: int
 * Created On	: Oct 27, 2013
 * Created By 	: hrushi
 * Comments		: Prints the Mean, Median, Standard Dev. the EM Score
 * Arguments	:
 *******************************************************************/
int GroundTruth::PrintStats(  const Args& args  ) const
{
	vector<double> AllScoreVal;

	string ScoreSavePath = GetSavePath( args );
	cout << "Saving to: " << ScoreSavePath << endl;

	cv::FileStorage fScore;
	fScore.open(ScoreSavePath, cv::FileStorage::WRITE);

	AllScoreVal.reserve(m_vScores.size());

	for( auto ClassName : RGN_TYPES )
	{
		vector<double> ClassScoreVal;

		for(const auto& val : m_vScores )
		{
			AllScoreVal.push_back( val.second );
			ClassScoreVal.push_back( val.second );
		}

		PrintAllVals(args, fScore, ClassName, ClassScoreVal);
	}

	fScore.release();


	PrintStats(args, AllScoreVal);

	return EXIT_SUCCESS;
}
Beispiel #9
0
void CRawLogMod::PutLog(const CString& sLine)
{
	std::ofstream ofLog;
	std::stringstream ssPath;
	time_t curtime;
	tm* timeinfo;

	time(&curtime);
	timeinfo = gmtime(&curtime);

	ssPath.fill('0');
	ssPath << GetSavePath() << "/"
	   << std::setw(4) << (timeinfo->tm_year + 1900)
	   << std::setw(2) << (timeinfo->tm_mon + 1)
	   << std::setw(2) << (timeinfo->tm_mday)
	   << ".log";

	ofLog.open(ssPath.str().c_str(), std::ofstream::app);

	if (ofLog.good())
	{
		ofLog.fill('0');
		char ts [15];
		sprintf(ts, "%i ", (int)time(NULL));
		ofLog << ts << sLine << endl;
	}
}
Beispiel #10
0
	QPair<quint64, quint64> AddTorrent::GetAvailableSpaceInDestination ()
	{
		try
		{
#ifdef Q_OS_WIN32
			const auto space = boost::filesystem::space (std::string (GetSavePath ().toUtf8 ().constData ()));
#else
			const auto space = boost::filesystem::space (GetSavePath ().toStdWString ());
#endif
			return qMakePair<quint64, quint64> (space.available, space.capacity);
		}
		catch (...)
		{
			return qMakePair<quint64, quint64> (-1, -1);
		}
	}
Beispiel #11
0
	virtual bool OnLoad(const CString & sArgs, CString & sMessage) {
		CString sTarget = GetNV("target");
		if (sTarget.Equals("syslog"))
			m_eLogMode = LOG_TO_SYSLOG;
		else if (sTarget.Equals("both"))
			m_eLogMode = LOG_TO_BOTH;
		else if (sTarget.Equals("file"))
			m_eLogMode = LOG_TO_FILE;
		else
			m_eLogMode = LOG_TO_FILE;

		m_sLogFile = GetSavePath() + "/znc.log";

		Log("Logging started. ZNC PID[" + CString(getpid()) + "] UID/GID[" + CString(getuid()) + ":" + CString(getgid()) + "]");
		return true;
	}
Beispiel #12
0
bool MainWindow::PromptSaveLog()
{
  QString saveFilename = GetSavePath();

  if(saveFilename != "")
  {
    if(m_Ctx->IsLogLocal() && !QFileInfo(m_Ctx->LogFilename()).exists())
    {
      RDDialog::critical(NULL, tr("File not found"),
                         tr("Logfile %1 couldn't be found, cannot save.").arg(m_Ctx->LogFilename()));
      return false;
    }

    bool success = false;

    if(m_Ctx->IsLogLocal())
    {
      // we copy the (possibly) temp log to the desired path, but the log item remains referring to
      // the original path.
      // This ensures that if the user deletes the saved path we can still open or re-save it.
      success = QFile::copy(m_Ctx->LogFilename(), saveFilename);
    }
    else
    {
      // TODO Remote
      // m_Core.Renderer.CopyCaptureFromRemote(m_Core.LogFileName, saveFilename, this);
    }

    if(!success)
    {
      RDDialog::critical(NULL, tr("File not found"), tr("Couldn't save to %1").arg(saveFilename));
      return false;
    }

    PersistantConfig::AddRecentFile(m_Ctx->Config.RecentLogFiles, saveFilename, 10);
    PopulateRecentFiles();
    SetTitle(saveFilename);

    // we don't prompt to save on closing - if the user deleted the log that we just saved, then
    // that is up to them.
    m_SavedTempLog = true;

    return true;
  }

  return false;
}
Beispiel #13
0
bool VariantDB::Save(const string &fileName, bool bAddBasePath)
{
	
	string f;

	if (bAddBasePath)
	{
		f = GetSavePath()+fileName;
	} else
	{
		f = fileName;
	}

	FILE *fp = fopen( f.c_str(), "wb");
	
	if (!fp)
	{
		LogError("Unable to save data");
		return false;
	}
	uint32 version = C_VARIANT_DB_FILE_VERSION;
	fwrite(&version, sizeof(uint32), 1, fp);

	dataList::iterator itor = m_data.begin();
	
	while (itor != m_data.end())
	{
		Variant *pV = itor->second;
		
		if (!pV->Save(fp, itor->first))
		{
			LogError("Unable to save data");
			fclose(fp);
			return false;
		}

		itor++;
	}

	//add out done marker
	uint32 doneMarker = Variant::TYPE_UNUSED;
	fwrite(&doneMarker, sizeof(uint32), 1, fp);

	fclose(fp);
	return true;
}
Beispiel #14
0
void CLogMod::PutLog(const CString& sLine, const CString& sWindow /*= "Status"*/)
{
	CString sPath;
	time_t curtime;
	tm* timeinfo;
	char buffer[1024];

	time(&curtime);
	// Don't forget the user's timezone offset
	setenv("TZ", m_pUser->GetTimezone().c_str(), 1);
	timeinfo = localtime(&curtime);

	// Generate file name
	if (!strftime(buffer, sizeof(buffer), m_sLogPath.c_str(), timeinfo))
	{
		DEBUG("Could not format log path [" << sPath << "]");
		return;
	}
	sPath = buffer;

	// $WINDOW has to be handled last, since it can contain %
	sPath.Replace("$NETWORK", (m_pNetwork ? m_pNetwork->GetName() : "znc"));
	sPath.Replace("$WINDOW", sWindow.Replace_n("/", "?"));
	sPath.Replace("$USER", (m_pUser ? m_pUser->GetUserName() : "UNKNOWN"));

	// Check if it's allowed to write in this specific path
	sPath = CDir::CheckPathPrefix(GetSavePath(), sPath);
	if (sPath.empty())
	{
		DEBUG("Invalid log path ["<<m_sLogPath<<"].");
		return;
	}

	CFile LogFile(sPath);
	CString sLogDir = LogFile.GetDir();
	if (!CFile::Exists(sLogDir)) CDir::MakeDir(sLogDir);
	if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))
	{
		snprintf(buffer, sizeof(buffer), "[%02d:%02d:%02d] ",
				timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);

		LogFile.Write(buffer + sLine + "\n");
	} else
		DEBUG("Could not open log file [" << sPath << "]: " << strerror(errno));
}
Beispiel #15
0
//                              CDirList::SaveFile()
//
//  generate file name based on output dir and time
//    file name begins with dir name and ends 
//    with ".obr" (osiris batch report)
//
//
bool CDirList::SaveFile()
{
  bool bRtn = CreateFileName();
  if(bRtn)
  {
    bRtn = SaveFile(m_sFileName);
  }
  if(bRtn)
  {
    m_sDirLoad = GetSavePath();
  }
  else
  {
    m_sDirLoad.Empty();
    m_sDirSave.Empty();
  }
  return bRtn;
}
Beispiel #16
0
	void GetCommand(const CString& sLine) {
		CString sFile = sLine.Token(1);
		CString sAllowedPath = GetSavePath();
		CString sAbsolutePath;

		if (sFile.empty()) {
			PutModule("Usage: Get <file>");
			return;
		}

		sAbsolutePath = CDir::CheckPathPrefix(sAllowedPath, sFile);

		if (sAbsolutePath.empty()) {
			PutModule("Illegal path.");
			return;
		}

		SendFile(m_pUser->GetNick(), sFile);
	}
Beispiel #17
0
bool CDirList::LoadFile(const wxString &sFileName)
{
  Cleanup();
  bool bRtn = nwxXmlPersist::LoadFile(sFileName);
  if(bRtn)
  {
    m_sFileName = sFileName;
    wxFileName fn(m_sFileName);
    m_sDirLoad = fn.GetPath();
    nwxFileUtil::EndWithSeparator(&m_sDirLoad);
    m_parmOsiris.SetOutputDirectory(m_sDirLoad);
    GetSavePath();
  }
  else
  {
    Cleanup();
  }
  return bRtn;
}
Beispiel #18
0
byte * LoadFileIntoMemoryBasic(string fileName, unsigned int *length, bool bUseSavePath, bool bAddBasePath)
{
	*length = 0;

	if (bAddBasePath)
	{
		if (bUseSavePath)
		{
			fileName = GetSavePath() + fileName;
		} else
		{
			fileName = GetBaseAppPath() + fileName;
		}
	}
	
	FILE *fp = fopen(fileName.c_str(), "rb");
	if (!fp)
	{
		//file not found	
		return NULL;
	}

	fseek(fp, 0, SEEK_END);
	*length = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	byte *pData = new byte[(*length) +1];
	
	if (!pData)
	{
		fclose(fp);
		*length = UINT_MAX; //signal a mem error
		return NULL;
	}
	pData[*length] = 0; 
	fread(pData, *length, 1, fp);
	fclose(fp);

	//we add an extra null at the end to be nice, when loading text files this can be useful

	return pData;
}
Beispiel #19
0
	void SendCommand(const CString& sLine) {
		CString sToNick = sLine.Token(1);
		CString sFile = sLine.Token(2);
		CString sAllowedPath = GetSavePath();
		CString sAbsolutePath;

		if ((sToNick.empty()) || (sFile.empty())) {
			PutModule("Usage: Send <nick> <file>");
			return;
		}

		sAbsolutePath = CDir::CheckPathPrefix(sAllowedPath, sFile);

		if (sAbsolutePath.empty()) {
			PutStatus("Illegal path.");
			return;
		}

		SendFile(sToNick, sFile);
	}
Beispiel #20
0
bool CLogMod::OnLoad(const CString& sArgs, CString& sMessage)
{
	// Use load parameter as save path
	m_sLogPath = sArgs;

	// Add default filename to path if it's a folder
	if (GetType() == CModInfo::UserModule) {
		if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == string::npos || m_sLogPath.find("$NETWORK") == string::npos) {
			if (!m_sLogPath.empty()) {
				m_sLogPath += "/";
			}
			m_sLogPath += "$NETWORK_$WINDOW_%Y%m%d.log";
		}
	} else if (GetType() == CModInfo::NetworkModule) {
		if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == string::npos) {
			if (!m_sLogPath.empty()) {
				m_sLogPath += "/";
			}
			m_sLogPath += "$WINDOW_%Y%m%d.log";
		}
	} else {
		if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$USER") == string::npos || m_sLogPath.find("$WINDOW") == string::npos || m_sLogPath.find("$NETWORK") == string::npos) {
			if (!m_sLogPath.empty()) {
				m_sLogPath += "/";
			}
			m_sLogPath += "$USER_$NETWORK_$WINDOW_%Y%m%d.log";
		}
	}

	// Check if it's allowed to write in this path in general
	m_sLogPath = CDir::CheckPathPrefix(GetSavePath(), m_sLogPath);
	if (m_sLogPath.empty())
	{
		sMessage = "Invalid log path ["+m_sLogPath+"].";
		return false;
	} else {
		sMessage = "Logging to ["+m_sLogPath+"].";
		return true;
	}
}
Beispiel #21
0
void CLogMod::PutLog(const CString& sLine, const CString& sWindow /*= "Status"*/)
{
	CString sPath;
	time_t curtime;
	tm* timeinfo;
	char buffer[1024];

	time(&curtime);
	// Don't forget the user's timezone offset (which is in hours and we want seconds)
	curtime += (time_t) (m_pUser->GetTimezoneOffset() * 60 * 60);
	timeinfo = localtime(&curtime);

	/* Generate file name: ~/.znc/users/<user>/moddata/log/WINDOW_YYYYMMDD.log  */
	CString sWindowFixed(sWindow);
	sWindowFixed = sWindowFixed.Replace_n("/", "_");
	sWindowFixed = sWindowFixed.Replace_n("\\", "_");
	sWindowFixed = sWindowFixed.Replace_n(":", "_");
	sWindowFixed = sWindowFixed.Replace_n("*", "_");
	sWindowFixed = sWindowFixed.Replace_n("?", "_");
	sWindowFixed = sWindowFixed.Replace_n("\"", "_");
	sWindowFixed = sWindowFixed.Replace_n("<", "_");
	sWindowFixed = sWindowFixed.Replace_n(">", "_");
	sWindowFixed = sWindowFixed.Replace_n("|", "_");

	sPath = GetSavePath() + "/" + sWindowFixed + "_";
	snprintf(buffer, sizeof(buffer), "%04d%02d%02d.log", timeinfo->tm_year + 1900,
			timeinfo->tm_mon + 1, timeinfo->tm_mday);
	sPath += buffer;

	CFile LogFile(sPath);
	if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))
	{
		snprintf(buffer, sizeof(buffer), "[%02d:%02d:%02d] ",
				timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);

		LogFile.Write(buffer + sLine + "\n");
	} else
		DEBUG("Could not open log file [" << sPath << "]: " << strerror(errno));
}
Beispiel #22
0
	void AddTorrent::MarkExisting (T bool2mark)
	{
		auto rootPath = GetSavePath ();
		if (!rootPath.endsWith ('/'))
			rootPath += '/';

		QList<QModelIndex> queue { QModelIndex {} };
		while (!queue.isEmpty ())
		{
			const auto& idx = queue.takeFirst ();

			if (const auto rc = FilesModel_->rowCount (idx))
				for (int i = 0; i < rc; ++i)
					queue << FilesModel_->index (i, 0, idx);
			else
			{
				const auto& subpath = idx.data (AddTorrentFilesModel::RoleFullPath).toString ();

				const bool exists = QFile::exists (rootPath + subpath);
				FilesModel_->setData (idx, bool2mark (exists), Qt::CheckStateRole);
			}
		}
	}
Beispiel #23
0
bool App::Init()
{
	
	if (m_bInitted)	
	{
		return true;
	}
	
	if (!BaseApp::Init()) return false;
	
	if (GetEmulatedPlatformID() == PLATFORM_ID_IOS || GetEmulatedPlatformID() == PLATFORM_ID_WEBOS)
	{
		//SetLockedLandscape( true); //if we don't allow portrait mode for this game
		//SetManualRotationMode(true); //don't use manual, it may be faster (33% on a 3GS) but we want iOS's smooth rotations
	}

	LogMsg("The Save path is %s", GetSavePath().c_str());
	LogMsg("Region string is %s", GetRegionString().c_str());

#ifdef _DEBUG
	LogMsg("Built in debug mode");
#endif
#ifndef C_NO_ZLIB
	//fonts need zlib to decompress.  When porting a new platform I define C_NO_ZLIB and add zlib support later sometimes
	if (!GetFont(FONT_SMALL)->Load("interface/font_trajan.rtfont")) return false;
#endif

	GetBaseApp()->SetFPSVisible(true);
	GetBaseApp()->SetFPSLimit(30);

	/**
	* My init stuff
	*/
	g_game = new game();
	g_game->init();
	return true;
}
Beispiel #24
0
void CLogMod::PutLog(const CString& sLine, const CString& sWindow /*= "Status"*/)
{
    CString sPath;
    time_t curtime;

    time(&curtime);
    // Generate file name
    sPath = CUtils::FormatTime(curtime, m_sLogPath, m_pUser->GetTimezone());
    if (sPath.empty())
    {
        DEBUG("Could not format log path [" << sPath << "]");
        return;
    }

    // $WINDOW has to be handled last, since it can contain %
    sPath.Replace("$NETWORK", (m_pNetwork ? m_pNetwork->GetName() : "znc"));
    sPath.Replace("$WINDOW", sWindow.Replace_n("/", "?"));
    sPath.Replace("$USER", (m_pUser ? m_pUser->GetUserName() : "UNKNOWN"));

    // Check if it's allowed to write in this specific path
    sPath = CDir::CheckPathPrefix(GetSavePath(), sPath);
    if (sPath.empty())
    {
        DEBUG("Invalid log path ["<<m_sLogPath<<"].");
        return;
    }

    CFile LogFile(sPath);
    CString sLogDir = LogFile.GetDir();
    if (!CFile::Exists(sLogDir)) CDir::MakeDir(sLogDir);
    if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))
    {
        LogFile.Write(CUtils::FormatTime(curtime, "[%H:%M:%S] ", m_pUser->GetTimezone()) + sLine + "\n");
    } else
        DEBUG("Could not open log file [" << sPath << "]: " << strerror(errno));
}
Beispiel #25
0
	bool SendFile(const CString& sRemoteNick, const CString& sFileName) {
		CString sFullPath = CDir::ChangeDir(GetSavePath(), sFileName, CZNC::Get().GetHomePath());
		CDCCSock* pSock = new CDCCSock(this, sRemoteNick, sFullPath);

		CFile* pFile = pSock->OpenFile(false);

		if (!pFile) {
			delete pSock;
			return false;
		}

		unsigned short uPort = CZNC::Get().GetManager().ListenRand("DCC::LISTEN::" + sRemoteNick, m_pUser->GetLocalDCCIP(), false, SOMAXCONN, pSock, 120);

		if (m_pUser->GetNick().Equals(sRemoteNick)) {
			PutUser(":*[email protected] PRIVMSG " + sRemoteNick + " :\001DCC SEND " + pFile->GetShortName() + " " + CString(CUtils::GetLongIP(m_pUser->GetLocalDCCIP())) + " "
				+ CString(uPort) + " " + CString(pFile->GetSize()) + "\001");
		} else {
			PutIRC("PRIVMSG " + sRemoteNick + " :\001DCC SEND " + pFile->GetShortName() + " " + CString(CUtils::GetLongIP(m_pUser->GetLocalDCCIP())) + " "
			    + CString(uPort) + " " + CString(pFile->GetSize()) + "\001");
		}

		PutModule("DCC -> [" + sRemoteNick + "][" + pFile->GetShortName() + "] - Attempting Send.");
		return true;
	}
Beispiel #26
0
bool CDirList::CreateFileName(bool bForce)
{
  bool bDone = false;
  if((!bForce) && m_sFileName.Len())
  {
    bDone = true;
  }
//  else if(!wxFileName::Mkdir(m_sDirSave,0755,wxPATH_MKDIR_FULL))
//  {
//    bDone = false;
//  }
  else
  {
    wxString sPathBase = GetSavePath(true);
    if(!sPathBase.IsEmpty())
    {
      wxString sName(sPathBase);
      wxString sPath;
      nwxFileUtil::NoEndWithSeparator(&sName);
      wxFileName fn(sName);
      sName = fn.GetFullName();
      sName.Replace(" ","_",true);
      if(sName.IsEmpty())
      {
        wxASSERT_MSG(
          false,"Problem with CDirList::CreateFileName()");
        sName = "run_";
      }
      else
      {
        sName.Append("_");
      }
      wxString sFullName;
      wxString sExt(EXT_BATCH);
      int nAdd = 0;
      sPathBase.Append(sName);
      bool bDoneLoop = false;
      while(!bDoneLoop)
      {
        sPath = sPathBase;
        sPath.Append(GetTimeStamp(nAdd));
        sPath.Append(sExt);
        sFullName = nwxFileUtil::SetupFileName(sPath,sExt);
        if(sFullName.IsEmpty())
        {
          bDoneLoop = true; // end loop
          wxASSERT_MSG(false,
            "sFullName is Empty in CDirList::CreateFileName()");
        }
        else if(wxFileName::FileExists(sFullName))
        {
          nAdd++;
        }
        else
        {
          wxFile xFile(sFullName.wc_str(),wxFile::write_excl);
          if(!xFile.IsOpened())
          {
            wxString s("Cannot create file: ");
            s.Append(sFullName);
            wxASSERT_MSG(false,s);
          }
          else
          {
            m_sFileName = sFullName;
            bDone = true;
          }
          bDoneLoop = true;
        }
      }
    }
    else
    {
      wxASSERT_MSG(
          false,"empty path in CDirList::CreateFileName()");
    }
  }
  return bDone;
}
Beispiel #27
0
bool CModule::SaveRegistry() const {
	//CString sPrefix = (m_pUser) ? m_pUser->GetUserName() : ".global";
	return (m_mssRegistry.WriteToDisk(GetSavePath() + "/.registry", 0600) == MCString::MCS_SUCCESS);
}
Beispiel #28
0
bool CModule::LoadRegistry() {
	//CString sPrefix = (m_pUser) ? m_pUser->GetUserName() : ".global";
	return (m_mssRegistry.ReadFromDisk(GetSavePath() + "/.registry") == MCString::MCS_SUCCESS);
}
Beispiel #29
0
	CString PemFile() const {
		return GetSavePath() + "/user.pem";
	}
int BatchedFolderRegistration( int argc, char* argv[] )
{
  ctkCommandLineParser parser;
  parser.setArgumentPrefix("--","-");
  // Add command line argument names
  parser.addArgument("help", "h",ctkCommandLineParser::Bool, "Show this help text");
  parser.addArgument("xml", "x",ctkCommandLineParser::Bool, "Print a XML description of this modules command line interface");
  //parser.addArgument("usemask", "u", QVariant::Bool, "Use segmentations (derived resources) to exclude areas from registration metrics");
  parser.addArgument("input", "i", ctkCommandLineParser::String, "Input folder",us::Any(),false);
  parser.addArgument("output", "o", ctkCommandLineParser::String, "Output folder (ending with /)",us::Any(),false);
  parser.addArgument("fixed", "f", ctkCommandLineParser::String, "Suffix for fixed image",us::Any(),false);
  parser.addArgument("moving", "m", ctkCommandLineParser::String, "Suffix for moving images",us::Any(),false);
  parser.addArgument("derived", "d", ctkCommandLineParser::String, "Derived resources suffixes (replaces suffix for moving images); comma separated",us::Any(),true);
  parser.addArgument("silent", "s", ctkCommandLineParser::Bool, "No xml progress output.");
  // Feature currently disabled
  //parser.addArgument("resample", "r", QVariant::String, "Reference Image for resampling (optional), is not applied to tensor data");

  map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);

  // Handle special arguments
  bool silent = false;
  {
    if (parsedArgs.size() == 0)
    {
      MITK_ERROR << "Missig arguements" ;
      return EXIT_FAILURE;
    }

    if (parsedArgs.count("xml"))
    {
      MITK_ERROR << "This is to be handled by shell script";
      return EXIT_SUCCESS;
    }

    if (parsedArgs.count("silent"))
      silent = true;

    // Show a help message
    if ( parsedArgs.count("help") || parsedArgs.count("h"))
    {
      std::cout << parser.helpText();
      return EXIT_SUCCESS;
    }
  }
  std::string outputPath = us::any_cast<string>(parsedArgs["output"]);
  std::string refPattern = us::any_cast<string>(parsedArgs["fixed"]);
  std::string inputPath = us::any_cast<string>(parsedArgs["input"]);
  std::string movingImgPattern = us::any_cast<string>(parsedArgs["moving"]);
  //QString resampleReference = parsedArgs["resample"].toString();
  //bool maskTumor = parsedArgs["usemask"].toBool();

  // if derived sources pattern is provided, populate QStringList with possible filename postfixes
  std::vector<std::string> derPatterns;

  if (parsedArgs.count("derived") || parsedArgs.count("d") )
  {
    std::string arg =  us::any_cast<string>(parsedArgs["derived"]);
    derPatterns = split(arg ,',');
  }

  MITK_INFO << "Input Folder : " << inputPath;
  MITK_INFO << "Looking for reference image ...";
  FileListType referenceFileList = CreateFileList(inputPath,refPattern);

  if (referenceFileList.size() != 1)
  {
    MITK_ERROR << "None or more than one possible reference images (" << refPattern <<") found. Exiting." << referenceFileList.size();
    MITK_INFO  << "Choose a fixed arguement that is unique in the given folder!";
    return EXIT_FAILURE;
  }

  std::string referenceFileName = referenceFileList.at(0);

  MITK_INFO << "Loading Reference (fixed) image: " << referenceFileName;
  mitk::Image::Pointer refImage = mitk::IOUtil::LoadImage(referenceFileName);

  if (refImage.IsNull())
    MITK_ERROR << "Loaded fixed image is NULL";

  // Copy reference image to destination
  std::string savePathAndFileName = GetSavePath(outputPath, referenceFileName);
  mitk::IOUtil::SaveImage(refImage, savePathAndFileName);

  // Copy all derived resources also to output folder, adding _reg suffix
  referenceFileList = CreateDerivedFileList(referenceFileName, movingImgPattern,derPatterns);
  CopyResources(referenceFileList, outputPath);

  std::string derivedResourceFilename;
  mitk::Image::Pointer referenceMask = NULL; // union of all segmentations

  if (!silent)
  {
    // XML Output to report progress
    std::cout << "<filter-start>";
    std::cout << "<filter-name>Batched Registration</filter-name>";
    std::cout << "<filter-comment>Starting registration ... </filter-comment>";
    std::cout << "</filter-start>";
  }

  // Now iterate over all files and register them to the reference image,
  // also register derived resources based on file patterns
  // ------------------------------------------------------------------------------

  // Create File list

  FileListType movingImagesList = CreateFileList(inputPath, movingImgPattern);


  // TODO Reactivate Resampling Feature
  //  mitk::Image::Pointer resampleImage = NULL;
  //  if (QFileInfo(resampleReference).isFile())
  //  {
  //    resampleImage = mitk::IOUtil::LoadImage(resampleReference.toStdString());
  //  }
  for (unsigned int i =0; i < movingImagesList.size(); i++)
  {
    std::string fileMorphName = movingImagesList.at(i);
    if (fileMorphName == referenceFileName)
    {

      // do not process reference image again
      continue;
    }
    MITK_INFO << "Processing image " << fileMorphName;

    // 1 Register morphological file to reference image

    if (!itksys::SystemTools::FileExists(fileMorphName.c_str()))
    {
      MITK_WARN << "File does not exit. Skipping entry.";
      continue;
    }
    // Origin of images is cancelled
    // TODO make this optional!!
    double transf[6];
    double offset[3];
    {
      mitk::Image::Pointer movingImage = mitk::IOUtil::LoadImage(fileMorphName);

      MITK_ERROR << "REF COUNT MOVING 0 " << movingImage->GetReferenceCount();
      if (movingImage.IsNull())
        MITK_ERROR << "Loaded moving image is NULL";

      // Store transformation,  apply it to morph file
      MITK_INFO << "----------Registering moving image to reference----------";


      MITK_ERROR << "REF COUNT MOVING 1 " << movingImage->GetReferenceCount();
      //mitk::RegistrationWrapper::GetTransformation(refImage, movingImage, transf, offset, referenceMask);
      MITK_ERROR << "REF COUNT MOVING 2 " << movingImage->GetReferenceCount();

      mitk::RegistrationWrapper::ApplyTransformationToImage(movingImage, transf,offset, NULL); // , resampleImage
      MITK_ERROR << "REF COUNT MOVING 3 " << movingImage->GetReferenceCount();
      savePathAndFileName = GetSavePath(outputPath, fileMorphName);
      std::string fileType = itksys::SystemTools::GetFilenameExtension(fileMorphName);
      SaveImage(savePathAndFileName,movingImage,fileType );
    }

    if (!silent)
    {
      std::cout << "<filter-progress-text progress=\"" <<
                   (float)i / (float)movingImagesList.size()
                << "\" >.</filter-progress-text>";
    }

    // Now parse all derived resource and apply the above calculated transformation to them
    // ------------------------------------------------------------------------------------

    FileListType fList = CreateDerivedFileList(fileMorphName, movingImgPattern,derPatterns);
    if (fList.size() > 0)
      MITK_INFO << "----------DERIVED RESOURCES ---------";
    for (unsigned int j=0; j < fList.size(); j++)
    {
      derivedResourceFilename = fList.at(j);
      MITK_INFO << "----Processing derived resource " << derivedResourceFilename << " ...";
      mitk::Image::Pointer derivedMovingResource = mitk::IOUtil::LoadImage(derivedResourceFilename);
      // Apply transformation to derived resource, treat derived resource as binary
      mitk::RegistrationWrapper::ApplyTransformationToImage(derivedMovingResource, transf,offset, NULL, true);

      savePathAndFileName = GetSavePath(outputPath, derivedResourceFilename);
      std::string fileType = itksys::SystemTools::GetFilenameExtension(derivedResourceFilename);

      SaveImage(savePathAndFileName,derivedMovingResource,fileType );
    }
  }

  if (!silent)
    std::cout << "<filter-end/>";
  return EXIT_SUCCESS;
}