Ejemplo n.º 1
0
QString BtsSpawnClient::getDataPath()
{
	if(!p->dataPath.isEmpty())
		return p->dataPath;

	QDir dataPath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
	dataPath.mkpath("sync_storage");

	if(!dataPath.cd("sync_storage"))
	{
		qWarning("Failed creating sync storage dir!");
		return QString();
	}

	p->dataPath = dataPath.absolutePath();

	return p->dataPath;
}
Ejemplo n.º 2
0
bool BrisaConfigurationManager::setGlobalConfigPath(QString &path)
{
	if (instance) {
		qWarning() << "BrisaConfigurationManager was already instanciated. "
				   "Call setConfigFilePath to change the already existing instance configuration file path.";
	}
	QDir dir;
	if (dir.exists(path)) {
		globalConfigPath = path;
		return true;
	} else if (dir.mkpath(path)) {
		qWarning() << "Path " << path << " does not exist. Creating path...";
		globalConfigPath = path;
		return true;
	}
	checkConfigFile = false;
	return false;
}
// need to refactor this out
// we probably want the process instead of this function
// cmakeproject then could even run the cmake process in the background, adding the files afterwards
// sounds like a plan
void CMakeManager::createXmlFile(Utils::QtcProcess *proc, const QString &arguments,
                                 const QString &sourceDirectory, const QDir &buildDirectory,
                                 const Utils::Environment &env, const QString &generator)
{
    QString buildDirectoryPath = buildDirectory.absolutePath();
    buildDirectory.mkpath(buildDirectoryPath);
    proc->setWorkingDirectory(buildDirectoryPath);
    proc->setEnvironment(env);

    const QString srcdir = buildDirectory.exists(QLatin1String("CMakeCache.txt")) ?
                QString(QLatin1Char('.')) : sourceDirectory;
    QString args;
    Utils::QtcProcess::addArg(&args, srcdir);
    Utils::QtcProcess::addArgs(&args, arguments);
    Utils::QtcProcess::addArg(&args, generator);
    proc->setCommand(cmakeExecutable(), args);
    proc->start();
}
Ejemplo n.º 4
0
void FlashcardsDeck::saveResources (QString deckFileName, bool verbose)
{
	if (resourceAbsoluteToDeckPathMap.empty()) return;
	verify (!(mediaDirectoryName.isEmpty() || mediaDirectoryName.isNull()), "Media directory not specified or empty.");

	QDir createMediaIn = QFileInfo (deckFileName).dir();
	verify (createMediaIn.exists(), "Failed to access parent directory of '" + deckFileName + "'.");

	verify (createMediaIn.mkpath (mediaDirectoryName), "Failed to create media subdirectory '" + mediaDirectoryName + "' for deck file '" + deckFileName +"'.");

	for (std::pair <QString, QString> absoluteToRelative : resourceAbsoluteToDeckPathMap.toStdMap())
	{
		QString destination = createMediaIn.absolutePath() + "/" + mediaDirectoryName + "/" + absoluteToRelative.second;

		QFileInfo sourceFile (absoluteToRelative.first), destinationFile (destination);
		if (destinationFile.exists() && sourceFile.lastModified() == destinationFile.lastModified() && sourceFile.size() == destinationFile.size())
		{
			if (verbose)
				qstderr << "File '" << absoluteToRelative.first << "' has same last accessed time as '" << destination << "': skipping." << endl;
			continue;
		}

		//bool copied = QFile::copy (absoluteToRelative.first, destination);

		// Copy preserving timestamps via 'cp'
		bool copied = false;

#ifdef  Q_OS_LINUX
		QProcess process;
		process.start ("cp", QStringList() << sourceFile.absoluteFilePath() << destinationFile.absoluteFilePath() << "--preserve=timestamps");
		verify (process.waitForFinished(), "Failed to wait for 'cp' to finish.");
		copied = process.exitCode() == 0;
#else
#error This platform is not supported. Add more cases or test if the existing code works.
#endif

		verify (copied, "Failed to copy '" + absoluteToRelative.first + "' to '" + destination + "'.");

		if (verbose)
			qstderr << "Copied resource '" + absoluteToRelative.first + "' to '" + destination + "'." << endl;
	}
	if (verbose)
		qstderr << resourceAbsoluteToDeckPathMap.size() << " resources saved." << endl;
}
Ejemplo n.º 5
0
QString getIniFile( const QString& s )
{
#if defined Q_OS_MAC
	return QString( "%1/../%2.ini" ).arg( QApplication::applicationDirPath() ).arg( s );
#elif defined Q_OS_WIN
	/* We used to store the ini file in the application directory, before moving to the
	correct location, but some users like it better the old way... so if we find a .ini
	file in the application directory, we're using it */
	QString oldinifile = QString( "%1/%2.ini" ).arg( QApplication::applicationDirPath() ).arg( s );
	if ( QFile::exists( oldinifile )) return oldinifile;

	return QString( "%1/%2.ini" ).arg( getDataDirPath() ).arg(s);
#else
	/*
	We used to store the ini file in ~/.$SOMETHING/$SOMETHING.ini, were $SOMETHING could
	be at least yabause or yabause-qt
	With release 0.9.12 we moved to the XDG compliant location ~/.config/yabause/qt/yabause.ini
	and we don't want this location to depends on the program name anymore.
	This code is trying to copy the content from the old location to the new.
	In the future, we may drop support for the old location and rewrite the following to:

	return QString( "%1/.config/yabause/qt/yabause.ini" ).arg( QDir::homePath() );
	*/

	QString xdginifile = QString( "%1/.config/yabause/qt/yabause.ini" ).arg( QDir::homePath() );
	QString oldinifile = QString( "%1/.%2/%2.ini" ).arg( QDir::homePath() ).arg( s );

	if ( not QFile::exists( xdginifile ) )
	{
		QString xdgpath = QString( "%1/.config/yabause/qt" ).arg( QDir::homePath() );
		if ( ! QFile::exists( xdgpath ) )
		{
			// for some reason, Qt doesn't provide a static mkpath method O_o
			QDir dir;
			dir.mkpath( xdgpath );
		}

		if ( QFile::exists( oldinifile ) )
			QFile::copy( oldinifile, xdginifile );
	}

	return xdginifile;
#endif
}
void Launcher_page::cpWallpaper(QString extWallpaperPath)
{
    /* 用bash脚本拷贝壁纸
    QStringList strList;
    QString command = Global::mingw64 + "\\bash.exe";
    strList << "test.sh" << Global::mingw64 << Global::srcPath << extWallpaperPath << "2";
    qDebug() << command;
   // strList << Global::mingw64 << Global::prj_home_path + "\\bin\\bash_helper.sh"<< Global::srcPath << extWallpaperPath << "2";
   qDebug() << strList;
    p->start("bash", strList);
*/

    QDir *extDir = new QDir(extWallpaperPath);
    QStringList fileList = extDir->entryList();
    QString pathWallpaperOverlay = Global::srcPath + "/" + Global::overlayPath + "/packages/apps/Launcher3/res/drawable-nodpi";
    QString wallpaperXml =  Global::srcPath + "/packages/apps/Launcher3/res/values/wallpapers.xml";
    QDir *overlayDir = new QDir(pathWallpaperOverlay);
    if(fileList.length() > 2)
    {
        if(!overlayDir->mkpath(pathWallpaperOverlay))
        {
            qDebug() << "mkpath fail.. " << pathWallpaperOverlay;
            QMessageBox::critical(this, tr("错误警告 : "), tr("创建目录") + pathWallpaperOverlay + tr("失败,请检查目标路径是否有可写权限,或目标路径被文件浏览器打开"));
            return;
        }
        for(int i = 2; i < fileList.length(); i++)
        {
            QStringList nameList = fileList[i].split(".");
            QImage srcImg(extWallpaperPath + "/" + fileList[i]);
            qDebug() << extWallpaperPath + "/" + fileList[i];
            QImage smlImg = srcImg.scaled(200,200);
            if(!smlImg.save(pathWallpaperOverlay + "/" + nameList[0] + "_small." + nameList[1]))
            {
                qDebug() << "small image save fail";
            }
            QFile::copy(extWallpaperPath + "/" + fileList[i], pathWallpaperOverlay +"/" + fileList[i]);
            qDebug() << pathWallpaperOverlay + "/" + nameList[0] + "_small." + nameList[1];
            textHelper.addWallpaperXml(wallpaperXml, nameList[0]);
        }
    }else
    {
        QMessageBox::information(this, tr("提示~~~"), tr("壁纸文件夹内空。。。。。"));
    }
}
Ejemplo n.º 7
0
/*!
 * \brief Database::Database
 * \param databaseDir directory to load/store the database
 * \param schemaDirectory directory of the SQL schema for the database
 * \param parent
 */
Database::Database(const QString &databaseDir, const QString &schemaDirectory,
                   QObject* parent) :
    QObject(parent),
    m_databaseDirectory(databaseDir),
    m_sqlSchemaDirectory(schemaDirectory),
    m_db(new QSqlDatabase())
{
    if (!QFile::exists(m_databaseDirectory)) {
        QDir dir;
        bool createOk = dir.mkpath(m_databaseDirectory);
        if (!createOk)
            qWarning() << "Unable to create DB directory" << m_databaseDirectory;
    }

    m_albumTable = new AlbumTable(this, this);
    m_mediaTable = new MediaTable(this, this);

    // Open the database.
    if (!openDB())
        restoreFromBackup();

    // Attempt a query to make sure the DB is valid.
    QSqlQuery test_query(*m_db);
    if (!test_query.exec("SELECT * FROM SQLITE_MASTER LIMIT 1")) {
        logSqlError(test_query);
        restoreFromBackup();
    }

    QSqlQuery query(*m_db);
    // Turn synchronous off.
    if (!query.exec("PRAGMA synchronous = OFF")) {
        logSqlError(query);
        return;
    }

    // Enable foreign keys.
    if (!query.exec("PRAGMA foreign_keys = ON")) {
        logSqlError(query);
        return;
    }

    // Update if needed.
    upgradeSchema(schemaVersion());
}
Ejemplo n.º 8
0
void tst_QMimeDatabase::initTestCase()
{
    QVERIFY2(m_temporaryDir.isValid(), qPrintable(m_temporaryDir.errorString()));
    QStandardPaths::setTestModeEnabled(true);
    m_localMimeDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/mime";
    if (QDir(m_localMimeDir).exists()) {
        QVERIFY2(QDir(m_localMimeDir).removeRecursively(), qPrintable(m_localMimeDir + ": " + qt_error_string()));
    }
    QString errorMessage;

#ifdef USE_XDG_DATA_DIRS
    // Create a temporary "global" XDG data dir for later use
    // It will initially contain a copy of freedesktop.org.xml
    QVERIFY2(m_temporaryDir.isValid(),
             ("Could not create temporary subdir: " + m_temporaryDir.errorString()).toUtf8());
    const QDir here = QDir(m_temporaryDir.path());
    m_globalXdgDir = m_temporaryDir.path() + QStringLiteral("/global");
    const QString globalPackageDir = m_globalXdgDir + QStringLiteral("/mime/packages");
    QVERIFY(here.mkpath(globalPackageDir));

    qputenv("XDG_DATA_DIRS", QFile::encodeName(m_globalXdgDir));
    qDebug() << "\nGlobal XDG_DATA_DIRS: " << m_globalXdgDir;

    const QString freeDesktopXml = QStringLiteral("freedesktop.org.xml");
    const QString xmlFileName = QLatin1String(RESOURCE_PREFIX) + freeDesktopXml;
    const QString xmlTargetFileName = globalPackageDir + QLatin1Char('/') + freeDesktopXml;
    QVERIFY2(copyResourceFile(xmlFileName, xmlTargetFileName, &errorMessage), qPrintable(errorMessage));
#endif

    m_testSuite = QFINDTESTDATA("testfiles");
    if (m_testSuite.isEmpty())
        qWarning("%s", qPrintable(testSuiteWarning()));

    errorMessage = QString::fromLatin1("Cannot find '%1'");
    for (uint i = 0; i < sizeof additionalMimeFiles / sizeof additionalMimeFiles[0] - 1; i++) {
        const QString resourceFilePath = QString::fromLatin1(RESOURCE_PREFIX) + QLatin1String(additionalMimeFiles[i]);
        QVERIFY2(QFile::exists(resourceFilePath), qPrintable(errorMessage.arg(resourceFilePath)));
        m_additionalMimeFileNames.append(QLatin1String(additionalMimeFiles[i]));
        m_additionalMimeFilePaths.append(resourceFilePath);
    }

    initTestCaseInternal();
    m_isUsingCacheProvider = !qEnvironmentVariableIsSet("QT_NO_MIME_CACHE");
}
Ejemplo n.º 9
0
void HighScoresModel::loadData()
{
    QDir gluonDir = QDir::home();
    gluonDir.mkpath( ".gluon/" + QString( serviceURI ) );
    gluonDir.cd( ".gluon/" + QString( serviceURI ) );
    QString filename = gluonDir.absoluteFilePath( "highscores.gdl" );

    QFile dataFile( filename );
    while( 1 )
    {
        if( !dataFile.open( QIODevice::ReadOnly ) )
        {
            if( !QFile::exists( filename ) )
            {
                qDebug() << "Cannot find the file " << filename << ", creating new";
                dataFile.close();
                saveData();         //Create a blank file if it doesn't exist
                continue;       //Try to open again
            }
            else
            {
                qDebug() << "Cannot open the file " << filename;
                return;     //return from loadData()
            }
        }
        else
        {
            break;      //File opened successfully
        }
    }

    QTextStream highScoresReader( &dataFile );
    QString fileContents = highScoresReader.readAll();
    dataFile.close();

    if( fileContents.isEmpty() )
    {
        qDebug() << "Something is wrong with the high scores file";
        return;
    }

    QList<GluonObject*> highScores = GluonCore::GDLHandler::instance()->parseGDL( fileContents, 0 );
    rootNode = highScores.at( 0 );
}
Ejemplo n.º 10
0
void FileReceiver::receiveFile(void) {
	QDir dir = QFileInfo(filePath).dir();
	if(!dir.exists())
		dir.mkpath(dir.absolutePath());

	file = new QFile(filePath);

	if(file->open(QIODevice::WriteOnly)) {
		buffer = new char[bufferSize];
		active = true;

		timer = new QTimer(this);
		connect(timer, SIGNAL(timeout()), this, SLOT(timer_timeout()));
		timer->start(timeout);
	} else {
		socket->close();
		emit progressUpdated(FM_Receive, FO_Error, type, &id, &peerId, &filePath);
	}
}
Ejemplo n.º 11
0
void MainWindow::playerMoved(int player, const Tile * tile, const MoveHistoryEntry & move)
{
	emit updateNeeded();
	boardUi->playerMoved(player, tile, move);

	if (move.move.tileMove.isNull())
		emit gameEvent(tr("A non-suitable tile was drawn and discarded."));
	else
		emit gameEvent(tr("Player %1 moved.").arg(player+1));

//	QSettings settings;
//	settings.beginGroup("games");
//	int size = settings.beginReadArray("game");
//	settings.endArray(); //game

//	settings.beginWriteArray("game");
//	settings.setArrayIndex(size-1);

//	int moveSize = settings.beginReadArray("moves");
//	settings.endArray(); //moves

//	auto const & history = game->getMoveHistory();
//	settings.beginWriteArray("moves");
//	for (size_t i = moveSize; i < history.size(); ++i)
//	{
//		settings.setArrayIndex((int)i);
//		MoveHistoryEntry const & m = history[i];
//		settings.setValue("tile", m.tile);
//		settings.setValue("x", m.move.tileMove.x);
//		settings.setValue("y", m.move.tileMove.y);
//		settings.setValue("orientation", m.move.tileMove.orientation);
//		settings.setValue("meeple", m.move.meepleMove.nodeIndex);
//	}
//	settings.endArray(); //moves

//	settings.endArray(); //game
//	settings.endGroup(); //games

	QString const & dataLoc = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
	QDir dir = QDir(dataLoc).absoluteFilePath("games");
	if (dir.mkpath(".") && gameStartTimestamp != -1)
		game->storeToFile(dir.absoluteFilePath(QString::number(gameStartTimestamp)));
}
Ejemplo n.º 12
0
void XCA_application::switchLanguage(QAction* a)
{
	QLocale lang = a->data().toLocale();
	setupLanguage(lang);

	QString dir = getUserSettingsDir();
	QFile file(dir +QDir::separator() +"defaultlang");

	if (lang == QLocale::system()) {
		file.remove();
		return;
	}

	QDir d;
	d.mkpath(dir);
	if (file.open(QIODevice::WriteOnly)) {
		file.write(lang.name().toUtf8());
	}
}
Ejemplo n.º 13
0
Cache::Cache(QObject *parent) :
    QObject(parent)
{
    m_cacheonly = false;

    QDesktopServices dirs;
    m_path = dirs.storageLocation(QDesktopServices::CacheLocation);
    m_path += "/nelisquare/";
    //qDebug() << "Cache location: " << m_path;

    if (m_path.length()) {
        QDir dir;
        if (!dir.mkpath(m_path))
            qDebug () << "Error creating cache directory";
    }

    manager = new QNetworkAccessManager (this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),SLOT(onDownloadFinished(QNetworkReply*)));
}
Ejemplo n.º 14
0
void TextEdit::fileOpen(const QString &curFile) {
    QDir dir;
	fileName = curFile;
	if(!QFile::exists(path + fileName)||fileName.isEmpty())
	{
		QString newFile("");
		do
		{
			newFile = "page_" + QTime::currentTime().toString("mmsszzz") + ".html";
		}
		while (QFile::exists(path + newFile));
		fileName = newFile;
	}
	name = fileName;
	name.replace(".html","");
	QString imagesPath = path + name;
	dir.mkpath(imagesPath);
	load(path + fileName);
}
Ejemplo n.º 15
0
int Database::init ()
{
    _db = QSqlDatabase::database("quote");
    if (! _db.isOpen())
    {
        QString s = QDir::homePath() + "/QtTrader/db/";
        QDir dir;
        if (! dir.mkpath(s))
        {
            qDebug() << "Database::init: error creating database" << s;
            return 0;
        }

        s.append("quote");

        _db = QSqlDatabase::addDatabase("QSQLITE", "quote");
        _db.setHostName("QtTrader");
        _db.setDatabaseName(s);
        _db.setUserName("QtTrader");
        _db.setPassword("QtTrader");
        if (! _db.open())
        {
            qDebug() << "Database::init:" << _db.lastError().text();
            return 0;
        }
    }

    QSqlQuery q(_db);
    QString s = "CREATE TABLE IF NOT EXISTS symbolIndex (";
    s.append("a INTEGER PRIMARY KEY"); // auto increment index
    s.append(", name TEXT"); // entity name
    s.append(", key TEXT"); // attribute
    s.append(", value TEXT"); // value
    s.append(")");
    q.exec(s);
    if (q.lastError().isValid())
    {
        qDebug() << "Database::init:" << _db.lastError().text();
        return 0;
    }

    return 1;
}
Ejemplo n.º 16
0
LastFmPlugin::LastFmPlugin( QObject* parent )
    : InfoPlugin(parent)
    , m_scrobbler( 0 )
    , m_authJob( 0 )
{
    QSet< InfoType > supportedTypes;
    supportedTypes << InfoMiscSubmitScrobble << InfoMiscSubmitNowPlaying << InfoAlbumCoverArt;
    qobject_cast< InfoSystem* >(parent)->registerInfoTypes(this, supportedTypes);
    
/*
      Your API Key is 7194b85b6d1f424fe1668173a78c0c4a
      Your secret is ba80f1df6d27ae63e9cb1d33ccf2052f
*/

    // Flush session key cache
    TomahawkSettings::instance()->setLastFmSessionKey( QByteArray() );

    lastfm::ws::ApiKey = "7194b85b6d1f424fe1668173a78c0c4a";
    lastfm::ws::SharedSecret = "ba80f1df6d27ae63e9cb1d33ccf2052f";
    lastfm::ws::Username = TomahawkSettings::instance()->lastFmUsername();
    
    m_pw = TomahawkSettings::instance()->lastFmPassword();
    
    if( TomahawkSettings::instance()->scrobblingEnabled() && !lastfm::ws::Username.isEmpty() )
    {
        createScrobbler();
    }
        
    //HACK work around a bug in liblastfm---it doesn't create its config dir, so when it
    // tries to write the track cache, it fails silently. until we have a fixed version, do this
    // code taken from Amarok (src/services/lastfm/ScrobblerAdapter.cpp)
#ifdef Q_WS_X11
    QString lpath = QDir::home().filePath( ".local/share/Last.fm" );
    QDir ldir = QDir( lpath );
    if( !ldir.exists() )
    {
        ldir.mkpath( lpath );
    }
#endif

    connect( TomahawkSettings::instance(), SIGNAL( changed() ),
                                             SLOT( settingsChanged() ), Qt::QueuedConnection );
}
Ejemplo n.º 17
0
void MainWindow::session_save()
{
    QDir dir;
    #if QT_VERSION >= 0x050400
    QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    #else
    QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    #endif
    if(dir.mkpath(path)) {
        dir.cd(path);
        QString driver_name = _session.get_device()->name();
        QString mode_name = QString::number(_session.get_device()->dev_inst()->mode);
        QString file_name = dir.absolutePath() + "/" + driver_name + mode_name + ".dsc";
        if (strncmp(driver_name.toLocal8Bit(), "virtual", 7) &&
            !file_name.isEmpty()) {
            store_session(file_name);
        }
    }
}
Ejemplo n.º 18
0
void NetworkAccessManager::save(void) {
  _cookieJar->save();
  QString path = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/";
  QDir dir;
  if(!dir.mkpath(path)) {
    return;
  }
  QFile file(path + "trustedDomains");
  if(!file.open(QIODevice::WriteOnly)) {
    return;
  }
  QByteArray array;
  for(int i = 0; i < _trustedDomains.count(); i++) {
    array += _trustedDomains.at(i).toString().toUtf8();
    array += "\n";;
  }
  file.write(array);
  file.close();
}
Ejemplo n.º 19
0
int ApplicationManager::init(){
    if(!isInitiated){
        //Makin' the universe utf-8, as it should have been at the first place...
        //        QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); // Commented out because of Bug #27
        QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
        QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));

        //Setting application info for preferences interface

        FileManager::init();

        PreferencesManager::loadSettings();

        LanguageManager::init();

        TrayManager::init();

        HotkeyManager::init();

        CevirgecLibrary::init();

        OnlineLookupSourceManager::init();

        ClipboardManager::init();

        ThemeManager::init();

        //Create the path to save data.cdx when closing
        QDir qdir;
        qdir.mkpath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));

        QString startMessage;
        startMessage.append(("You can reach Cevirgec from system tray\nPress ")).
                append(PreferencesManager::getHotKeyOpenSettings().toUpper()).
                append(" to open Preferences Window");
        TrayManager::showTrayMessage("Cevirgec started", startMessage, QSystemTrayIcon::Information, 5000);

        isInitiated = true;
        return 0;
    }
    qCritical("@ApplicationManager::init: Application has been already initialized check the code!");
    return -31;
}
Ejemplo n.º 20
0
Future<GitRepo *> GitRepo::init(const QDir &dir)
{
	return async([dir](Notifier)
	{
		initGit();
		if (!dir.mkpath(dir.absolutePath())) {
			throw Exception("Unable to create directory to init");
		}

		std::unique_ptr<GitRepo> repo = std::make_unique<GitRepo>(dir);

		git_repository_init_options opts = GIT_REPOSITORY_INIT_OPTIONS_INIT;
		opts.flags |= GIT_REPOSITORY_INIT_MKPATH;
		repo->m_repo = GitResource<git_repository>::create(&git_repository_init_ext, &git_repository_free,
														   dir.absolutePath().toLocal8Bit(), &opts);

		return repo.release();
	});
}
Ejemplo n.º 21
0
//runs before all tests
void TestQgsWcsPublicServers::init()
{
  // init QGIS's paths - true means that all path will be inited from prefix
  QgsDebugMsg( "Entered" );

  // Unfortunately this seems to be the only way to set timeout, we try to reset it
  // at the end but it can be canceled before ...
  QSettings settings;
  mOrigTimeout = settings.value( "/qgis/networkAndProxy/networkTimeout", "20000" ).toInt();
  settings.setValue( "/qgis/networkAndProxy/networkTimeout", mTimeout );

  //mCacheDir = QDir( "./wcstestcache" );
  mCacheDir = QDir( mCacheDirPath );
  if ( !mCacheDir.exists() )
  {
    QDir myDir = QDir::root();
    if ( !myDir.mkpath( mCacheDir.absolutePath() ) )
    {
      QgsDebugMsg( "Cannot create cache dir " + mCacheDir.absolutePath() );
      QCoreApplication::exit( 1 );
    }
  }

  mHead << "Coverage";

  QStringList providers;
  providers << "wcs" << "gdal";
  Q_FOREACH ( const QString& provider, providers )
  {
    QString prefix = provider == "gdal" ? "GDAL " : "";
    mHead << prefix + "CRS";
    mHead << prefix + "Width";
    mHead << prefix + "Height";
    mHead << prefix + "Extent";
    mHead << prefix + "Snap";
    mHead << prefix + "Bands";
    mHead << prefix + "Type";
    mHead << prefix + "Min";
    mHead << prefix + "Max";
    mHead << prefix + "Values";
    mHead << prefix + "Colors";
    mHead << prefix + "Time (s)";
  }
Ejemplo n.º 22
0
/**
 * @brief Returns the path to the database (on disk)
 * @return
 */
QString DatabaseService::getDiskDatabasePath() {

    QStandardPaths::StandardLocation location;

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
    location = QStandardPaths::AppDataLocation;
#else
    location = QStandardPaths::GenericDataLocation;
#endif

    // get the path to store the database
    QString path = QStandardPaths::writableLocation(location);
    QDir dir;

    // create path if it doesn't exist yet
    dir.mkpath(path);

    return path + QDir::separator() + "QOwnNotes.sqlite";
}
Ejemplo n.º 23
0
/*!
    \brief Creates the file on file system

    The given text file \a fileName is created on file system. If directory
    doesn't exist yet it's created. In case the file already exists, user is
    asked whether to overwrite or not.
    File is filled with the \a content.
    If some error occurs the error message is available via \a errorMessage (if
    not null).
    \return true for successfully created file
 */
bool FileHelper::createFile(const QString &fileName, const QString &content,
        QString *errorMessage)
{
    const QFileInfo fileInfo(fileName);

    // Create the directory if not created yet
    const QDir dir = fileInfo.absoluteDir();
    if (!dir.exists()) {
        if (!dir.mkpath(dir.absolutePath())) {
            if (errorMessage != 0)
                *errorMessage =
                    QObject::tr("Unable to create the directory '%1'.")
                        .arg(QDir::toNativeSeparators(dir.absolutePath()));
            return false;
        }
    }

    const bool overwriteAllowed = promptOverwrite(fileName, errorMessage);
    if (!overwriteAllowed)
        return true; // User discarded creation means method was successful

    QFile file(fileName);
    QIODevice::OpenMode flags = QIODevice::WriteOnly | QIODevice::Truncate;
    //! \todo Extend functionality in case we need to deal with binary file
    flags |= QIODevice::Text;

    // Create or re-open and clear the file
    if (!file.open(flags)) {
        if (errorMessage != 0)
            *errorMessage =
                QObject::tr("Unable to open '%1' for writing: %2")
                    .arg(fileName, file.errorString());
        return false;
    }

    // Add file's default content
    if (!content.isEmpty()) {
        QTextStream fileStream(&file);
        fileStream << content;
    }

    return true;
}
Ejemplo n.º 24
0
void DB::import(QString audioFilePath, QString annotationFilePath, QHash<QString, QVariant> tagData) {
  try {
    //import file
    int id = work_find_by_audio_file_location(audioFilePath);
    QString movedAnnotation;
    bool update_existing = false;

    if (id == 0) {
      id = work_create(tagData, audioFilePath);
      movedAnnotation = default_file_location(id, tagData);
    } else {
      update_existing = true;
      QString dummyAudioPath;
      if (!find_locations_by_id(id, dummyAudioPath, movedAnnotation)) {
        update_existing = false;
        movedAnnotation = default_file_location(id, tagData);
      }
    }

    //move the annotation
    QFileInfo movedInfo(movedAnnotation);
    QDir dir = movedInfo.dir();
    if (!dir.mkpath(dir.path()))
      throw std::runtime_error("couldn't create path to annotation file: " + movedAnnotation.toStdString());
    if (update_existing)
      QFile::remove(movedAnnotation);
    if (!QFile::rename(annotationFilePath, movedAnnotation))
      throw std::runtime_error("couldn't move to annotation file to: " + movedAnnotation.toStdString());

    //add the annotation
    work_update_attribute(id, "annotation_file_location", movedAnnotation);

    //add the median tempo
    auto it = tagData.find("tempo_median");
    if (it != tagData.end())
      work_descriptor_create_or_update(id, "tempo_median", it.value().toDouble());
  } catch (std::runtime_error& e) {
    emit(importError(audioFilePath, QString::fromStdString(e.what())));
    return;
  }
  emit(importSuccess(audioFilePath));
}
Ejemplo n.º 25
0
int main(int argc, char *argv[])
{
    if ( argc != 2 )
    {
        /* display usage on error stream */
        fprintf(stderr, "usage: znm-project project_name\n\n");
        exit(1);  /* exit status of the program : non-zero for errors */
    }

    if ( QString("--help") == argv[1] )
    {
        printf ("usage: znm-project project_name\nCreates a zenom project.\n\n");
        exit(0);  /* exit status of the program : non-zero for errors */
    }

    QDir projectDir;
    if ( projectDir.exists( argv[1] ) )
    {
        fprintf(stderr, "The project cannot be created because '%s' folder already exists.\n", argv[1]);
        exit(1);  /* exit status of the program : non-zero for errors */
    }

    projectDir.mkpath( argv[1] );
    projectDir.cd( argv[1] );

    QFileInfo programFileInfo( getexepath() );
    QString projectName( QFileInfo(argv[1]).fileName() );

    createFile( programFileInfo.dir().filePath("znm-project-main.template"), projectDir.filePath("main.cpp"), projectName );
    createFile( programFileInfo.dir().filePath("znm-project-makefile.template"), projectDir.filePath("Makefile"), projectName );

    // Open project file to write
    QFile configFile( projectDir.filePath(QString("%1.znm").arg(projectName)) );
    if ( !configFile.open(QFile::WriteOnly | QFile::Text) )
    {
        fprintf(stderr, "The project cannot be created because the file '%s' could not be opened.\n", configFile.fileName().toAscii().data());
        exit(1);  /* exit status of the program : non-zero for errors */
    }
    configFile.close();

    return 0;
}
Ejemplo n.º 26
0
bool UAVObjectGeneratorMatlab::generate(UAVObjectParser* parser,QString templatepath,QString outputpath) {

    QString gcsRevision = QString::fromLatin1(Core::Constants::GCS_REVISION_STR);

    fieldTypeStrMatlab << "int8" << "int16" << "int32"
        << "uint8" << "uint16" << "uint32" << "single" << "uint8";
    fieldSizeStrMatlab << "1" << "2" << "4"
        << "1" << "2" << "4" << "4" << "1";

    QDir matlabTemplatePath = QDir( templatepath + QString("ground/gcs/src/plugins/uavobjects"));
    QDir matlabOutputPath = QDir( outputpath + QString("matlab") );
    matlabOutputPath.mkpath(matlabOutputPath.absolutePath());

    QString matlabCodeTemplate = readFile( matlabTemplatePath.absoluteFilePath( "uavobjecttemplate.m") );

    if (matlabCodeTemplate.isEmpty() ) {
        std::cerr << "Problem reading matlab templates" << endl;
        return false;
    }

    for (int objidx = 0; objidx < parser->getNumObjects(); ++objidx) {
        ObjectInfo* info=parser->getObjectByIndex(objidx);
        int numBytes=parser->getNumBytes(objidx);
        process_object(info, numBytes);
    }

    matlabCodeTemplate.replace( QString("$(GCSREVISION)"), gcsRevision);
    matlabCodeTemplate.replace( QString("$(INSTANTIATIONCODE)"), matlabInstantiationCode);
    matlabCodeTemplate.replace( QString("$(SWITCHCODE)"), matlabSwitchCode);
    matlabCodeTemplate.replace( QString("$(CLEANUPCODE)"), matlabCleanupCode);
    matlabCodeTemplate.replace( QString("$(SAVEOBJECTSCODE)"), matlabSaveObjectsCode);
    matlabCodeTemplate.replace( QString("$(ALLOCATIONCODE)"), matlabAllocationCode);
    matlabCodeTemplate.replace( QString("$(EXPORTCSVCODE)"), matlabExportCsvCode);

    bool res = writeFile( matlabOutputPath.absolutePath() + "/LogConvert.m.pass1", matlabCodeTemplate );
    if (!res) {
        cout << "Error: Could not write output files" << endl;
        return false;
    }

    return true; // if we come here everything should be fine
}
Ejemplo n.º 27
0
void Queue::saveQueues()
{
	if (!m_bLoaded)
	{
		qDebug() << "Not saving queues as they haven't been loaded yet.";
		return;
	}

	QDomDocument doc;
	QDomElement root;
	QFile file;
	QDir dir = QDir::home();
	
    dir.mkpath(".local/share/fatrat");
	if(!dir.cd(".local/share/fatrat"))
		return;
	file.setFileName(dir.filePath("queues.xml.new"));
	
	if(!file.open(QIODevice::WriteOnly))
		return;
	
	root = doc.createElement("fatrat");
	doc.appendChild(root);
	
	g_queuesLock.lockForRead();
	
	foreach(Queue* q, g_queues)
	{
		QDomElement elem = doc.createElement("queue");
		elem.setAttribute("name",q->m_strName);
		elem.setAttribute("downlimit",QString::number(q->m_nDownLimit));
		elem.setAttribute("uplimit",QString::number(q->m_nUpLimit));
		elem.setAttribute("dtranslimit",QString::number(q->m_nDownTransferLimit));
		elem.setAttribute("utranslimit",QString::number(q->m_nUpTransferLimit));
		elem.setAttribute("upasdown",QString::number(q->m_bUpAsDown));
		elem.setAttribute("uuid",q->m_uuid.toString());
		elem.setAttribute("defaultdir",q->m_strDefaultDirectory);
		elem.setAttribute("movedir",q->m_strMoveDirectory);
		
		q->saveQueue(elem,doc);
		root.appendChild(elem);
	}
Ejemplo n.º 28
0
/*!
  Recursive copy from directory to another.
  Note that this updates the file stamps on Linux but not on Windows.
  */
void TestBlackboxBase::ccp(const QString &sourceDirPath, const QString &targetDirPath)
{
    QDir currentDir;
    QDirIterator dit(sourceDirPath, QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden);
    while (dit.hasNext()) {
        dit.next();
        const QString targetPath = targetDirPath + QLatin1Char('/') + dit.fileName();
        currentDir.mkpath(targetPath);
        ccp(dit.filePath(), targetPath);
    }

    QDirIterator fit(sourceDirPath, QDir::Files | QDir::Hidden);
    while (fit.hasNext()) {
        fit.next();
        const QString targetPath = targetDirPath + QLatin1Char('/') + fit.fileName();
        QFile::remove(targetPath);  // allowed to fail
        QFile src(fit.filePath());
        QVERIFY2(src.copy(targetPath), qPrintable(src.errorString()));
    }
}
Ejemplo n.º 29
0
void configureLogging()
{
    // Primer comprovem que existeixi el direcotori ~/.starviewer/log/ on guradarem els logs
    QDir logDir = udg::UserLogsPath;
    if (!logDir.exists())
    {
        // Creem el directori
        logDir.mkpath(udg::UserLogsPath);
    }
    // TODO donem per fet que l'arxiu es diu així i es troba a la localització que indiquem. S'hauria de fer una mica més flexible o genèric;
    // està així perquè de moment volem anar per feina i no entretenir-nos però s'ha de fer bé.
    QString configurationFile = "/etc/starviewer/log.conf";
    if (!QFile::exists(configurationFile))
    {
        configurationFile = qApp->applicationDirPath() + "/log.conf";
    }

    LOGGER_INIT(configurationFile.toStdString());
    DEBUG_LOG("Arxiu de configuració del log: " + configurationFile);
}
Ejemplo n.º 30
0
void Profiler::prepareLayout()
{
    QDir dir(dataDirectory);

    if(dir.exists()){
        qDebug() << "return in prepare layout";
        return;
    }

    QDir helper;    

    //Create directory and subdirectories 0-F
    helper.mkpath(dataDirectory);

    for (uint i = 0; i < 16 ; i++) {
        QString str = QString::number(i, 16);
        QString subdir = dataDirectory + str;
        helper.mkdir(subdir);
    }
}