コード例 #1
1
ファイル: utility.cpp プロジェクト: 13221325403/openbr
QList<br::FilesWithLabel> br::getFilesWithLabels(QDir dir)
{
    dir = QDir(dir.canonicalPath());

    QStringList files;
    foreach (const QString &file, dir.entryList(QDir::Files))
        files.append(dir.absoluteFilePath(file));

    QList<br::FilesWithLabel> filesWithLabels;
    filesWithLabels.append(br::FilesWithLabel(dir.dirName(),files));

    foreach (const QString &folder, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {
        QDir subdir(dir);
        bool success = subdir.cd(folder); if (!success) qFatal("cd failure.");
        filesWithLabels.append(getFilesWithLabels(subdir));
    }
    return filesWithLabels;
}
コード例 #2
0
void InitializeMythDirs(void)
{
    installprefix = QString(RUNPREFIX);

    char *tmp_installprefix = std::getenv("MYTHTVDIR");
    if (tmp_installprefix)
        installprefix = tmp_installprefix;

#if CONFIG_DARWIN
    // Work around bug in OS X where applicationDirPath() can crash
    // (if binary is not in a bundle, and is daemon()ized)

    QDir prefixDir = QFileInfo(qApp->argv()[0]).dir();
#else
    QDir prefixDir = qApp->applicationDirPath();
#endif

    if (QDir(installprefix).isRelative())
    {
        // If the PREFIX is relative, evaluate it relative to our
        // executable directory. This can be fragile on Unix, so
        // use relative PREFIX values with care.

        LOG(VB_GENERAL, LOG_DEBUG, QString("Relative PREFIX! (%1), appDir=%2")
            .arg(installprefix) .arg(prefixDir.canonicalPath()));

        if (!prefixDir.cd(installprefix))
        {
            LOG(VB_GENERAL, LOG_ERR,
                QString("Relative PREFIX does not resolve, using %1")
                .arg(prefixDir.canonicalPath()));
        }
        installprefix = prefixDir.canonicalPath();
    }

    LOG(VB_GENERAL, LOG_NOTICE, "Using runtime prefix = " + installprefix);

    char *tmp_confdir = std::getenv("MYTHCONFDIR");
    if (tmp_confdir)
    {
        confdir = QString(tmp_confdir);
        LOG(VB_GENERAL, LOG_NOTICE, QString("Read conf dir = %1").arg(confdir));
        confdir.replace("$HOME", QDir::homePath());
    }
    else
        confdir = QDir::homePath() + "/.mythtv";

    LOG(VB_GENERAL, LOG_NOTICE,
        QString("Using configuration directory = %1").arg(confdir));

    sharedir = installprefix + "/share/mythtv/";
    libdir = installprefix + '/' + QString(LIBDIRNAME) + "/mythtv/";
    themedir = sharedir + "themes/";
    pluginsdir = libdir + "plugins/";
    translationsdir = sharedir + "i18n/";
    filtersdir = libdir + "filters/";
}
コード例 #3
0
ファイル: main.cpp プロジェクト: andresmmera/qucs
int main(int argc, char *argv[])
{
  // apply default settings
  QucsSettings.x = 100;
  QucsSettings.y = 50;
  QucsSettings.dx = 600;
  QucsSettings.dy = 350;
  QucsSettings.font = QFont("Helvetica", 12);
  QucsSettings.QucsHomeDir.setPath(QDir::homePath() + "/.qucs");

  // is application relocated?
  char * var = getenv ("QUCSDIR");
  QDir QucsDir;
  if (var != NULL) {
    QucsDir = QDir(QString(var));
    QucsSettings.LangDir =     QucsDir.canonicalPath() + "/share/qucs/lang/";
    QucsSettings.LibDir =      QucsDir.canonicalPath() + "/share/qucs/library/";
  } else {
    QString QucsApplicationPath = QCoreApplication::applicationDirPath();
#ifdef __APPLE__
    QucsDir = QDir(QucsApplicationPath.section("/bin",0,0));
#else
    QucsDir = QDir(QucsApplicationPath);
    QucsDir.cdUp();
#endif
    QucsSettings.LangDir = QucsDir.canonicalPath() + "/share/qucs/lang/";
    QucsSettings.LibDir  = QucsDir.canonicalPath() + "/share/qucs/library/";
  }

  loadSettings();

  UserLibDir.setPath(QucsSettings.QucsHomeDir.canonicalPath() + "/user_lib/");

  QApplication a(argc, argv);
  a.setFont(QucsSettings.font);

  QTranslator tor( 0 );
  QString lang = QucsSettings.Language;
  if(lang.isEmpty())
    lang = QString(QLocale::system().name());
  tor.load( QString("qucs_") + lang, QucsSettings.LangDir);
  a.installTranslator( &tor );

  QucsLib *qucs = new QucsLib();
  qucs->raise();
  qucs->resize(QucsSettings.dx, QucsSettings.dy); // size and position ...
  qucs->move(QucsSettings.x, QucsSettings.y);     // ... before "show" !!!
  qucs->show();

  int result = a.exec();
  saveApplSettings(qucs);
  delete qucs;
  return result;
}
コード例 #4
0
ファイル: main.cpp プロジェクト: Qucs/qucs
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString LangDir;
    // apply default settings
    QucsSettings.x = 200;
    QucsSettings.y = 100;
    QucsSettings.font = QFont("Helvetica", 12);
    QucsSettings.showConsole = true;

    // is application relocated?
    char * var = getenv ("QUCSDIR");
    QDir QucsDir;
    if (var != NULL) {
      QucsDir = QDir (var);
      QString QucsDirStr = QucsDir.canonicalPath ();
      LangDir =
        QDir::toNativeSeparators(QucsDirStr + "/share/qucs/lang/");
    } else {
      QString QucsApplicationPath = QCoreApplication::applicationDirPath();
#ifdef __APPLE__
      QucsDir = QDir(QucsApplicationPath.section("/bin",0,0));
#else
      QucsDir = QDir(QucsApplicationPath);
      QucsDir.cdUp();
#endif
      LangDir = QucsDir.canonicalPath() + "/share/qucs/lang/";
    }

    loadSettings();

    a.setFont(QucsSettings.font);

    QTranslator tor( 0 );
    QString Lang = QucsSettings.Language;
    if(Lang.isEmpty())
      Lang = QString(QLocale::system().name());
    tor.load( QString("qucs_") + Lang, LangDir);
    a.installTranslator( &tor );

    QucsActiveFilter *w = new QucsActiveFilter();
    w->raise();
    w->move(QucsSettings.x, QucsSettings.y);  // position before "show" !!!
    w->show();
    
    int result = a.exec();
    saveApplSettings(w);
    return result;
}
コード例 #5
0
ファイル: filebrowser.cpp プロジェクト: luznicky/GPXSee
void FileBrowser::setCurrent(const QString &path)
{
	QFileInfo file(path);
	QDir dir = file.absoluteDir();

	if (_files.isEmpty() || _files.last().canonicalPath()
	  != dir.canonicalPath()) {
		if (!_watcher->directories().isEmpty())
			_watcher->removePaths(_watcher->directories());
		_watcher->addPath(dir.canonicalPath());
		_files = dir.entryInfoList(_filter, QDir::Files);
	}

	_index = _files.empty() ? -1 : _files.indexOf(file);
}
コード例 #6
0
static QString _convert_md_raid_path( const QString& dev,bool wait )
{
	QString volume = dev ;

	QString dev_1 ;
	QDir d( "/dev/md/" ) ;
	QDir f ;

	if( wait ){
		/*
		 * wait for a while because things dont always happen as expected if we check too soon.
		 */
		utility::Task::wait( 4 ) ;
	}

	if( d.exists() ){

		QStringList l = d.entryList() ;

		for( const auto& it : l ){

			dev_1 = "/dev/md/" + it ;
			f.setPath( dev_1 ) ;

			if( f.canonicalPath() == dev ){

				volume = dev_1 ;

				break ;
			}
		}
	}

	return volume ;
}
コード例 #7
0
ファイル: TrainDB.cpp プロジェクト: peterjoo/GoldenCheetah
void
TrainDB::initDatabase(QDir home)
{


    if(db->database(sessionid).isOpen()) return;

    // get a connection
    sessionid = "train";
    db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE", sessionid));
    db->setDatabaseName(home.canonicalPath() + "/trainDB");

    if (!db->database(sessionid).isOpen()) {
        QMessageBox::critical(0, qApp->translate("TrainDB","Cannot open database"),
                       qApp->translate("TrainDB","Unable to establish a database connection.\n"
                                       "This feature requires SQLite support. Please read "
                                       "the Qt SQL driver documentation for information how "
                                       "to build it.\n\n"
                                       "Click Cancel to exit."), QMessageBox::Cancel);
    } else {

        // create database - does nothing if its already there
        createDatabase();
    }
}
コード例 #8
0
ファイル: QGAlgoMenuFactory.cpp プロジェクト: rentpath/qgar
// Default constructor
QGAlgoMenuFactory::QGAlgoMenuFactory() {

  // Change cursor to 'wait' while reading file information
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  //-- Locate configuration file
  QDir qgarDir = QDir(getenv("HOME") + QString("/") + QGAR_DIRNAME);  

  // Check if a the file exists in the users home
  if (! findInDir(QGAR_CFG_FILENAME, qgarDir) ) {
    qgarDir = QDir(getenv("QGARSHARE"));
  }


  // Check if a .qgar exists in the qgar shared directory.
  else if (! findInDir(QGAR_CFG_FILENAME, qgarDir) ) {
    return; // No config file found, return without further
    // processing.
  }


  QString filename = qgarDir.canonicalPath() + "/" + QGAR_CFG_FILENAME;

  // Load application entries from config file.
  QGAppRegister reg(filename.toLatin1());
  buildDescrMap(reg);

  QApplication::restoreOverrideCursor();

}
コード例 #9
0
/*
 * Try to initialize the folder (with *write* access)
 */
static QString lamexp_try_init_folder(const QString &folderPath)
{
	static const char *TEST_DATA = "Lorem ipsum dolor sit amet, consectetur, adipisci velit!";
	
	bool success = false;

	const QFileInfo folderInfo(folderPath);
	const QDir folderDir(folderInfo.absoluteFilePath());

	//Create folder, if it does *not* exist yet
	for(int i = 0; (i < 16) && (!folderDir.exists()); i++)
	{
		folderDir.mkpath(".");
	}

	//Make sure folder exists now *and* is writable
	if(folderDir.exists())
	{
		const QByteArray testData = QByteArray(TEST_DATA);
		for(int i = 0; (i < 32) && (!success); i++)
		{
			QFile testFile(folderDir.absoluteFilePath(QString("~%1.tmp").arg(lamexp_rand_str())));
			if(testFile.open(QIODevice::ReadWrite | QIODevice::Truncate))
			{
				if(testFile.write(testData) >= testData.size())
				{
					success = true;
				}
				testFile.remove();
			}
		}
	}

	return (success ? folderDir.canonicalPath() : QString());
}
コード例 #10
0
static QVector< deviceList > _getDevices()
{
	const char * p = "/dev/disk/by-id/" ;

	QDir d( p ) ;
	QDir e ;

	QStringList l = d.entryList() ;

	l.removeOne( "." ) ;
	l.removeOne( ".." ) ;

	QVector< deviceList > devices ;

	if( l.isEmpty() ){

		return devices ;
	}else{
		for( const auto& it : l ){

			e.setPath ( p + it ) ;

			devices.append( deviceList( e.canonicalPath(),it ) ) ;
		}
	}

	return devices ;
}
コード例 #11
0
OsmAnd::ObfsCollection::SourceOriginId OsmAnd::ObfsCollection_P::addDirectory(const QDir& dir, bool recursive)
{
    QWriteLocker scopedLocker(&_sourcesOriginsLock);

    const auto allocatedId = _lastUnusedSourceOriginId++;
    auto sourceOrigin = new DirectoryAsSourceOrigin();
    sourceOrigin->directory = dir;
    sourceOrigin->isRecursive = recursive;
    _sourcesOrigins.insert(allocatedId, qMove(std::shared_ptr<const SourceOrigin>(sourceOrigin)));

    _fileSystemWatcher->addPath(dir.canonicalPath());
    if (recursive)
    {
        QFileInfoList subdirs;
        Utilities::findDirectories(dir, QStringList() << QLatin1String("*"), subdirs, true);
        for(const auto& subdir : subdirs)
        {
            const auto canonicalPath = subdir.canonicalFilePath();
            sourceOrigin->watchedSubdirectories.insert(canonicalPath);
            _fileSystemWatcher->addPath(canonicalPath);
        }
    }

    invalidateCollectedSources();

    return allocatedId;
}
コード例 #12
0
ファイル: main.cpp プロジェクト: NextGenIntelligence/qucs
int main(int argc, char *argv[])
{
    QString Lang,LangDir;
    QSettings settings("qucs","qucs");
    if(settings.contains("Language")) {
        Lang=settings.value("Language").toString();
    }

    char * var = getenv ("QUCSDIR");
    if (var != NULL) {
      QDir QucsDir = QDir (var);
      QString QucsDirStr = QucsDir.canonicalPath ();
      LangDir =
        QDir::convertSeparators (QucsDirStr + "/share/qucs/lang/");
    } else {
      LangDir = LANGUAGEDIR;
    }

    QApplication a(argc, argv);

    QTranslator tor( 0 );
    if(Lang.isEmpty())
      Lang = QString(QLocale::system().name());
    tor.load( QString("qucs_") + Lang, LangDir);
    a.installTranslator( &tor );

    QucsActiveFilter w;
    w.show();
    
    return a.exec();
}
コード例 #13
0
QList<ProjectExplorer::ToolChain *> CrossLinuxToolChain32BitFactory::autoDetectToolChains(
        const QString &displayName, const QString &commandPath,
        const QStringList &debuggers, const ProjectExplorer::Abi &requiredAbi)
{
    //TODO add debuger options

    Q_UNUSED(debuggers);
    QList<ProjectExplorer::ToolChain *> result;
    CrossToolChain32Bit *tc = static_cast<CrossToolChain32Bit *>(createToolChain(true));
    QDir sdkDir =CrossSDKInfo::instance().sdkRoot();
    Utils::FileName tcCommand;
    QString sdkPath;

    sdkPath = sdkDir.canonicalPath();
    tcCommand.append(sdkPath + commandPath);

    if (!tcCommand.toFileInfo().exists()) {
        return result;
    }

    tc->setDisplayName(displayName);
    tc->setCompilerCommand(tcCommand);
    tc->setTargetAbi(requiredAbi);
    result.append(tc);
    return result;
}
コード例 #14
0
bool
LibraryParser::serialize(QDir home)
{
    // we write to root of all cyclists
    home.cdUp();

    // open file - truncate contents
    QString filename = home.canonicalPath() + "/library.xml";
    QFile file(filename);
    file.open(QFile::WriteOnly);
    file.resize(0);
    QTextStream out(&file);
    out.setCodec("UTF-8");


    // write out to file
    foreach (Library *l, ::libraries) {
        // begin document
        out << QString("<library name=\"%1\">\n").arg(l->name);

        // paths...
        foreach(QString p, l->paths)
            out << QString("\t<path>%1</path>\n").arg(p);

        // paths...
        foreach(QString r, l->refs)
            out << QString("\t<ref>%1</ref>\n").arg(r);

        // end document
        out << "</library>\n";
    }
コード例 #15
0
void QtZLFSManager::normalizeRealPath(std::string &path) const
{
    QString oldPath = QString::fromStdString(path);

    if (isDataPath(path)) {
        const size_t offset = path.find_first_not_of('/', DATA_PATH_SIZE - 1);
        const QString fileName = oldPath.mid(offset);

        oldPath = QStandardPaths::locate(QStandardPaths::DataLocation, fileName, QStandardPaths::LocateDirectory);
        if (oldPath.isEmpty())
            oldPath = QStandardPaths::locate(QStandardPaths::DataLocation, fileName, QStandardPaths::LocateFile);

        if (oldPath.isEmpty()) {
            qWarning("data path not found: \"%s\"", qPrintable(fileName));
            oldPath = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + fileName;
        }

    } else if (oldPath.startsWith(QStringLiteral("~/")) || oldPath == QStringLiteral("~")) {
        oldPath.replace(0, 1, QDir::homePath());
    }
    
    const QFileInfo info = oldPath;
    const QDir dir = info.absolutePath();
    const QString newPath = dir.canonicalPath() + QLatin1Char('/') + info.fileName();
    path = newPath.toStdString();
}
コード例 #16
0
void BtInstallPathDialog::slotAddClicked() {
    QString dirname = QFileDialog::getExistingDirectory(this, tr("Choose Folder"), "", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    if (dirname.isEmpty()) { // if user cancelled the dialog
        return;
    }
    QDir dir = QDir(dirname);
    if (dir.isReadable()) {
        const QFileInfo fi( dir.canonicalPath() );
        if (!fi.exists() || !fi.isWritable()) {
            const int result = message::showWarning(this, tr("Use Folder?"), tr("This folder is not writable, so works can not be installed here using BibleTime. Do you still want to add it to the list of bookshelf folders?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
            if (result != QMessageBox::Yes) {
                return;
            }
        }
        addPathToList(util::directory::convertDirSeparators(dir.canonicalPath()));
        updateTopLevelItems();
    }
}
コード例 #17
0
    void doChDir(const QDir& dir)
    {
        QString path = dir.canonicalPath();
        if (fsModel)
            currentModelIndex = fsModel->setRootPath(path);
        if (view)
            view->setRootIndex(fsModel->index(path));

    }
コード例 #18
0
ファイル: cleaner.cpp プロジェクト: parapente/epcleanup
QString Cleaner::findFile(QDir dir, QString filename)
{
    QStringList dirs;

    if (QFile::exists(dir.canonicalPath() + "/" + filename))
        return QString(dir.canonicalPath() + "/" + filename);
    else { // file not in this dir, search recursively
        dirs = dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
        for (int i=0; i<dirs.size(); i++) {
            QString tmp;
            tmp = findFile(QDir(dir.canonicalPath() + "/" + dirs[i]), filename);
            if (!(tmp.isNull() || tmp.isEmpty())) {
                return QString(tmp);
            }
        }
        return(QString());
    }
}
コード例 #19
0
ファイル: dirscanner.cpp プロジェクト: VicHao/kkscope
/**
 * Recursively scans a directory for a files matching the current filter.
 * @param	dir	A directory object set to the folder from which files are
 *			added
 * @return	The total number of files added
 */
int DirScanner::scanDir(QDir& dir)
{
	QString sCanon;
	QStringList slDirFiles, slDirs;
	QStringList::const_iterator itr;
	QString sFile;
	int nFiles = 0;

	if (m_bCancel)
		return -1;
		
	// Make sure this directory has not been previously visited (e.g., through a
	// symbolic link)
	sCanon = dir.canonicalPath();
	if (m_setScanned.exists(sCanon))
		return 0;
	
	m_setScanned.insert(sCanon);
	
	// Add all files in this directory
	slDirFiles = dir.entryList(m_sNameFilter, QDir::Files);
	for (itr = slDirFiles.begin(); itr != slDirFiles.end(); ++itr) {
		sFile = dir.absPath() + "/" + *itr;

		// Make sure an entry for this file does not exist
		if (m_pDicFiles->find(sFile) == NULL) {
			m_slFiles.append(sFile);
			nFiles++;
		}
	}

	QApplication::postEvent(m_pEventReceiver,
		new DirScanEvent(nFiles, false));
	
	// Recurse into sub-directories, if requested
	if (!m_bRecursive)
		return nFiles;

	slDirs = dir.entryList(QDir::Dirs);

	// Iterate the list of sub-directories
	for (itr = slDirs.begin(); itr != slDirs.end(); ++itr) {
		if (m_bCancel)
			return -1;
			
		// Skip the "." and ".." directories
		if (*itr == "." || *itr == "..")
			continue;

		// Add the files in each sub-directory
		QDir dirSub(dir);
		if (dirSub.cd(*itr))
			nFiles += scanDir(dirSub);
	}

	return nFiles;
}
コード例 #20
0
ファイル: plexyconfig.cpp プロジェクト: vzades/plexydesk
QString Config::plexydeskBasePath()
{
#ifndef Q_WS_X11
    QDir binaryPath (QCoreApplication::applicationDirPath());
    if (binaryPath.cdUp()) {
        qDebug() << Q_FUNC_INFO << QDir::toNativeSeparators(binaryPath.canonicalPath());
        return QDir::toNativeSeparators(binaryPath.canonicalPath());
    }
#endif

#ifdef Q_WS_X11
    QString basePath(qgetenv("PLEXYDESK_DIR"));
    if (basePath.isEmpty() || basePath.isNull()) {
        return PLEXYPREFIX;
    }

    return basePath;
#endif
}
コード例 #21
0
ファイル: HrZones.cpp プロジェクト: CaptainOnly/GoldenCheetah
/*
 * Copyright (c) 2010 Damien Grauser ([email protected])
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <QMessageBox>
#include "HrZones.h"
#include "Colors.h"
#include "TimeUtils.h"
#include <QtGui>
#include <QtAlgorithms>
#include <qcolor.h>
#include <assert.h>
#include <cmath>


// the infinity endpoints are indicated with extreme date ranges
// but not zero dates so we can edit and compare them
static const QDate date_zero(1900, 01, 01);
static const QDate date_infinity(9999,12,31);

// initialize default static zone parameters
void HrZones::initializeZoneParameters()
{
    static int initial_zone_default[] = {
        0, 68, 83, 94, 105
    };
    static double initial_zone_default_trimp[] = {
        0.9, 1.1, 1.2, 2.0, 5.0
    };
    static const QString initial_zone_default_desc[] = {
        tr("Active Recovery"), tr("Endurance"), tr("Tempo"), tr("Threshold"),
        tr("VO2Max")
    };
    static const char *initial_zone_default_name[] = {
        "Z1", "Z2", "Z3", "Z4", "Z5"
    };

    static int initial_nzones_default =
    sizeof(initial_zone_default) /
    sizeof(initial_zone_default[0]);

    if (run) {
        fileName_ = "run-hr.zones";
    } else {
        fileName_ = "hr.zones";
    }

    scheme.zone_default.clear();
    scheme.zone_default_is_pct.clear();
    scheme.zone_default_desc.clear();
    scheme.zone_default_name.clear();
    scheme.zone_default_trimp.clear();
    scheme.nzones_default = 0;

    scheme.nzones_default = initial_nzones_default;

    for (int z = 0; z < scheme.nzones_default; z ++) {
        scheme.zone_default.append(initial_zone_default[z]);
        scheme.zone_default_is_pct.append(true);
        scheme.zone_default_name.append(QString(initial_zone_default_name[z]));
        scheme.zone_default_desc.append(QString(initial_zone_default_desc[z]));
        scheme.zone_default_trimp.append(initial_zone_default_trimp[z]);
    }
}

// read zone file, allowing for zones with or without end dates
bool HrZones::read(QFile &file)
{

    //
    // GET SET
    //
    defaults_from_user = false;
    scheme.zone_default.clear();
    scheme.zone_default_is_pct.clear();
    scheme.zone_default_name.clear();
    scheme.zone_default_desc.clear();
    scheme.zone_default_trimp.clear();
    scheme.nzones_default = 0;
    ranges.clear();

    // set up possible warning dialog
    warning = QString();
    int warning_lines = 0;
    const int max_warning_lines = 100;

    // macro to append lines to the warning
    #define append_to_warning(s) \
        if (warning_lines < max_warning_lines) \
        warning.append(s);  \
        else if (warning_lines == max_warning_lines) \
        warning.append("...\n"); \
        warning_lines ++;

    // read using text mode takes care of end-lines
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        err = tr("can't open %1 file").arg(fileName_);
        return false;
    }
    QTextStream fileStream(&file);

    QRegExp commentrx("\\s*#.*$");
    QRegExp blankrx("^[ \t]*$");
    QRegExp rangerx[] = {
        QRegExp("^\\s*(?:from\\s+)?"                                 // optional "from"
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|BEGIN)" // begin date
                "\\s*([,:]?\\s*(LT)\\s*=\\s*(\\d+))?"                // optional {LT = integer (optional %)}
                "\\s*([,:]?\\s*(RestHr)\\s*=\\s*(\\d+))?"            // optional {RestHr = integer (optional %)}
                "\\s*([,:]?\\s*(MaxHr)\\s*=\\s*(\\d+))?"             // optional {MaxHr = integer (optional %)}
                "\\s*:?\\s*$",                                       // optional :
                Qt::CaseInsensitive),
        QRegExp("^\\s*(?:from\\s+)?"                                 // optional "from"
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|BEGIN)" // begin date
                "\\s+(?:until|to|-)\\s+"                             // until
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|END)?"  // end date
                "\\s*:?,?\\s*((LT)\\s*=\\s*(\\d+))?"                 // optional {LT = integer (optional %)}
                "\\s*:?,?\\s*((RestHr)\\s*=\\s*(\\d+))?"             // optional {RestHr = integer (optional %)}
                "\\s*:?,?\\s*((MaxHr)\\s*=\\s*(\\d+))?"              // optional {MaxHr = integer (optional %)}
                "\\s*:?\\s*$",                                       // optional :
                Qt::CaseInsensitive)
    };
    QRegExp zonerx("^\\s*([^ ,][^,]*),\\s*([^ ,][^,]*),\\s*"
           "(\\d+)\\s*(%?)\\s*(?:,\\s*(\\d+(\\.\\d+)?)\\s*)?$",
           Qt::CaseInsensitive);//
    QRegExp zonedefaultsx("^\\s*(?:zone)?\\s*defaults?\\s*:?\\s*$",
              Qt::CaseInsensitive);

    int lineno = 0;

    // the current range in the file
    // ZoneRange *range = NULL;
    bool in_range = false;
    QDate begin = date_zero, end = date_infinity;
    int lt = 0;
    int restHr = 0;
    int maxHr = 0;
    QList<HrZoneInfo> zoneInfos;

    // true if zone defaults are found in the file (then we need to write them)
    bool zones_are_defaults = false;

    //
    // READ IN hr.zones FILE
    //

    // loop through line by line
    while (!fileStream.atEnd()) {

        // starting from line 1
        ++lineno;

        // get a line in
        QString line = fileStream.readLine();
        int pos = commentrx.indexIn(line, 0);

        // strip comments
        if (pos != -1) line = line.left(pos);

        // its a blank line (we check after comments stripped)
        if (blankrx.indexIn(line, 0) == 0) goto next_line; // who wrote this? bleck.

        // check for default zone range definition (may be followed by hr zone definitions)
        if (zonedefaultsx.indexIn(line, 0) != -1) {
            zones_are_defaults = true;

            // defaults are allowed only at the beginning of the file
            if (ranges.size()) {
                err = tr("HR Zone defaults must be specified at head of %1 file").arg(fileName_);
                return false;
            }

            // only one set of defaults is allowed
            if (scheme.nzones_default) {
                err = tr("Only one set of zone defaults may be specified in %1 file").arg(fileName_);
                return false;
            }

            // ok move on to get defaults setup
            goto next_line;
        }

        // check for range specification (may be followed by zone definitions)
        for (int r=0; r<2; r++) {

            if (rangerx[r].indexIn(line, 0) != -1) {

                if (in_range) {

                    // if zones are empty, then generate them
                    HrZoneRange range(begin, end, lt, restHr, maxHr);
                    range.zones = zoneInfos;

                    if (range.zones.empty()) {
                        if (range.lt > 0) setHrZonesFromLT(range);
                        else {
                            err = tr("line %1: read new range without reading "
                                    "any zones for previous one").arg(lineno);
                            file.close();
                            return false;
                        }
                    } else {
                        qSort(range.zones);
                    }
                    ranges.append(range);
                }

                in_range = true;
                zones_are_defaults = false;
                zoneInfos.clear();

                // process the beginning date
                if (rangerx[r].cap(1) == "BEGIN")
                    begin = date_zero;
                else {
                    begin = QDate(rangerx[r].cap(2).toInt(),
                    rangerx[r].cap(3).toInt(),
                    rangerx[r].cap(4).toInt());
                }

                // process an end date, if any, else it is null
                if (rangerx[r].cap(5) == "END") end = date_infinity;
                else if (rangerx[r].cap(6).toInt() || rangerx[r].cap(7).toInt() || rangerx[r].cap(8).toInt()) {

                    end = QDate(rangerx[r].cap(6).toInt(),
                    rangerx[r].cap(7).toInt(),
                    rangerx[r].cap(8).toInt());

                } else {
                    end = QDate();
                }

                // set up the range, capturing LT if it's specified
                // range = new ZoneRange(begin, end);
                int nLT = (r ? 11 : 7);
                if (rangerx[r].captureCount() >= (nLT)) lt = rangerx[r].cap(nLT).toInt();
                else lt = 0;

                int nRestHr = (r ? 14 : 10);
                if (rangerx[r].captureCount() >= (nRestHr)) restHr = rangerx[r].cap(nRestHr).toInt();
                else restHr = 0;

                int nMaxHr = (r ? 17 : 13);
                if (rangerx[r].captureCount() >= (nRestHr)) maxHr = rangerx[r].cap(nMaxHr).toInt();
                else maxHr = 0;

                // bleck
                goto next_line;
            }
        }

        // check for zone definition
        if (zonerx.indexIn(line, 0) != -1) {

            if (! (in_range || zones_are_defaults)) {
                err = tr("line %1: read zone without preceding date range").arg(lineno);
                file.close();
                return false;
            }

            int lo = zonerx.cap(3).toInt();
            double trimp = zonerx.cap(5).toDouble();

            // allow for zone specified as % of LT
            bool lo_is_pct = false;
            if (zonerx.cap(4) == "%") {
                if (zones_are_defaults) lo_is_pct = true;
                else if (lt > 0) lo = int(lo * lt / 100);
                else {
                    err = tr("attempt to set zone based on % of LT without setting LT in line number %1.\n").
                    arg(lineno);
                    file.close();
                    return false;
                }
            }

            int hi = -1; // signal an undefined number
            double tr =  zonerx.cap(5).toDouble();

            if (zones_are_defaults) {
                scheme.nzones_default ++;
                scheme.zone_default_is_pct.append(lo_is_pct);
                scheme.zone_default.append(lo);
                scheme.zone_default_name.append(zonerx.cap(1));
                scheme.zone_default_desc.append(zonerx.cap(2));
                scheme.zone_default_trimp.append(trimp);
                defaults_from_user = true;

            } else {

                HrZoneInfo zone(zonerx.cap(1), zonerx.cap(2), lo, hi, tr);
                zoneInfos.append(zone);
            }
        }

        next_line: ;
    }

    // did we drop out mid way through ?
    if (in_range) {
        HrZoneRange range(begin, end, lt, restHr, maxHr);
        range.zones = zoneInfos;
        if (range.zones.empty()) {
            if (range.lt > 0)
                setHrZonesFromLT(range);
            else {
                err = tr("file ended without reading any zones for last range");
                file.close();
                return false;
            }
        } else {

            qSort(range.zones);
        }
        ranges.append(range);
    }

    // reading done
    file.close();

    // sort the ranges
    qSort(ranges);

    //
    // POST-PROCESS / FIX-UP ZONES
    //

    // set the default zones if not in file
    if (!scheme.nzones_default)  {

        // do we have a zone which is explicitly set?
        for (int i=0; i<ranges.count(); i++) {
            if (ranges[i].hrZonesSetFromLT == false) {
                // set the defaults using this one!
                scheme.nzones_default = ranges[i].zones.count();
                for (int j=0; j<scheme.nzones_default; j++) {
                    scheme.zone_default.append(((double)ranges[i].zones[j].lo / (double)ranges[i].lt) * 100.00);
                    scheme.zone_default_is_pct.append(true);
                    scheme.zone_default_name.append(ranges[i].zones[j].name);
                    scheme.zone_default_desc.append(ranges[i].zones[j].desc);
                    scheme.zone_default_trimp.append(ranges[i].zones[j].trimp);
                }
            }
        }

        // still not set then reset to defaults as usual
        if (!scheme.nzones_default) initializeZoneParameters();
    }

    // resolve undefined endpoints in ranges and zones
    for (int nr = 0; nr < ranges.size(); nr ++) {

        // clean up gaps or overlaps in zone ranges
        if (ranges[nr].end.isNull()) {

            ranges[nr].end = (nr < ranges.size() - 1) ?  ranges[nr + 1].begin : date_infinity;

         } else if ((nr < ranges.size() - 1) && (ranges[nr + 1].begin != ranges[nr].end)) {

            append_to_warning(tr("Setting end date of range %1 to start date of range %2.\n").arg(nr + 1).arg(nr + 2));
            ranges[nr].end = ranges[nr + 1].begin;

        } else if ((nr == ranges.size() - 1) && (ranges[nr].end < QDate::currentDate())) {


            append_to_warning(tr("Extending final range %1 to infinite to include present date.\n").arg(nr + 1));
            ranges[nr].end = date_infinity;
        }

        if (ranges[nr].lt <= 0) {
            err = tr("LT must be greater than zero in zone range %1 of %2").arg(nr + 1).arg(fileName_);
            return false;
        }

        if (ranges[nr].zones.size()) {

            // check that the first zone starts with zero
            // ranges[nr].zones[0].lo = 0; // there is no reason we should enforce this, so removing it.

            // resolve zone end powers
            for (int nz = 0; nz < ranges[nr].zones.size(); nz ++) {
                if (ranges[nr].zones[nz].hi == -1) 
                    ranges[nr].zones[nz].hi = (nz < ranges[nr].zones.size() - 1) ?  
                                                ranges[nr].zones[nz + 1].lo : INT_MAX;

                else if ((nz < ranges[nr].zones.size() - 1) && (ranges[nr].zones[nz].hi != ranges[nr].zones[nz + 1].lo)) {

                    if (abs(ranges[nr].zones[nz].hi - ranges[nr].zones[nz + 1].lo) > 4) {

                        append_to_warning(tr("Range %1: matching top of zone %2 (%3) to bottom of zone %4 (%5).\n")
                              .arg(nr+1).arg(ranges[nr].zones[nz].name).arg(ranges[nr].zones[nz].hi)
                              .arg(ranges[nr].zones[nz + 1].name) .arg(ranges[nr].zones[nz + 1].lo));
                    }
                    ranges[nr].zones[nz].hi = ranges[nr].zones[nz + 1].lo;

                } else if ((nz == ranges[nr].zones.size() - 1) && (ranges[nr].zones[nz].hi < INT_MAX)) {

                    append_to_warning(tr("Range %1: setting top of zone %2 from %3 to MAX.\n")
                                     .arg(nr + 1).arg(ranges[nr].zones[nz].name).arg(ranges[nr].zones[nz].hi));
                    ranges[nr].zones[nz].hi = INT_MAX;
                }
            }
        }
    }

    // mark zones as modified so pages which depend on zones can be updated
    modificationTime = QDateTime::currentDateTime();

    return true;
}

// note empty dates are treated as automatic matches for begin or
// end of range
int HrZones::whichRange(const QDate &date) const
{
    for (int rnum = 0; rnum < ranges.size(); ++rnum) {
        const HrZoneRange &range = ranges[rnum];
        if (((date >= range.begin) || (range.begin.isNull())) &&
            ((date < range.end) || (range.end.isNull())))
            return rnum;
    }
    return -1;
}

int HrZones::numZones(int rnum) const
{
    if (rnum < 0 || rnum >= ranges.size()) return 0;
    return ranges[rnum].zones.size();
}

int HrZones::whichZone(int rnum, double value) const
{
    if (rnum < 0 || rnum > ranges.size()) return 0;
    const HrZoneRange &range = ranges[rnum];
    for (int j = 0; j < range.zones.size(); ++j) {
        const HrZoneInfo &info = range.zones[j];
    // note: the "end" of range is actually in the next zone
        if ((value >= info.lo) && (value < info.hi))
            return j;
    }

    // if we got here either it is negative, nan, inf or way high
    return -1;
}

void HrZones::zoneInfo(int rnum, int znum,
                     QString &name, QString &description,
                     int &low, int &high, double &trimp) const
{
    assert(rnum < ranges.size());
    const HrZoneRange &range = ranges[rnum];
    assert(znum < range.zones.size());
    const HrZoneInfo &zone = range.zones[znum];
    name = zone.name;
    description = zone.desc;
    low = zone.lo;
    high = zone.hi;
    trimp= zone.trimp;
}

int HrZones::getLT(int rnum) const
{
    if (rnum < 0 || rnum > ranges.size()) return 0;
    return ranges[rnum].lt;
}

void HrZones::setLT(int rnum, int lt)
{
    ranges[rnum].lt = lt;
    modificationTime = QDateTime::currentDateTime();
}

// generate a list of zones from LT
int HrZones::lowsFromLT(QList <int> *lows, int lt) const {

    lows->clear();

    for (int z = 0; z < scheme.nzones_default; z++)
    lows->append(scheme.zone_default_is_pct[z] ?
                scheme.zone_default[z] * lt / 100 : scheme.zone_default[z]);

    return scheme.nzones_default;
}

int HrZones::getRestHr(int rnum) const
{
    if (rnum < 0 || rnum > ranges.size()) return 0;
    return ranges[rnum].restHr;
}

void HrZones::setRestHr(int rnum, int restHr)
{
    ranges[rnum].restHr = restHr;
    modificationTime = QDateTime::currentDateTime();
}

int HrZones::getMaxHr(int rnum) const
{
    if (rnum < 0 || rnum > ranges.size()) return 0;
    return ranges[rnum].maxHr;
}

void HrZones::setMaxHr(int rnum, int maxHr)
{
    ranges[rnum].maxHr = maxHr;
    modificationTime = QDateTime::currentDateTime();
}

// access the zone name
QString HrZones::getDefaultZoneName(int z) const {
    return scheme.zone_default_name[z];
}

// access the zone description
QString HrZones::getDefaultZoneDesc(int z) const {
    return scheme.zone_default_desc[z];
}

// set the zones from the LT value (the cp variable)
void HrZones::setHrZonesFromLT(HrZoneRange &range) {
    range.zones.clear();

    if (scheme.nzones_default == 0)
    initializeZoneParameters();

    for (int i = 0; i < scheme.nzones_default; i++) {
    int lo = scheme.zone_default_is_pct[i] ? scheme.zone_default[i] * range.lt / 100 : scheme.zone_default[i];
    int hi = lo;
    double trimp = scheme.zone_default_trimp[i];

    HrZoneInfo zone(scheme.zone_default_name[i], scheme.zone_default_desc[i], lo, hi, trimp);
    range.zones.append(zone);
    }

    // sort the zones (some may be pct, others absolute, so zones need to be sorted,
    // rather than the defaults
    qSort(range.zones);

    // set zone end dates
    for (int i = 0; i < range.zones.size(); i ++)
    range.zones[i].hi =
        (i < scheme.nzones_default - 1) ?
        range.zones[i + 1].lo :
        INT_MAX;

    // mark that the zones were set from LT, so if zones are subsequently
    // written, only LT is saved
    range.hrZonesSetFromLT = true;
}

void HrZones::setHrZonesFromLT(int rnum) {
    assert((rnum >= 0) && (rnum < ranges.size()));
    setHrZonesFromLT(ranges[rnum]);
}

// return the list of starting values of zones for a given range
QList <int> HrZones::getZoneLows(int rnum) const {
    if (rnum >= ranges.size())
        return QList <int>();
    const HrZoneRange &range = ranges[rnum];
    QList <int> return_values;
    for (int i = 0; i < range.zones.size(); i ++)
        return_values.append(ranges[rnum].zones[i].lo);
    return return_values;
}

// return the list of ending values of zones for a given range
QList <int> HrZones::getZoneHighs(int rnum) const {
    if (rnum >= ranges.size())
        return QList <int>();
    const HrZoneRange &range = ranges[rnum];
    QList <int> return_values;
    for (int i = 0; i < range.zones.size(); i ++)
        return_values.append(ranges[rnum].zones[i].hi);
    return return_values;
}

// return the list of zone names
QList <QString> HrZones::getZoneNames(int rnum) const {
    if (rnum >= ranges.size())
        return QList <QString>();
    const HrZoneRange &range = ranges[rnum];
    QList <QString> return_values;
    for (int i = 0; i < range.zones.size(); i ++)
        return_values.append(ranges[rnum].zones[i].name);
    return return_values;
}

// return the list of zone trimp coef
QList <double> HrZones::getZoneTrimps(int rnum) const {
    if (rnum >= ranges.size())
        return QList <double>();
    const HrZoneRange &range = ranges[rnum];
    QList <double> return_values;
    for (int i = 0; i < range.zones.size(); i ++)
        return_values.append(ranges[rnum].zones[i].trimp);
    return return_values;
}

QString HrZones::summarize(int rnum, QVector<double> &time_in_zone, QColor color) const
{
    assert(rnum < ranges.size());
    const HrZoneRange &range = ranges[rnum];
    if (time_in_zone.size() < range.zones.size()) return "";
    QString summary;
    if(range.lt > 0){
        summary += "<table align=\"center\" width=\"70%\" border=\"0\">";
        summary += "<tr><td align=\"center\">";
        summary += tr("Threshold (bpm): %1").arg(range.lt);
        summary += "</td></tr></table>";
    }
    summary += "<table align=\"center\" width=\"70%\" ";
    summary += "border=\"0\">";
    summary += "<tr>";
    summary += tr("<td align=\"center\">Zone</td>");
    summary += tr("<td align=\"center\">Description</td>");
    summary += tr("<td align=\"center\">Low (bpm)</td>");
    summary += tr("<td align=\"center\">High (bpm)</td>");
    summary += tr("<td align=\"center\">Time</td>");
    summary += tr("<td align=\"center\">%</td>");
    summary += "</tr>";

    double duration = 0;
    foreach(double v, time_in_zone) { duration += v; }

    for (int zone = 0; zone < time_in_zone.size(); ++zone) {
        if (time_in_zone[zone] > 0.0) {
            QString name, desc;
            int lo, hi;
            double trimp;
            zoneInfo(rnum, zone, name, desc, lo, hi, trimp);
            if (zone % 2 == 0)
                summary += "<tr bgcolor='" + color.name() + "'>";
            else
                summary += "<tr>";
            summary += QString("<td align=\"center\">%1</td>").arg(name);
            summary += QString("<td align=\"center\">%1</td>").arg(desc);
            summary += QString("<td align=\"center\">%1</td>").arg(lo);
            if (hi == INT_MAX)
                summary += "<td align=\"center\">MAX</td>";
            else
                summary += QString("<td align=\"center\">%1</td>").arg(hi);
            summary += QString("<td align=\"center\">%1</td>")
                .arg(time_to_string((unsigned) round(time_in_zone[zone])));
            summary += QString("<td align=\"center\">%1</td>")
                .arg((double)time_in_zone[zone]/duration * 100, 0, 'f', 0);
            summary += "</tr>";
        }
    }
    summary += "</table>";
    return summary;
}

#define USE_SHORT_POWER_ZONES_FORMAT true   /* whether a less redundent format should be used */
void HrZones::write(QDir home)
{
    QString strzones;

    // always write the defaults (config pane can adjust)
    strzones += QString("DEFAULTS:\n");
    for (int z = 0 ; z < scheme.nzones_default; z ++)
        strzones += QString("%1,%2,%3%4,%5\n").
        arg(scheme.zone_default_name[z]).
        arg(scheme.zone_default_desc[z]).
        arg(scheme.zone_default[z]).
        arg(scheme.zone_default_is_pct[z]?"%":"").
        arg(scheme.zone_default_trimp[z]);
    strzones += QString("\n");

    for (int i = 0; i < ranges.size(); i++) {
        int lt = getLT(i);
        int restHr = getRestHr(i);
        int maxHr = getMaxHr(i);

    // print header for range
    // note this explicitly sets the first and last ranges such that all time is spanned

        // note: BEGIN is not needed anymore
        //       since it becomes Jan 01 1900
        strzones += QString("%1: LT=%2, RestHr=%3, MaxHr=%4").arg(getStartDate(i).toString("yyyy/MM/dd")).arg(lt).arg(restHr).arg(maxHr);
    strzones += QString("\n");

    // step through and print the zones if they've been explicitly set
    if (! ranges[i].hrZonesSetFromLT) {
        for (int j = 0; j < ranges[i].zones.size(); j ++) {
                const HrZoneInfo &zi = ranges[i].zones[j];
        strzones += QString("%1,%2,%3,%4\n").arg(zi.name).arg(zi.desc).arg(zi.lo).arg(zi.trimp);
            }
        strzones += QString("\n");
    }
    }

    QFile file(home.canonicalPath() + "/" + fileName_);
    if (file.open(QFile::WriteOnly))
    {
        QTextStream stream(&file);
        stream << strzones;
        file.close();
    } else {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setText(tr("Problem Saving Heartrate Zones"));
        msgBox.setInformativeText(tr("File: %1 cannot be opened for 'Writing'. Please check file properties.").arg(home.canonicalPath() + "/" + fileName_));
        msgBox.exec();
        return;
    }
}
コード例 #22
0
ファイル: pathutils.cpp プロジェクト: mcu786/OpenPilot-1
    /**
      Returns the base path of the share directory.

      Path is in Qt/Unix conventions, separated by "/".
      */
QString PathUtils::GetDataPath()
{
    // This routine works with "/" as the standard:
    // Figure out root:  Up one from 'bin'
    QDir rootDir = QApplication::applicationDirPath();
    rootDir.cdUp();
    const QString rootDirPath = rootDir.canonicalPath();
    QString dataPath = rootDirPath;
    dataPath += QLatin1Char('/');
    dataPath += QLatin1String(GCS_DATA_BASENAME);
    dataPath += QLatin1Char('/');
   return dataPath;
}
コード例 #23
0
BodyMeasures::BodyMeasures(QDir dir, bool withData) : dir(dir), withData(withData) {
    // don't load data if not requested
    if (!withData) return;

    // get body measurements if the file exists
    QFile bodyFile(QString("%1/bodymeasures.json").arg(dir.canonicalPath()));
    if (bodyFile.exists()) {
        QList<BodyMeasure> bodyData;
        if (BodyMeasureParser::unserialize(bodyFile, bodyData)){
            setBodyMeasures(bodyData);
        }
    }
}
コード例 #24
0
ファイル: sandbox.cpp プロジェクト: flashpig/mixxx
// static
SecurityTokenPointer Sandbox::openSecurityToken(const QDir& dir, bool create) {
    QDir walkDir = dir;
    QString walkDirCanonicalPath = walkDir.canonicalPath();
    if (sDebug) {
        qDebug() << "openSecurityToken QDir" << walkDirCanonicalPath << create;
    }

    if (!enabled()) {
        return SecurityTokenPointer();
    }

    QMutexLocker locker(&s_mutex);
    if (s_pSandboxPermissions == NULL) {
        return SecurityTokenPointer();
    }

    while (true) {
        // Look for a valid token in the cache.
        QHash<QString, SecurityTokenWeakPointer>::iterator it = s_activeTokens
                .find(walkDirCanonicalPath);
        if (it != s_activeTokens.end()) {
            SecurityTokenPointer pToken(it.value());
            if (pToken) {
                if (sDebug) {
                    qDebug() << "openSecurityToken QDir" << walkDirCanonicalPath
                             << "using cached token for" << pToken->m_path;
                }
                return pToken;
            }
        }

        // Next, check if the key exists in the config.
        ConfigKey key = keyForCanonicalPath(walkDirCanonicalPath);
        if (s_pSandboxPermissions->exists(key)) {
            SecurityTokenPointer pToken = openTokenFromBookmark(
                    dir.canonicalPath(),
                    s_pSandboxPermissions->getValueString(key));
            if (pToken) {
                return pToken;
            }
        }

        // Go one step higher and repeat.
        if (!walkDir.cdUp()) {
            // There's nothing higher. Bail.
            break;
        }
        walkDirCanonicalPath = walkDir.canonicalPath();
    }

    // Last chance: Try to create a token for this directory.
    if (create && createSecurityToken(dir.canonicalPath(), true)) {
        ConfigKey key = keyForCanonicalPath(dir.canonicalPath());
        return openTokenFromBookmark(
                dir.canonicalPath(),
                s_pSandboxPermissions->getValueString(key));
    }
    return SecurityTokenPointer();
}
コード例 #25
0
void
DatabaseCommand_DirMtimes::execSelectPath( DatabaseImpl *dbi, const QDir& path, QMap<QString, unsigned int> &mtimes )
{
    TomahawkSqlQuery query = dbi->newquery();
    query.prepare( QString( "SELECT name, mtime "
                            "FROM dirs_scanned "
                            "WHERE name LIKE :prefix" ) );

    query.bindValue( ":prefix", path.canonicalPath() + "%" );
    query.exec();

    while( query.next() )
        mtimes.insert( query.value( 0 ).toString(), query.value( 1 ).toUInt() );
}
コード例 #26
0
ファイル: main.cpp プロジェクト: xingdl2007/WizQTClient
static inline QStringList getPluginSpecPaths()
{
#ifdef Q_OS_MAC
    QStringList rc;
    // Figure out root:  Up one from 'bin'
    QDir rootDir = QApplication::applicationDirPath();
    rootDir.cdUp();
    const QString rootDirPath = rootDir.canonicalPath();
    QString pluginSpecPath = rootDirPath;
    pluginSpecPath += QLatin1String("/Resources/plugIns");
    rc.push_back(pluginSpecPath);
    return rc;
#endif
    return getPluginPaths();
}
コード例 #27
0
    ~Impl()
    {
	QDir pdir = qboard::persistenceDir( persistanceClass );
	QString fn = pdir.canonicalPath() + "/" + fileName;
	try
	{
	    paw->s11nSave(fn,false);
	}
	catch(...){}
	/** Reminder: we could rely on the fact that the member QWidgets
	    will be assigned to parent widgets, and we don't need delete
	    them from here. Call me old fashioned. */
	delete paw;
	delete gv;
	delete sidebar;
    }
コード例 #28
0
ファイル: utility.cpp プロジェクト: 13221325403/openbr
QStringList br::getFiles(QDir dir, bool recursive)
{
    dir = QDir(dir.canonicalPath());

    QStringList files;
    foreach (const QString &file, QtUtils::naturalSort(dir.entryList(QDir::Files)))
        files.append(dir.absoluteFilePath(file));

    if (!recursive) return files;

    foreach (const QString &folder, QtUtils::naturalSort(dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))) {
        QDir subdir(dir);
        bool success = subdir.cd(folder); if (!success) qFatal("cd failure.");
        files.append(getFiles(subdir, true));
    }
    return files;
}
コード例 #29
0
ファイル: TomahawkUtils.cpp プロジェクト: zmak/tomahawk
QDir
appConfigDir()
{
    QDir ret;

#ifdef Q_WS_MAC
    if ( getenv( "HOME" ) )
    {
        return QDir( QString( "%1" ).arg( getenv( "HOME" ) ) );
    }
    else
    {
        tDebug() << "Error, $HOME not set.";
        throw "$HOME not set";
        return QDir( "/tmp" );
    }

#elif defined(Q_OS_WIN)
    throw "TODO";
    return QDir( "c:\\" ); //TODO refer to Qt documentation to get code to do this

#else
    if ( getenv( "XDG_CONFIG_HOME" ) )
    {
        ret = QDir( QString( "%1/Tomahawk" ).arg( getenv( "XDG_CONFIG_HOME" ) ) );
    }
    else if ( getenv( "HOME" ) )
    {
        ret = QDir( QString( "%1/.config/Tomahawk" ).arg( getenv( "HOME" ) ) );
    }
    else
    {
        tDebug() << "Error, $HOME or $XDG_CONFIG_HOME not set.";
        throw "Error, $HOME or $XDG_CONFIG_HOME not set.";
        ret = QDir( "/tmp" );
    }

    if ( !ret.exists() )
    {
        ret.mkpath( ret.canonicalPath() );
    }

    return ret;
#endif
}
コード例 #30
0
ファイル: main.cpp プロジェクト: AMDmi3/qucs
int main( int argc, char ** argv )
{
  // apply default settings
  QucsSettings.x = 200;
  QucsSettings.y = 100;
  QucsSettings.font = QFont("Helvetica", 12);

  // is application relocated?
  char * var = getenv ("QUCSDIR");
  if (var != NULL) {
    QDir QucsDir = QDir (var);
    QString QucsDirStr = QucsDir.canonicalPath ();
    QucsSettings.LangDir =
      QDir::convertSeparators (QucsDirStr + "/share/qucs/lang/");
  } else {
    QucsSettings.LangDir = LANGUAGEDIR;
  }

  loadSettings();

  QApplication a( argc, argv );
  a.setFont(QucsSettings.font);
  QTranslator tor( 0 );
  QString lang = QucsSettings.Language;
  if(lang.isEmpty())
    lang = QString(QLocale::system().name());
  tor.load( QString("qucs_") + lang, QucsSettings.LangDir);
  a.installTranslator( &tor );

  QucsAttenuator *qucs = new QucsAttenuator();
  //a.setMainWidget(qucs);
  qucs->raise();
  qucs->move(QucsSettings.x, QucsSettings.y);  // position before "show" !!!
  qucs->show();
  int result = a.exec();
  saveApplSettings(qucs);
  return result;

  //  QApplication a( argc, argv );
  //  QucsAttenuator w;
  //  w.show();
  //  a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );
  //  return a.exec();
}