Exemplo n.º 1
0
// FIXME: could become a skins2 OS factory function or a vlc core function
std::string ThemeLoader::getTmpDir( )
{
#if defined( _WIN32 )
    wchar_t *tmpdir = _wtempnam( NULL, L"vlt" );
    if( tmpdir == NULL )
        return "";
    char* utf8 = FromWide( tmpdir );
    free( tmpdir );
    std::string tempPath( utf8 ? utf8 : "" );
    free( utf8 );
    return tempPath;

#elif defined( __OS2__ )
    char *tmpdir = tempnam( NULL, "vlt" );
    if( tmpdir == NULL )
        return "";
    std::string tempPath( sFromLocale( tmpdir ));
    free( tmpdir );
    return tempPath;

#else
    char templ[] = "/tmp/vltXXXXXX";
    char *tmpdir = mkdtemp( templ );
    return std::string( tmpdir ? tmpdir : "");
#endif
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void CopyFeatureArrayToElementArray::dataCheck()
{
  setErrorCondition(0);

  if (getCreatedArrayName().isEmpty() == true)
  {
    setErrorCondition(-11002);
    notifyErrorMessage(getHumanLabel(), "The new Element array name must be set", getErrorCondition());
    return;
  }

  QVector<size_t> cDims(1, 1);
  m_FeatureIdsPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter>(this, getFeatureIdsArrayPath(), cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_FeatureIdsPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_FeatureIds = m_FeatureIdsPtr.lock()->getPointer(0); }    /* Now assign the raw pointer to data from the DataArray<T> object */

  m_InArrayPtr = getDataContainerArray()->getPrereqIDataArrayFromPath<IDataArray, AbstractFilter>(this, getSelectedFeatureArrayPath()); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */

  DataArrayPath tempPath(getFeatureIdsArrayPath().getDataContainerName(), getFeatureIdsArrayPath().getAttributeMatrixName(), "");
  getDataContainerArray()->getPrereqAttributeMatrixFromPath<AbstractFilter>(this, tempPath, -301);

  if(getErrorCondition() < 0 ) { return; }

  tempPath.update(getFeatureIdsArrayPath().getDataContainerName(), getFeatureIdsArrayPath().getAttributeMatrixName(), getCreatedArrayName());
  TemplateHelpers::CreateNonPrereqArrayFromArrayType()(this, tempPath, m_InArrayPtr.lock()->getComponentDimensions(), m_InArrayPtr.lock());
}
/**
 * @function smoothPath
 */
void PathPlanner::smoothPath( int _robotId, 
                              const Eigen::VectorXi &_links, 
                              std::list<Eigen::VectorXd> &_path ) {
  
  // =========== YOUR CODE HERE ==================
  // HINT: Use whatever technique you like better, first try to shorten a path and then you can try to make it smoother
  //////RRT rrt( world, _robotId, _links, _start, stepSize );
  //;
  if(path.empty() == true || path.size() <= 1)
  {return;}
  std::list<Eigen::VectorXd>::iterator pathhead, pathend1, pathend2; 
  ////////////////////////////////////////
  //
  //  pathend2 = pathend1 + 1;
  //  pathend1 = pathhead;
  //  check whether pathend2 is reachable for pathhead
  //  if no, (if pathend1 != pathhead, clear(pathhead, pathend1)
  //            if pathend1 == pathhead, pathhead = pathhead2);
  //  if yes, pathend1 = pathend2, pathend2++;
  //
  ////////////////////////////////////////
  pathhead = pathend1 = pathend2 = path.begin();
  pathend2 ++;
  while(pathend2 != path.end())
  {
	  if(checkPathSegment(_robotId, _links, (*pathhead), (*pathend2)) == true)
	  {
		  pathend1 = pathend2;
		  pathend2 ++;
	  }
	  else
	  {
		  std::list<Eigen::VectorXd> tempPath(pathhead,pathend2);
		  if( tempPath.size() <= 1)
		  {
			  pathhead = pathend1 = pathend2;
			  pathend2 ++;
		  }
		  else
		  {
			  pathhead ++;
			  path.erase(pathhead, pathend1);

			  pathhead = pathend1 = pathend2 = path.begin();
			  pathend2 ++;
		  }
	  }
  }
  /////////////////////////////////////////////////////////
  ///
  ///
  ///
  ///
  ///
  ///
  ///
  ////////////////////////////////////////////////////////
  return;
  // ========================================	
}
Exemplo n.º 4
0
CString openTemporaryFile(const char* prefix, PlatformFileHandle& handle)
{
    // BREW does not have a system-wide temporary directory,
    // use "fs:/~/tmp" as our temporary directory.
    String tempPath("fs:/~/tmp");

    PlatformRefPtr<IFileMgr> fileMgr = createRefPtrInstance<IFileMgr>(AEECLSID_FILEMGR);

    // Create the temporary directory if it does not exist.
    IFILEMGR_MkDir(fileMgr.get(), tempPath.utf8().data());

    // Loop until we find a temporary filename that does not exist.
    int number = static_cast<int>(randomNumber() * 10000);
    CString filename;
    do {
        StringBuilder builder;
        builder.append(tempPath);
        builder.append('/');
        builder.append(prefix);
        builder.append(String::number(number));
        filename = builder.toString().utf8();
        number++;
    } while (IFILEMGR_Test(fileMgr.get(), filename.data()) == SUCCESS);

    IFile* tempFile = IFILEMGR_OpenFile(fileMgr.get(), filename.data(), _OFM_CREATE);
    if (tempFile) {
        handle = tempFile;
        return filename;
    }

    return CString();
}
	nsresult JRexDirServiceProvider::Initialize(const char* grePath){
		nsEmbedCString tempPath(grePath);
		nsresult rv=NS_NewNativeLocalFile(tempPath,PR_TRUE,getter_AddRefs(greDirPath));
		JREX_RETURN_IF_FAILED(rv,"Initialize()--> **** NS_NewNativeLocalFile ****")
		JREX_LOGLN("Initialize()--> **** NS_NewNativeLocalFile Done GOT THE GRE PATH <"<<greDirPath.get()<<"> ****")
		return rv;
	}
Exemplo n.º 6
0
// If this is uninstaller and we're running from installation directory,
// copy uninstaller to temp directory and execute from there, exiting
// ourselves. This is needed so that uninstaller can delete itself
// from installation directory and remove installation directory
// If returns TRUE, this is an installer and we sublaunched ourselves,
// so the caller needs to exit
bool ExecuteUninstallerFromTempDir()
{
    // only need to sublaunch if running from installation dir
    ScopedMem<WCHAR> ownDir(path::GetDir(GetOwnPath()));
    ScopedMem<WCHAR> tempPath(GetTempUninstallerPath());

    // no temp directory available?
    if (!tempPath)
        return false;

    // not running from the installation directory?
    // (likely a test uninstaller that shouldn't be removed anyway)
    if (!path::IsSame(ownDir, gGlobalData.installDir))
        return false;

    // already running from temp directory?
    if (path::IsSame(GetOwnPath(), tempPath))
        return false;

    if (!CopyFile(GetOwnPath(), tempPath, FALSE)) {
        NotifyFailed(L"Failed to copy uninstaller to temp directory");
        return false;
    }

    ScopedMem<WCHAR> args(str::Format(L"/d \"%s\" %s", gGlobalData.installDir, gGlobalData.silent ? L"/s" : L""));
    bool ok = CreateProcessHelper(tempPath, args);

    // mark the uninstaller for removal at shutdown (note: works only for administrators)
    MoveFileEx(tempPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);

    return ok;
}
Exemplo n.º 7
0
bool Deck::importDana(QString fileName)
{
    QFileInfo fi(fileName);
    QString baseName = fi.baseName().toLower();

    QString tempFolder = utils::combinePaths(tempPath(), baseName);
    QString deckPath = utils::combinePaths(tempFolder, "deck.xml"); 
    QString iconPath = utils::combinePaths(tempFolder, "icon.png"); 
    
    utils::createDirectory(tempFolder);
    
    Compressor c;
    if(!c.decompressFolder(fileName, tempFolder)) {
        return false;
    }

    /// 
    importFromXml(deckPath);

    utils::removeFile(deckPath);
    utils::copyDirectory(getDeckPath(), tempFolder);

    /// load icon pixmap
    loadPixmap( iconPath );

    return true;
}
Exemplo n.º 8
0
void ThemesDlg::uninstall()
{
    ThemeWidget* w = (ThemeWidget*)(tableThemes->selectedItem());
    ThemeFile* tf = w->themeFile();
    KUrl theme(tf->file());
    QString tempPath(tf->path());

    karambaApp->closeTheme(tf->name());

    if (!tf->isZipTheme()) {
        kDebug() << "encountered unpacked theme" ;
        //Don't move it to the trash if it is a local theme
        if (isDownloaded(tempPath)) {
            QFileInfo remPath(tf->path());
            QDir remDir(remPath.dir());
            remDir.cdUp();
            kDebug() << "moving " << remDir.path() << " to the trash" ;
            KIO::trash(remDir.path());
        }
        tableThemes->removeItem((QWidget*)w);

        //some themes have multiple .theme files
        //find all .themes that could be listed in the dialog for the directory removed
        QList<ThemeWidget*> list;
        for (uint i = 2; i < tableThemes->count(); ++i) {
            ThemeWidget* tempW = (ThemeWidget*)(tableThemes->item(i));
            ThemeFile* tempTf = tempW->themeFile();
            if (tempTf->path().compare(tempPath) == 0) {
                list.append(tempW);
            }
        }
        foreach (ThemeWidget *twPtr, list) {
            karambaApp->closeTheme(twPtr->themeFile()->name());
            tableThemes->removeItem((QWidget*)twPtr);
        }
Exemplo n.º 9
0
static std::string
tempFileName(const std::string &ext="") {
#if 0 // [Robb Matzke 2014-06-18]: temp_directory_path and unique_path are not always available
    boost::filesystem::path path = boost::filesystem::temp_directory_path().string();
    path /= "%%%%-%%%%-%%%%-%%%%" + ext;
    return boost::filesystem::unique_path(path).string();
#else
# ifdef BOOST_WINDOWS
    char dummy;
    size_t size = GetTempPath(0, &dummy);               // size includes NUL terminator
    if (0==size)
        throw std::runtime_error("could not get system temporary directory name");
    std::vector<char> buffer(size);
    size = GetTempPath(size, &buffer[0]);
    ASSERT_require(size==buffer.size());
    std::string tempPath(buffer.begin(), buffer.begin()+size); // includes final back-slash according to documentation
# else
    std::string tempPath;
    if (0!=geteuid()) {
        if (char *e = getenv("TMPDIR")) {
            struct stat sb;
            if (0==stat(e, &sb) && S_ISDIR(sb.st_mode))
                tempPath = e;
        }
    }
    if (tempPath.empty()) {
        struct stat sb;
        if (0==stat(P_tmpdir, &sb) && S_ISDIR(sb.st_mode))
            tempPath = P_tmpdir;
    }
    if (tempPath.empty())
        tempPath = _PATH_TMP;
    if (tempPath.empty())
        tempPath = "/tmp";
    if ('/'!=tempPath[tempPath.size()-1])
        tempPath += "/";
# endif
    while (1) {
        std::string basename;
        for (int i=0; i<4; ++i) {
            if (i!=0)
                basename += '-';
            for (int j=0; j<4; ++j) {
                int k = rand() % 16;
                char ch = k < 10 ? '0'+k : 'a'+k-10;
                basename += ch;
            }
        }
        std::string path = tempPath + basename + ext;
#ifdef BOOST_WINDOWS
        bool exists = PathFileExists(path.c_str());
#else
        bool exists = 0 == access(path.c_str(), F_OK);
#endif
        if (!exists)
            return path;
    }
#endif
}
Exemplo n.º 10
0
QSqlDatabase QMail::createDatabase()
{
    if (!databaseDataInstance()->hasLocalData()) {
        databaseDataInstance()->setLocalData(new QDatabaseInstanceData);
    }
    QDatabaseInstanceData* instance = databaseDataInstance()->localData();

    QSqlDatabase db;
    if (instance->init) {
        db = QSqlDatabase::database("qmailstore_sql_connection");
    } else {
        qMailLog(Messaging) << "opening database";
        db = QSqlDatabase::addDatabase("QSQLITE", "qmailstore_sql_connection");
        
        QDir dbDir(dataPath() + "database");
        if (!dbDir.exists()) {
#ifdef Q_OS_UNIX
            QString path = dataPath();
            if (path.endsWith('/'))
                path = path.left(path.length() - 1);
            if (!QDir(path).exists() && ::mkdir(QFile::encodeName(path), S_IRWXU) == -1)
                qCritical() << "Cannot create database directory: " << errno;
#endif
            if (!dbDir.mkpath(dataPath() + "database"))
                qCritical() << "Cannot create database path";
        }

        db.setDatabaseName(dataPath() + "database/qmailstore.db");
#endif

        if(!db.open()) {
            QSqlError dbError = db.lastError();
            qCritical() << "Cannot open database: " << dbError.text();
        }

        QDir tp(tempPath());
        if(!tp.exists())
            if(!tp.mkpath(tempPath()))
                qCritical() << "Cannot create temp path";

        instance->init = true;
    }

    return db;
}
Exemplo n.º 11
0
void ConfigurationManager::processPaths(Files::PathContainer& dataDirs, bool create)
{
    std::string path;
    for (Files::PathContainer::iterator it = dataDirs.begin(); it != dataDirs.end(); ++it)
    {
        path = it->string();
        boost::erase_all(path, "\"");
        *it = boost::filesystem::path(path);

        // Check if path contains a token
        if (!path.empty() && *path.begin() == '?')
        {
            std::string::size_type pos = path.find('?', 1);
            if (pos != std::string::npos && pos != 0)
            {
                TokensMappingContainer::iterator tokenIt = mTokensMapping.find(path.substr(0, pos + 1));
                if (tokenIt != mTokensMapping.end())
                {
                    boost::filesystem::path tempPath(((mFixedPath).*(tokenIt->second))());
                    if (pos < path.length() - 1)
                    {
                        // There is something after the token, so we should
                        // append it to the path
                        tempPath /= path.substr(pos + 1, path.length() - pos);
                    }

                    *it = tempPath;
                }
                else
                {
                    // Clean invalid / unknown token, it will be removed outside the loop
                    (*it).clear();
                }
            }
        }

        if (!boost::filesystem::is_directory(*it))
        {
            if (create)
            {
                try
                {
                    boost::filesystem::create_directories (*it);
                }
                catch (...) {}

                if (boost::filesystem::is_directory(*it))
                    continue;
            }

            (*it).clear();
        }
    }

    dataDirs.erase(std::remove_if(dataDirs.begin(), dataDirs.end(),
        boost::bind(&boost::filesystem::path::empty, _1)), dataDirs.end());
}
Exemplo n.º 12
0
QString TempDeck::getDeckPath() const
{
    QString deckPath = utils::combinePaths(
        tempPath(), QString("tempDeck_%1").arg((quint64)this));

    utils::createDirectory(deckPath);

    return deckPath;
}
Exemplo n.º 13
0
String openTemporaryFile(const String& prefix, PlatformFileHandle& handle)
{
    GUniquePtr<gchar> filename(g_strdup_printf("%s%s", prefix.utf8().data(), createCanonicalUUIDString().utf8().data()));
    GUniquePtr<gchar> tempPath(g_build_filename(g_get_tmp_dir(), filename.get(), NULL));
    GRefPtr<GFile> file = adoptGRef(g_file_new_for_path(tempPath.get()));

    handle = g_file_create_readwrite(file.get(), G_FILE_CREATE_NONE, 0, 0);
    if (!isHandleValid(handle))
        return String();
    return String::fromUTF8(tempPath.get());
}
Exemplo n.º 14
0
void Filesystem::SetWritePath(const std::string& path)
{

	std::unique_ptr<ISearchPath> tempPath(new StdioSearchPath());

	if (!tempPath->Init(path))
		return;

	// Write path is always stdio
	writePath = std::move(tempPath);
}
Exemplo n.º 15
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void RemoveComponentFromArray::dataCheck()
{
  setErrorCondition(0);

  m_InArrayPtr = getDataContainerArray()->getPrereqIDataArrayFromPath<IDataArray, AbstractFilter>(this, getSelectedArrayPath());

  if (m_SaveRemovedComponent == true)
  {
    if (m_NewArrayArrayName.isEmpty() == true)
    {
      setErrorCondition(-11001);
      notifyErrorMessage(getHumanLabel(), "Removed Component array name must be set.", getErrorCondition());
      return;
    }
  }

  if (m_ReducedArrayArrayName.isEmpty() == true)
  {
    setErrorCondition(-11002);
    notifyErrorMessage(getHumanLabel(), "Reduced array name must be set.", getErrorCondition());
    return;
  }

  if(getErrorCondition() < 0) { return; }

  if (m_InArrayPtr.lock()->getNumberOfComponents() < 2)
  {
    setErrorCondition(-11003);
    QString ss = QObject::tr("Selected array '%1' must have more than 1 component. The number of components is %2").arg(getSelectedArrayPath().getDataArrayName()).arg(m_InArrayPtr.lock()->getNumberOfComponents());
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
    return;
  }

  if(m_CompNumber >= m_InArrayPtr.lock()->getNumberOfComponents())
  {
    setErrorCondition(-11004);
    QString ss = QObject::tr("Component to extract (%1) is larger than the number of components (%2) for array selected: '%1'").arg(m_CompNumber).arg(m_InArrayPtr.lock()->getNumberOfComponents()).arg(getSelectedArrayPath().getDataArrayName());
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
    return;
  }

  QVector<size_t> cDims(1, 1);
  if (m_SaveRemovedComponent == true)
  {
    DataArrayPath tempPath(getSelectedArrayPath().getDataContainerName(), getSelectedArrayPath().getAttributeMatrixName(), getNewArrayArrayName());
    m_NewArrayPtr = TemplateHelpers::CreateNonPrereqArrayFromArrayType()(this, tempPath, cDims, m_InArrayPtr.lock());
  }

  cDims[0] = m_InArrayPtr.lock()->getNumberOfComponents() - 1;
  DataArrayPath tempPath2(getSelectedArrayPath().getDataContainerName(), getSelectedArrayPath().getAttributeMatrixName(), getReducedArrayArrayName());
  m_ReducedArrayPtr = TemplateHelpers::CreateNonPrereqArrayFromArrayType()(this, tempPath2, cDims, m_InArrayPtr.lock());
}
Exemplo n.º 16
0
void LogPrefsView::MessageReceived(BMessage* msg)
{
    switch (msg->what) {
    case M_PREFLOG_CHECKBOX_CHANGED: {
        BControl* source(NULL);
        msg->FindPointer("source", reinterpret_cast<void**>(&source));
        vision_app->SetBool(msg->FindString("setting"), source->Value() == B_CONTROL_ON);
    }
    break;

    case M_PREFLOG_LOGPATH_CHANGED: {
        BString tempPath(fLogBaseDir->Text());
        if (tempPath.Length() == 0) {
            BAlert* emptyPathAlert(
                new BAlert(S_PREFLOG_ALERT_TITLE, S_PREFLOG_ALERT_TEXT, S_PREFLOG_ALERT_BUTTON));
            emptyPathAlert->Go();
            break;
        } else {
            // remove trailing slash to avoid setting off BPath's normalization
            if (tempPath[tempPath.Length() - 1] == '/') tempPath.ReplaceLast('/', '\0');

            BPath path(tempPath.String());
            if (path.InitCheck() != B_OK) {
                BAlert* badPathAlert(new BAlert(S_PREFLOG_ALERT_TITLE, S_PREFLOG_ALERT_TEXT,
                                                S_PREFLOG_ALERT_BUTTON));
                badPathAlert->Go();
                break;
            }
        }
        vision_app->SetString("logBaseDir", 0, tempPath.String());
    }
    break;

    case M_PREFLOG_TS_FORMAT_CHANGED: {
        vision_app->SetString("timestamp_format", 0, fLogStampFormat->Text());
    }
    break;

    case M_PREFLOG_DELETE_LOGS: {
        BString path(vision_app->GetString("logBaseDir"));
        BEntry entry(path.String());
        _DeleteLogs(&entry);
        fClearLogs->SetEnabled(false);
    }
    break;

    default:
        BView::MessageReceived(msg);
        break;
    }
}
Exemplo n.º 17
0
CLIB_API const boost::filesystem::path & GetTempFolder(boost::filesystem::path & path)
{
    DWORD result = ::GetTempPath(0, _T(""));
    if (result == 0)
        return path;

    std::vector<TCHAR> tempPath(result);
    result = ::GetTempPath(static_cast<DWORD>(tempPath.size()), &tempPath[0]);
    if ((result == 0) || (result > tempPath.size()))
        return path;

    path = stringToPath(std::_tstring(tempPath.begin(), tempPath.begin() + static_cast<std::size_t>(result)));
    return path;
}
Exemplo n.º 18
0
BOOL SnapshotWizardPage1::OnInitDialog(CWindow wndFocus, LPARAM lInitParam) {
	sourceEdit_ = GetDlgItem(IDC_SOURCE_EDIT);
	destinationEdit_ = GetDlgItem(IDC_DEST_EDIT);

	sourceEdit_.SetWindowTextW(L"%systemroot%\\NTDS\\ntds.dit");
	wchar_t destinationPath[MAX_PATH];
	if (::GetModuleFileName(nullptr, destinationPath, MAX_PATH)) {
		CPath tempPath(destinationPath);
		tempPath.RemoveFileSpec();
		tempPath.Append(L"\\ntdsSnapshot.dit");
		destinationEdit_.SetWindowTextW(static_cast<const wchar_t*>(tempPath));
	}
	return TRUE;
}
Exemplo n.º 19
0
std::string gettmpdir(void)
{
#ifdef _WIN32
  DWORD result = ::GetTempPath(0, _T(""));
  if (result == 0)
	throw std::runtime_error("Could not get system temp path");

  std::vector<TCHAR> tempPath(result + 1);
  result = ::GetTempPath(static_cast<DWORD>(tempPath.size()), &tempPath[0]);
  if((result == 0) || (result >= tempPath.size()))
	throw std::runtime_error("Could not get system temp path");

  return std::string(tempPath.begin(), tempPath.begin() + static_cast<std::size_t>(result));
#else
	  return std::string("/tmp/");
#endif
}
Exemplo n.º 20
0
    void SetUp() {
        samPath_ = tempPath("breakdancer-unit-test", ".sam");
        std::ofstream out(samPath_.c_str());
        out << samData;
        out.close();

        reader.reset(openBam(samPath_));

        boost::shared_ptr<RawBamEntry> entry(new RawBamEntry);
        while (reader->next(*entry) > 0) {
            reads.emplace_back(new Alignment(*entry));
            rawEntries.push_back(entry);
            entry.reset(new RawBamEntry);
        }

        EXPECT_EQ(6u, reads.size());
    }
Exemplo n.º 21
0
TEST_F(TestBam, bamWriter) {
    std::string tmpOut = tempPath("breakdancer-unit-test", ".sam");
    BamWriter writer(tmpOut, reader->header(), true);
    for (size_t i = 0; i < rawEntries.size(); ++i) {
        writer.write(*rawEntries[i]);
    }
    writer.close();

    std::ifstream in(tmpOut.c_str());
    in.seekg(0, std::ios::end);
    size_t size = in.tellg();
    in.seekg(0, std::ios::beg);
    std::vector<char> buf(size);
    ASSERT_TRUE(in.read(buf.data(), size));
    buf.push_back(0); // make sure buffer is null terminated
    EXPECT_STREQ(samData.c_str(), buf.data());

    bfs::remove(tmpOut);
}
Exemplo n.º 22
0
void FileUtils::removeFile(const char* src) throw (IOException)
{
#ifdef PLATFORM_UNIX
	if (unlink(src) != 0)
	{
		if (errno != ENOENT)
		{
			throw IOException("Unable to remove file " + std::string(src));
		}
	}
#else
	if (!DeleteFile(src))
	{
		if (GetLastError() == ERROR_ACCESS_DENIED)
		{
			// if another process is using the file, try moving it to
			// a temporary directory and then
			// scheduling it for deletion on reboot
			std::string tempDeletePathBase = tempPath();
			tempDeletePathBase += '/';
			tempDeletePathBase += fileName(src);

			int suffix = 0;
			std::string tempDeletePath = tempDeletePathBase;
			while (fileExists(tempDeletePath.c_str()))
			{
				++suffix;
				tempDeletePath = tempDeletePathBase + '_' + intToStr(suffix);
			}

			LOG(Warn,"Unable to remove file " + std::string(src) + " - it may be in use.  Moving to "
			         + tempDeletePath + " and scheduling delete on reboot.");
			moveFile(src,tempDeletePath.c_str());
			MoveFileEx(tempDeletePath.c_str(),0,MOVEFILE_DELAY_UNTIL_REBOOT);
		}
		else if (GetLastError() != ERROR_FILE_NOT_FOUND)
		{
			throw IOException("Unable to remove file " + std::string(src));
		}
	}
#endif
}
Exemplo n.º 23
0
void MeteorShowersMgr::updateFinished(QNetworkReply* reply)
{
	if (m_progressBar)
	{
		m_progressBar->setValue(100);
		StelApp::getInstance().removeProgressBar(m_progressBar);
		m_progressBar = NULL;
	}

	if (reply->error() != QNetworkReply::NoError)
	{
		qWarning() << "MeteorShowersMgr: Failed to download!" << reply->url();
		qWarning() << "MeteorShowersMgr: Error " << reply->errorString();
		setStatusOfLastUpdate(FAILED);
		return;
	}

	QString tempPath(m_catalogPath + "_new.json");
	QFile newCatalog(tempPath);
	newCatalog.remove(); // always overwrites
	if (!newCatalog.open(QIODevice::ReadWrite | QIODevice::Text))
	{
		qWarning() << "MeteorShowersMgr: Cannot write the downloaded catalog!";
		setStatusOfLastUpdate(FAILED);
		return;
	}

	newCatalog.write(reply->readAll());
	newCatalog.close();

	if (!loadCatalog(tempPath))
	{
		setStatusOfLastUpdate(FAILED);
		return;
	}

	QFile(m_catalogPath).remove();
	newCatalog.rename(tempPath.remove("_new.json"));

	qDebug() << "MeteorShowersMgr: The catalog was updated!";
	setStatusOfLastUpdate(UPDATED);
}
Exemplo n.º 24
0
bool Deck::exportToDana(QString fileName)
{
    QFileInfo fi(fileName);
    QString baseName = fi.baseName().toLower();
    
    QString tempFolder = utils::combinePaths(tempPath(), baseName);
    QString deckFile = utils::combinePaths(tempFolder, "deck.xml"); 
        
    utils::removeDirectory(tempFolder);
    utils::createDirectory(tempFolder);
    
    if(!exportToXml(deckFile))
        return false;

    utils::copyDirectory(tempFolder, getDeckPath());

    Compressor c;
    if(!c.compressFolder(tempFolder, fileName)) {
        return false;
    }

    return true;  
}
Exemplo n.º 25
0
void ProjectBase::onProblemFinished(Problem* problem,Result* result)
{
    if(result)
    {
        //Results
        if(!result->isSuccess())
        {
            QString msg = "Problem "+ problem->getClassName()+ " has failed";
            InfoSender::instance()->send(Info(msg,ListInfo::ERROR2));
            delete result;
        }
        else
        {
            QString msg = "Problem "+ problem->getClassName()+ " succeeded";
            InfoSender::instance()->send(Info(msg,ListInfo::NORMAL2));

            if(result->name().isEmpty())
                result->setName(result->problem()->name()+" result");

            HighTools::checkUniqueResultName(this,result,_results);

            // prepare directory (erase content/create folder)
            QString storeFolder = resultsFolder()+QDir::separator()+result->name();
            LowTools::mkpath(storeFolder,true);

            result->store(storeFolder,tempPath());
            // result->setParent(this);
            addResult(result);
            save(result);
        }
    }
    _problemLaunchMutex.unlock();
    _problemsThreads.remove(problem);

    /// @todo check whether it is really deleted
    problem->deleteLater();
}
Exemplo n.º 26
0
/**
 * Sets the name of the base template for this template.
 *
 * @param name		the base template name
 *
 * @return 0 on success, error code on error
 */
int TpfTemplate::setBaseTemplateName(const std::string & name)
{
	m_baseTemplateName = name;
	
	if (m_parentFile == NULL)
		return -1;

	// load the base template
	if (m_baseTemplateFile != NULL)
	{
		delete m_baseTemplateFile;
		m_baseTemplateFile = NULL;
	}

	Filename baseTemplateFileName(NULL, NULL, name.c_str(), TEMPLATE_EXTENSION);
	Filename sourceTpfPath(NULL, m_parentFile->getTpfPath().c_str(), NULL, NULL);
	Filename tempPath(baseTemplateFileName);

	tempPath.setPath(sourceTpfPath.getPath().c_str());
	tempPath.appendPath(baseTemplateFileName);
	tempPath.setDrive(m_parentFile->m_fp.getFilename().getDrive().c_str());

	File fp;
	int i = 0;
	while (!fp.exists(tempPath) && i < MAX_DIRECTORY_DEPTH)
	{
		sourceTpfPath.appendPath(NEXT_HIGHER_PATH);
		tempPath.setPath(sourceTpfPath.getPath().c_str());
		tempPath.appendPath(baseTemplateFileName);
		++i;
	}
	if (i == MAX_DIRECTORY_DEPTH)
		return -1;

	m_baseTemplateFile = new TpfFile;
	return m_baseTemplateFile->loadTemplate(tempPath);
}	// TpfTemplate::setBaseTemplateName
Exemplo n.º 27
0
TEST_F(TrackExporterTest, MungeFilename) {
    // Create a track list with a duplicate track in a different location,
    // see that the name gets munged.
    QFileInfo fileinfo1(m_testDataDir.filePath("cover-test.ogg"));
    TrackPointer track1(TrackInfoObject::newTemporary(fileinfo1));

    // Create a file with the same name in a different place.  Its filename
    // should be munged and the file still copied.
    QDir tempPath(QDir::tempPath());
    QFile file2(tempPath.filePath("cover-test.ogg"));
    QFileInfo fileinfo2(file2);
    ASSERT_TRUE(file2.open(QIODevice::WriteOnly));
    file2.close();
    TrackPointer track2(TrackInfoObject::newTemporary(fileinfo2));

    // Set up the worker and answerer.
    QList<TrackPointer> tracks;
    tracks.append(track1);
    tracks.append(track2);
    TrackExportWorker worker(m_exportDir.canonicalPath(), tracks);
    m_answerer.reset(new FakeOverwriteAnswerer(&worker));

    worker.run();
    EXPECT_TRUE(worker.wait(10000));

    EXPECT_EQ(2, m_answerer->currentProgress());
    EXPECT_EQ(2, m_answerer->currentProgressCount());

    QFileInfo newfile1(m_exportDir.filePath("cover-test.ogg"));
    EXPECT_TRUE(newfile1.exists());
    QFileInfo newfile2(m_exportDir.filePath("cover-test-0001.ogg"));
    EXPECT_TRUE(newfile2.exists());

    // Remove the track we created.
    tempPath.remove("cover-test.ogg");
}
Exemplo n.º 28
0
char *realpath(const char *path, char *resolved_path) {
  BPath tempPath(path,NULL,true);
  strcpy(resolved_path,tempPath.Path());
  return resolved_path;
}
Exemplo n.º 29
0
bool Deck::importMnemosyne(QString fileName)
{
    QFileInfo fi(fileName);
    QString baseName = fi.baseName().toLower();

    QString tempFolder = utils::combinePaths(tempPath(), baseName);
    QString metadataPath = utils::combinePaths(tempFolder, "METADATA"); 
    QString cardsPath = utils::combinePaths(tempFolder, "cards.xml"); 

    utils::createDirectory(tempFolder);

    Compressor c;
    if(!c.decompressFolder(fileName, tempFolder)) {
        return false;
    }

    /// import metadata
    ///
    QTextStream s;
    QFile metadataFile(metadataPath);

    metadataFile.open(QIODevice::ReadOnly | QIODevice::Text);

    if(!metadataFile.isOpen())
        return false;

    s.setDevice(&metadataFile);
    s.setCodec("UTF-8");

    QStringList sl;
    QString l = s.readLine();
    while (!s.atEnd()) {
        sl = l.split(":");

        if(sl.size()>1) {
            if(sl[0]=="tags")
                setTags(sl[1]);
            else if(sl[0]=="notes")
                setDesc(sl[1]);
            else if(sl[0]=="author_name")
                setAuthor(sl[1]);
            else if(sl[0]=="card_set_name")
                setName(sl[1]);
        }

        l = s.readLine();
    }

    /// read cards
    QDomDocument domDocument;
    QString errorStr;
    int errorLine;
    int errorColumn;
    QString front, back, level;
    QFile cardsFile(cardsPath);

    cardsFile.open(QIODevice::ReadOnly | QIODevice::Text);

    if(!cardsFile.isOpen())
        return false;

    if (!domDocument.setContent(&cardsFile, true, &errorStr, &errorLine,
        &errorColumn)) {
            qDebug() << QString("Parse error at line %1, column %2:\n%3")
                .arg(errorLine)
                .arg(errorColumn)
                .arg(errorStr);
            return false;
    }

    QDomElement root = domDocument.documentElement();
    QString rootName = root.tagName().toLower();

    if (rootName == "opensm2sync") {
        QDomNodeList nodes = root.elementsByTagName("log");
        QDomNode node;
        QDomElement elnode;
        
        int count = nodes.count();

        for(int no = 0; no < count; no++) {
            node = nodes.at(no);

            if(node.attributes().namedItem("type").nodeValue()=="16") {
                elnode = node.firstChildElement("f");
                front = elnode.text();

                elnode = node.firstChildElement("b");
                back = elnode.text();

                if(!front.isEmpty()) {
                    Card *card = new Card();

                    card->updateFront(front);
                    card->updateBack(back);

                    addCard(card);
                }
            }
        }
    }

    metadataFile.close();
    cardsFile.close();

    utils::removeFile(metadataPath);
    utils::removeFile(cardsPath);
    utils::copyDirectory(getDeckPath(), tempFolder);

    return true;
}
Exemplo n.º 30
0
bool ProjectBase::createTempDir()
{
    return LowTools::mkpath(tempPath(),true);
}