Example #1
0
// File must not be open and will be closed afterwards!
QByteArray Sha1File(QFile& file) {
  file.open(QIODevice::ReadOnly);
  QCryptographicHash hash(QCryptographicHash::Sha1);
  QByteArray data;

  while (!file.atEnd()) {
    data = file.read(1000000);  // 1 mib
    hash.addData(data.data(), data.length());
    data.clear();
  }

  file.close();

  return hash.result();
}
Example #2
0
Nuria::ArgumentManager::ArgumentManager (QObject *parent)
	: QObject (parent)
{
	
	// 
	g_data = new Nuria::ArgumentManagerPrivate;
	
	// 
	QStringList args = qApp->arguments ();
	QString configPath = qApp->applicationDirPath () + "/settings.cfg";
	
	// Has the user passed a different path to the settings file?
	for (int i = 1; i < args.length (); i++) {
		const QString &cur = args.at (i);
		
		if (cur.startsWith (QLatin1String ("nuria.settings="), Qt::CaseInsensitive)) {
			configPath = cur.mid (cur.indexOf ('=') + 1);
			break;
		}
		
	}
	
	// Load additional settings from settings.cfg
	QFile config (configPath);
	if (config.open (QIODevice::ReadOnly | QIODevice::Text)) {
		
		while (!config.atEnd ()) {
			QString line = config.readLine ();
			
			if (line.indexOf ('#') != -1)
				line = line.left (line.indexOf ('#'));
			else if (line.endsWith (QLatin1Char ('\n')))
				line.chop (1);
			else if (line.endsWith (QLatin1String ("\r\n")))
				line.chop (2);
			
			if (!line.isEmpty ())
				matchArgument (line);
			
		}
		
	}
	
	// Parse command line arguments
	for (int i = 1; i < args.length (); i++)
		matchArgument (args.at (i));
	
}
Example #3
0
static bool processProjectFile(QFile& projectFile, QMap<QString, QString>& args)
{
    QByteArray line = projectFile.readLine().trimmed();
    if (line.isEmpty() || line != "[generator-project]")
        return false;

    QStringList includePaths;
    QStringList typesystemPaths;
    QStringList apiVersions;

    while (!projectFile.atEnd()) {
        line = projectFile.readLine().trimmed();
        if (line.isEmpty())
            continue;

        int split = line.indexOf("=");
        QString key;
        QString value;
        if (split > 0) {
            key = line.left(split - 1).trimmed();
            value = line.mid(split + 1).trimmed();
        } else {
            key = line;
        }

        if (key == "include-path")
            includePaths << QDir::toNativeSeparators(value);
        else if (key == "typesystem-path")
            typesystemPaths << QDir::toNativeSeparators(value);
        else if (key == "api-version")
            apiVersions << value;
        else if (key == "header-file")
            args["arg-1"] = value;
        else if (key == "typesystem-file")
            args["arg-2"] = value;
        else
            args[key] = value;
    }

    if (!includePaths.isEmpty())
        args["include-paths"] = includePaths.join(PATH_SPLITTER);

    if (!typesystemPaths.isEmpty())
        args["typesystem-paths"] = typesystemPaths.join(PATH_SPLITTER);
    if (!apiVersions.isEmpty())
        args["api-version"] = apiVersions.join("|");
    return true;
}
Example #4
0
//-------------------------------------------------------------------------------------------
void AsciiDataReader::detectLineEndingType(QFile& file)
{
  QByteArray line;
  int line_size = 0;
  while (line_size < 2 && !file.atEnd()) {
    line = file.readLine();
    line_size = line.size();
  }
  file.seek(0);
  if (line_size < 2) {
    _lineending = LineEndingType();
  } else {
    _lineending.is_crlf = line[line_size - 2] == '\r' && line[line_size - 1] == '\n' ;
    _lineending.character =  _lineending.is_crlf ? line[line_size - 2] : line[line_size - 1];
  }
}
Example #5
0
bool FrameFileIO::loadGenericCSVFile(QString filename, QVector<CANFrame>* frames)
{
    QFile *inFile = new QFile(filename);
    CANFrame thisFrame;
    QByteArray line;
    long long timeStamp = Utility::GetTimeMS();
    int lineCounter = 0;

    if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        delete inFile;
        return false;
    }

    line = inFile->readLine(); //read out the header first and discard it.

    while (!inFile->atEnd()) {
        lineCounter++;
        if (lineCounter > 100)
        {
            qApp->processEvents();
            lineCounter = 0;
        }

        line = inFile->readLine();
        if (line.length() > 2)
        {
            QList<QByteArray> tokens = line.split(',');

            timeStamp += 5;
            thisFrame.timestamp = timeStamp;
            thisFrame.ID = tokens[0].toInt(NULL, 16);
            if (thisFrame.ID > 0x7FF) thisFrame.extended = true;
            else thisFrame.extended  = false;
            thisFrame.bus = 0;
            QList<QByteArray> dataTok = tokens[1].split(' ');
            thisFrame.len = dataTok.length();
            if (thisFrame.len > 8) thisFrame.len = 8;
            for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = dataTok[d].toInt(NULL, 16);

            frames->append(thisFrame);
        }
    }
    inFile->close();
    delete inFile;
    return true;
}
Example #6
0
bool UpdateAlgePap::checkupdate() {
    //setting keys of existings files
    settings = new QSettings("AlgePap","UpdateAlgePap");
    directory.setPath(DirPath+"/DATA/newspapers/downloadscript");
    QStringList list = directory.entryList();
    for(int i = 2;i < list.count();i++)
        settings->setValue("downloadscript/Dnd"+list.at(i),
                           getkey(directory.path()+"/"+list.at(i)));
    settings->setValue("information/Dninewspapersdata",getkey(DirPath+"/DATA/newspapers/information/newspapersdata"));
    settings->setValue("information/Dninewspapersdataar",getkey(DirPath+"/DATA/newspapers/information/newspapersdataar"));
    //getting keys in web
    list.clear();
    QString linkupdate = "wget -t3 \"https://docs.google.com/document/d/1s0-6xfegMZWrTcdwJcf7zQPDzVblIdRDWSbTPSAOncY/export?format=txt&id=1s0-6xfegMZWrTcdwJcf7zQPDzVblIdRDWSbTPSAOncY&token=AC4w5Vgc6SGsKhrbXlGT0d2JwODk-XHK4Q:1303608416000&authkey=CMjSiN4G&tfe=yn_215\" --output-document \""+DirPath+"/TMP/AlgePapUpdate\"";
    linkweb.setFileName(DirPath+"/TMP/AlgePapUpdate");
    linkdownload.setFileName(DirPath+"/TMP/linkdownload");
    if(!system(linkupdate.toAscii().constData())) {
        if(!linkweb.open(QIODevice::ReadOnly | QIODevice::Text))
            return false;
        if(!linkdownload.open(QIODevice::WriteOnly | QIODevice::Text))
            return false;
        QString loc = QString::fromUtf8(linkweb.readLine());
        loc = QString::fromUtf8(linkweb.readLine());
        while(!linkweb.atEnd() && loc != "END") {
            QString scope = QString::fromUtf8(linkweb.readLine());
            QString link = QString::fromUtf8(linkweb.readLine());
            QString key = QString::fromUtf8(linkweb.readLine());
            QString hash = QString::fromUtf8(linkweb.readLine());
            QString namear = QString::fromAscii(linkweb.readLine());
            scope.remove("\n");
            if(key != settings->value(scope,"").toString()) {
                linkdownload.write(loc.toAscii().constData());
                linkdownload.write(scope.toAscii().constData());
                linkdownload.write("\n");
                linkdownload.write(link.toAscii().constData());
                linkdownload.write(hash.toAscii().constData());
                linkdownload.write(namear.toAscii().constData());
            }
            loc = QString::fromUtf8(linkweb.readLine());
        }
        linkweb.close();
        linkdownload.close();
        delete settings;
        return true;
    }
    else
        return false;
}
QMap<QString, QString>* MLocationDatabaseFake::countriesMap()
{
    QMap<QString, QString> *map = new QMap<QString, QString>();
    QFile *file;

    file = new QFile(countryListFile);
    if (!file->open(QIODevice::ReadOnly | QIODevice::Text)){
        qCritical("Could not read file %s", qPrintable(countryListFile));
        return map;
    }

    int lineNum = -1;
    while (!file->atEnd()) {
        QString country;
        QString line = file->readLine();
        lineNum++;

        if (line.startsWith("#"))
            continue;

        QStringList item = line.split(QRegExp("\\t"), QString::SkipEmptyParts);

        /* skip bad results/table lines those would break the follower code */
        if(item.size() < 2){
            qWarning("Less than two column found in file %s at line %d",
                    qPrintable(countryListFile),
                    lineNum);
            continue;
        }

        if(2 < item.size())
            qWarning("More than two column found in file %s at line %d",
                    qPrintable(countryListFile),
                    lineNum);

        country = item.at(1);

        /* country code => country name */
        /* key expected but value will not be unique */
        map->insert(item.at(0), country);
    }
    file->close();
    delete file;

    return map;
}
Example #8
0
int loadLabels(const char* fn) {
	int res = 1;
	QString path(fn);
	QString line;
	QString name;
	QStringList arr;
	QFile file;
	xAdr xadr;
	if (path.isEmpty())
		path = QFileDialog::getOpenFileName(NULL, "Load SJASM labels");
	if (path.isEmpty()) {
		res = 0;			// no file specified
	} else {
		conf.labels.clear();
		file.setFileName(path);
		if (file.open(QFile::ReadOnly)) {
			while(!file.atEnd()) {
				line = file.readLine();
				arr = line.split(QRegExp("[: \r\n]"),QString::SkipEmptyParts);
				if (arr.size() > 2) {
					xadr.type = MEM_RAM;
					xadr.bank = arr.at(0).toInt(NULL,16);
					xadr.adr = arr.at(1).toInt(NULL,16) & 0x3fff;
					xadr.abs = (xadr.bank << 14) | xadr.adr;
					name = arr.at(2);
					switch (xadr.bank) {
						case 0xff:
							xadr.type = MEM_ROM;
							xadr.bank = -1;
							break;
						case 0x05:
							xadr.adr |= 0x4000;
							break;
						case 0x02:
							xadr.adr |= 0x8000;
							break;
						default:
							xadr.adr |= 0xc000;
							break;
					}
					if (xadr.bank > 0)
						xadr.bank = xadr.abs >> 8;
					conf.labels[name] = xadr;
				}
			}
		} else {
QString md5hash (const QString &fileName)
{
	QFile file (fileName);

	if (!file.open (QIODevice::ReadOnly)) {
		return QString ();
	}

	QCryptographicHash hash (QCryptographicHash::Md5);

	while (!file.atEnd()) {
		const QByteArray &buf = file.read (bufferSize);
		hash.addData (buf);
	}

	return hash.result().toHex();
}
Example #10
0
/*
tokens:
0 = timestamp
1 = Transmission direction
2 = Channel
3 = ID
4 = Type (s = standard, I believe x = extended)
5 = Data byte length
6-x = The data bytes

Sample chunk of a busmaster log:
***BUSMASTER Ver 2.4.0***
***PROTOCOL CAN***
***NOTE: PLEASE DO NOT EDIT THIS DOCUMENT***
***[START LOGGING SESSION]***
***START DATE AND TIME 8:8:2014 11:49:7:965***
***HEX***
***SYSTEM MODE***
***START CHANNEL BAUD RATE***
***CHANNEL 1 - Kvaser - Kvaser Leaf Light HS #0 (Channel 0), Serial Number- 0, Firmware- 0x00000037 0x00020000 - 500000 bps***
***END CHANNEL BAUD RATE***
***START DATABASE FILES (DBF/DBC)***
***END OF DATABASE FILES (DBF/DBC)***
***<Time><Tx/Rx><Channel><CAN ID><Type><DLC><DataBytes>***
11:49:12:9420 Rx 1 0x023 s 1 40
11:49:12:9440 Rx 1 0x460 s 8 03 E0 00 00 C0 00 00 00
11:49:12:9530 Rx 1 0x023 s 1 40
11:49:12:9680 Rx 1 0x408 s 8 0F 02 00 30 00 00 7F 00
11:49:12:9680 Rx 1 0x40B s 8 00 00 00 00 00 10 60 00
11:49:12:9690 Rx 1 0x045 s 8 40 00 00 00 00 00 00 00
*/
bool FrameFileIO::loadLogFile(QString filename, QVector<CANFrame>* frames)
{
    QFile *inFile = new QFile(filename);
    CANFrame thisFrame;
    QByteArray line;
    uint64_t timeStamp = Utility::GetTimeMS();
    int lineCounter = 0;

    if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        delete inFile;
        return false;
    }

    line = inFile->readLine(); //read out the header first and discard it.

    while (!inFile->atEnd()) {
        lineCounter++;
        if (lineCounter > 100)
        {
            qApp->processEvents();
            lineCounter = 0;
        }

        line = inFile->readLine();
        if (line.startsWith("***")) continue;
        if (line.length() > 1)
        {
            QList<QByteArray> tokens = line.split(' ');
            QList<QByteArray> timeToks = tokens[0].split(':');
            timeStamp = (timeToks[0].toInt() * (1000ul * 1000ul * 60ul * 60ul)) + (timeToks[1].toInt() * (1000ul * 1000ul * 60ul))
                      + (timeToks[2].toInt() * (1000ul * 1000ul)) + (timeToks[3].toInt() * 100ul);
            thisFrame.timestamp = timeStamp;
            thisFrame.ID = tokens[3].right(tokens[3].length() - 2).toInt(NULL, 16);
            if (tokens[4] == "s") thisFrame.extended = false;
            else thisFrame.extended = true;
            thisFrame.bus = tokens[2].toInt() - 1;
            thisFrame.len = tokens[5].toInt();
            for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = tokens[d + 6].toInt(NULL, 16);
        }
        frames->append(thisFrame);
    }
    inFile->close();
    delete inFile;
    return true;
}
Example #11
0
bool BadgeData::getTimetable(TimeTable &tt)
{
#ifdef ONLY_BADGE
    QFile data;
    TimeTable dum;
    data.setFileName(QDir::homePath() + QDir::separator() + "badge.data");
    data.open(QIODevice::ReadOnly);
    QDataStream out(&data);



    while (!data.atEnd()) {
        out >> dum;
        if (dum.day == tt.day) {
            tt = dum;
            data.close();
            return true;
        }
    }
    data.close();
    return false;
#else
    QSqlQuery query;
    QVariant vday(tt.day);

    query.prepare("select *  from days where daywork = ?");
    query.addBindValue(vday);

    query.exec();


    if (query.next()) {

        tt.entrance = query.value(1).toTime();
        tt.exit = query.value(2).toTime();
        tt.firstPause  = query.value(3).toTime();
        tt.endFirstPause  = query.value(4).toTime();
        tt.secondPause  = query.value(5).toTime();
        tt.endSecondPause  = query.value(6).toTime();

        return true;
    }
#endif
    return false;
}
Example #12
0
vector<QStringList> MainWindow::getFromCsv(QString path){
    vector<QStringList> fileDate;

    QFile file;
    file.setFileName(path);
    file.open(QIODevice::ReadOnly);
    cout<<"FilePath - "<<path.toUtf8().constData()<<endl;
    while(!file.atEnd()){
        QString str= file.readLine();
        str.replace(',','.');
        QStringList oneString=str.split(';');
        cout<<str.toUtf8().constData()<<endl;
        fileDate.push_back(oneString);
    }
    file.close();

    return fileDate;
}
Example #13
0
/*
 * Writes back the changes of the temporary file
 * to the original file.
 * Must only be called if in write mode, not in read mode
 */
bool KTar::KTarPrivate::writeBackTempFile( const QString & fileName )
{
    if ( !tmpFile )
        return true;

    //qDebug() << "Write temporary file to compressed file" << fileName << mimetype;

    bool forced = false;
    if (QLatin1String(application_gzip) == mimetype || QLatin1String(application_bzip) == mimetype ||
        QLatin1String(application_lzma) == mimetype || QLatin1String(application_xz) == mimetype)
        forced = true;

    // #### TODO this should use QSaveFile to avoid problems on disk full
    // (KArchive uses QSaveFile by default, but the temp-uncompressed-file trick
    // circumvents that).

    KFilterDev dev(fileName);
    QFile* file = tmpFile;
    if ( !dev.open(QIODevice::WriteOnly) )
    {
        file->close();
        return false;
    }
    if ( forced )
        dev.setOrigFileName( origFileName );
    file->seek(0);
    QByteArray buffer;
    buffer.resize(8*1024);
    qint64 len;
    while ( !file->atEnd()) {
        len = file->read(buffer.data(), buffer.size());
        dev.write(buffer.data(),len); // TODO error checking
    }
    file->close();
    dev.close();

    //qDebug() << "Write temporary file to compressed file done.";
    return true;
}
Example #14
0
void Dialog::getSourceCodeStringsNumber() {

    QString str;
    QFile srcFile;

    for (ptrdiff_t i=0; i<files->count(); i++) {

        srcFile.setFileName(files->at(i));
        srcFile.open(QIODevice::ReadOnly);

        while (!srcFile.atEnd()) {

            str = srcFile.readLine().trimmed();

            if ( (!str.isEmpty()) && (!str.isNull()) ) {

                lines++;
            }
        }

        srcFile.close();
    }
}
void BasicMixedProviderPrivate::update(const QString &path, QMap <QString, QString> *data)
{
    data->clear();

    QFile file (path);
    if (!file.open(QIODevice::ReadOnly)) {
        return;
    }

    while (!file.atEnd()) {
        QString line = file.readLine();
        QStringList lineSplitted = line.split(";");

        if (lineSplitted.count() == 1) {
            data->insert(lineSplitted.at(0).trimmed(), QString());
        }

        if (lineSplitted.count() == 2) {
            data->insert(lineSplitted.at(0).trimmed(), lineSplitted.at(1).trimmed());
        }
    }
    file.close();
}
Example #16
0
void TsunamiEvacModel::on_actionLoad_cost_grid_triggered()
{
    QString fileName;
    fileName = QFileDialog::getOpenFileName(this,
        tr("Open Image"), QDir::homePath(), tr("Image Files (*.csv)"));
    QList<QStringList> myMat;

    QFile file;
    file.setFileName(fileName);
    if(file.open(QIODevice::ReadOnly))
        setStatus("File opened");
    else
        setStatus("Could not open file");

    while (!file.atEnd()){
        QByteArray line = file.readLine();
        QStringList temp;
        for(int i = 0; i < line.split(',').size(); i++)
            temp.append(line.split(',').at(i));
        myMat.append(temp);
    }

    QString temp;
    delete myGrid;
    myGrid = new Grid(myMat.size(),myMat.at(1).size(),this);

    for(int i = 0; i < myMat.size(); i++){
        for(int j = 0; j < myMat.at(i).size(); j++){

            myGrid->setValue(i,j,myMat.at(i).at(j).toInt());
            temp.append(myMat.at(i).at(j));
            temp.append(" ");
        }
        temp.append("\n");
    }
    ui->textBrowser->append(temp);
}
Example #17
0
void ServerFileTransfer::slotStartTransfer(){
    fileTransferInProgress.lock();
    QFile *file = new QFile("./Songs/" + fileName_);
    Packet pckt;

    if(!file->open(QIODevice::ReadOnly)) {
        cleanup();
        return;
    }

    pckt.data = new char[FT_DATA_SIZE];

    while (!file->atEnd()) {
        pckt.length = file->read(pckt.data,FT_DATA_SIZE);
        pckt.type = kTransfer;
        socket_->transmit(pckt);
    }
    if (pckt.data != 0) {
        delete[] pckt.data;
        pckt.data = 0;
    }
    file->close();
    cleanup();
}
Example #18
0
void CLoaderRecipe::getRecipe()
{
    QFile *file;
    QDir dir("recipe");
    if (!dir.exists())
        qWarning("Cannot find the example directory");
    dir.setFilter(QDir::Files);
    QFileInfoList list = dir.entryInfoList();
    for (int loop = 0; loop < list.size(); ++loop)
    {
        QFileInfo fileInfo = list.at(loop);
        file = new QFile(fileInfo.filePath());
        file->open(QIODevice::ReadOnly | QIODevice::Text);
        QString line;
        while (!file->atEnd())
        {
            line = file->readLine();
            QStringList lineList = line.split(";");
            if (lineList.size() == 6)
                recipeList.append(new CRecipe(lineList[0], lineList[1], lineList[2], lineList[3], lineList[4], lineList[5].remove("\n"), fileInfo.filePath()));
        }
        delete file;
    }
}
bool PlaylistImporter::parsePlaylist_pls(QFile &data, QStringList &fileList, const QDir &baseDir, const QDir &rootDir)
{
	QRegExp plsEntry("File(\\d+)=(.+)", Qt::CaseInsensitive);
	const QTextCodec *codec = QTextCodec::codecForName("System");
	bool foundAtLeastOneFile = false;

	data.reset();

	while(!data.atEnd())
	{
		QString filePath[3];
		QByteArray line = data.readLine();

		filePath[0] = QString(QDir::fromNativeSeparators(codec->toUnicode(line.constData(), line.size()).trimmed()));
		filePath[1] = QString(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed()));
		filePath[2] = QString(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed()));
		
		for(size_t i = 0; i < 3; i++)
		{
			if(!filePath[i].contains(QChar(QChar::ReplacementCharacter)))
			{
				if(plsEntry.indexIn(filePath[i]) >= 0)
				{
					QFileInfo filename(QDir::fromNativeSeparators(plsEntry.cap(2)).trimmed());
					filename.setCaching(false);
					fixFilePath(filename, baseDir, rootDir);

					if(filename.exists() && filename.isFile())
					{
						if(isPlaylist(filename.canonicalFilePath()) == notPlaylist)
						{
							fileList << filename.canonicalFilePath();
						}
						foundAtLeastOneFile = true;
						break;
					}
				}
			}
		}
	}

	//If we did not find any files yet, try UTF-16 now
	if(!foundAtLeastOneFile)
	{
		const char* codecs[2] = {"UTF-16LE", "UTF-16BE"};

		for(size_t i = 0; i < 2; i++)
		{
			QTextStream stream(&data);
			stream.setAutoDetectUnicode(false);
			stream.setCodec(codecs[i]);
			stream.seek(0i64);

			while(!stream.atEnd())
			{
				QString filePath = stream.readLine().trimmed();

				if(!filePath.contains(QChar(QChar::ReplacementCharacter)))
				{
					if(plsEntry.indexIn(filePath) >= 0)
					{
						QFileInfo filename(QDir::fromNativeSeparators(plsEntry.cap(2)).trimmed());
						filename.setCaching(false);
						fixFilePath(filename, baseDir, rootDir);

						if(filename.exists() && filename.isFile())
						{
							if(isPlaylist(filename.canonicalFilePath()) == notPlaylist)
							{
								fileList << filename.canonicalFilePath();
							}
							foundAtLeastOneFile = true;
						}
					}
				}
			}

			if(foundAtLeastOneFile) break;
		}
	}

	return foundAtLeastOneFile;
}
Example #20
0
QString QHostInfo::localDomainName()
{
#if !defined(Q_OS_VXWORKS)
    resolveLibrary();
    if (local_res_ninit) {
        // using thread-safe version
        res_state_ptr state = res_state_ptr(qMalloc(sizeof(*state)));
        Q_CHECK_PTR(state);
        memset(state, 0, sizeof(*state));
        local_res_ninit(state);
        QString domainName = QUrl::fromAce(state->defdname);
        if (domainName.isEmpty())
            domainName = QUrl::fromAce(state->dnsrch[0]);
        local_res_nclose(state);
        qFree(state);

        return domainName;
    }

    if (local_res_init && local_res) {
        // using thread-unsafe version

#if defined(QT_NO_GETADDRINFO)
        // We have to call res_init to be sure that _res was initialized
        // So, for systems without getaddrinfo (which is thread-safe), we lock the mutex too
        QMutexLocker locker(::getHostByNameMutex());
#endif
        local_res_init();
        QString domainName = QUrl::fromAce(local_res->defdname);
        if (domainName.isEmpty())
            domainName = QUrl::fromAce(local_res->dnsrch[0]);
        return domainName;
    }
#endif
    // nothing worked, try doing it by ourselves:
    QFile resolvconf;
#if defined(_PATH_RESCONF)
    resolvconf.setFileName(QFile::decodeName(_PATH_RESCONF));
#else
    resolvconf.setFileName(QLatin1String("/etc/resolv.conf"));
#endif
    if (!resolvconf.open(QIODevice::ReadOnly))
        return QString();       // failure

    QString domainName;
    while (!resolvconf.atEnd()) {
        QByteArray line = resolvconf.readLine().trimmed();
        if (line.startsWith("domain "))
            return QUrl::fromAce(line.mid(sizeof "domain " - 1).trimmed());

        // in case there's no "domain" line, fall back to the first "search" entry
        if (domainName.isEmpty() && line.startsWith("search ")) {
            QByteArray searchDomain = line.mid(sizeof "search " - 1).trimmed();
            int pos = searchDomain.indexOf(' ');
            if (pos != -1)
                searchDomain.truncate(pos);
            domainName = QUrl::fromAce(searchDomain);
        }
    }

    // return the fallen-back-to searched domain
    return domainName;
}
Example #21
0
/*!
   Load a spkac FILE into this request structure.
   The file format follows the conventions understood by the 'openssl ca'
   command. (see: 'man ca')
*/
int pki_x509req::load_spkac(const QString filename)
{
	QFile file;
	x509name subject;
	EVP_PKEY *pktmp = NULL;
	pki_ign_openssl_error();

	file.setFileName(filename);
        if (!file.open(QIODevice::ReadOnly))
		return 1;

	while (!file.atEnd()) {
		int idx, nid;
		QByteArray line = file.readLine();
		if (line.size() == 0)
			continue;
		idx = line.indexOf('=');
		if (idx == -1)
			goto err;
		QString type = line.left(idx).trimmed();
		line = line.mid(idx+1).trimmed();

		idx = type.lastIndexOf(QRegExp("[:,\\.]"));
		if (idx != -1)
			type = type.mid(idx+1);

		if ((nid = OBJ_txt2nid(CCHAR(type))) == NID_undef) {
			if (type != "SPKAC")
				goto err;
			pki_ign_openssl_error();
			spki = NETSCAPE_SPKI_b64_decode(line, line.size());
			if (!spki)
				goto err;
			/*
			  Now extract the key from the SPKI structure and
			  check the signature.
			 */
			pktmp = NETSCAPE_SPKI_get_pubkey(spki);
			if (pktmp == NULL)
				goto err;

			if (NETSCAPE_SPKI_verify(spki, pktmp) != 1)
				goto err;
		} else {
			// gather all values in the x509name subject.
			subject.addEntryByNid(nid,
				filename2QString(line.constData()));
		}
	}
	if (!pktmp)
		goto err;
	setSubject(subject);
	X509_REQ_set_pubkey(request, pktmp);
	EVP_PKEY_free(pktmp);
	return 0;
err:
	if (pktmp)
		EVP_PKEY_free(pktmp);
	if (spki) {
		NETSCAPE_SPKI_free(spki);
		spki = NULL;
	}
	return 1;
}
Example #22
0
bool PlaylistImporter::parsePlaylist_m3u(QFile &data, QStringList &fileList, const QDir &baseDir, const QDir &rootDir)
{
	const QTextCodec *codec = QTextCodec::codecForName("System");
	const bool preferUTF8 = data.fileName().endsWith(".m3u8", Qt::CaseInsensitive);
	bool foundAtLeastOneFile = false;
	
	data.reset();

	while(!data.atEnd())
	{
		QString filePath[3];
		QByteArray line = data.readLine();

		if(preferUTF8)
		{
			filePath[0] = QString(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed()));
			filePath[1] = QString(QDir::fromNativeSeparators(codec->toUnicode(line.constData(), line.size()).trimmed()));
			filePath[2] = QString(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed()));
		}
		else
		{
			filePath[0] = QString(QDir::fromNativeSeparators(codec->toUnicode(line.constData(), line.size()).trimmed()));
			filePath[1] = QString(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed()));
			filePath[2] = QString(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed()));
		}

		for(size_t i = 0; i < 3; i++)
		{
			if(!(filePath[i].isEmpty() || filePath[i].startsWith("#") || filePath[i].contains(QChar(QChar::ReplacementCharacter))))
			{
				QFileInfo filename(filePath[i]);
				filename.setCaching(false);
				fixFilePath(filename, baseDir, rootDir);

				if(filename.exists() && filename.isFile())
				{
					qDebug("Found: \"%s\"", filePath[i].toUtf8().constData());
					if(isPlaylist(filename.canonicalFilePath()) == notPlaylist)
					{
						fileList << filename.canonicalFilePath();
					}
					foundAtLeastOneFile = true;
					break;
				}
			}
		}
	}

	//If we did not find any files yet, try UTF-16 now
	if(!foundAtLeastOneFile)
	{
		const char* codecs[2] = {"UTF-16LE", "UTF-16BE"};

		for(size_t i = 0; i < 2; i++)
		{
			QTextStream stream(&data);
			stream.setAutoDetectUnicode(false);
			stream.setCodec(codecs[i]);
			stream.seek(0i64);

			while(!stream.atEnd())
			{
				QString filePath = stream.readLine().trimmed();

				if(!(filePath.isEmpty() || filePath.startsWith("#") || filePath.contains(QChar(QChar::ReplacementCharacter))))
				{
					QFileInfo filename(filePath);
					filename.setCaching(false);
					fixFilePath(filename, baseDir, rootDir);

					if(filename.exists() && filename.isFile())
					{
						if(isPlaylist(filename.canonicalFilePath()) == notPlaylist)
						{
							fileList << filename.canonicalFilePath();
						}
						foundAtLeastOneFile = true;
					}
				}
			}

			if(foundAtLeastOneFile) break;
		}
	}

	return true;
}
Example #23
0
/**
 * Set entries to a variable. Will set the variables to the existing line, removing duplicates
 * Will preserve += constructs and make sure that the variable only has one copy of the value across
 * all += constructs
 * Adds line if it does not exist.
 * @param fileName
 * @param variables key=value string of entries to add
 */
void AutoProjectTool::setMakefileam ( const QString &fileName, QMap<QString, QString> variables )
{
	for ( QMap<QString, QString>::Iterator it0 = variables.begin(); it0 != variables.end(); ++it0 )
	{
		kdDebug ( 9020 ) << "key (set): " << it0.key() << "=" << it0.data() << endl;
	}

	// input file reading
	QFile fin ( fileName );
	if ( !fin.open ( IO_ReadOnly ) )
	{
		return ;
	}
	QTextStream ins ( &fin );

	// output file writing.
	QFile fout ( fileName + "#" );
	if ( !fout.open ( IO_WriteOnly ) )
	{
		fin.close();
		return ;
	}
	QTextStream outs ( &fout );

	// variables
	QRegExp re ( "^(#kdevelop:[ \t]*)?([A-Za-z][@A-Za-z0-9_]*)[ \t]*([:\\+]?=)[ \t]*(.*)$" );

	bool multiLine = false;
	QString lastLhs;
	QMap<QString, QString> seenLhs;
	while ( !fin.atEnd() )
	{
		QString s = ins.readLine();
		if ( re.exactMatch ( s ) )
		{
			QString lhs = re.cap ( 2 );
			bool notFound = ( variables.find ( lhs ) == variables.end() );

			if ( notFound )
			{
				if ( seenLhs.find ( lhs ) == seenLhs.end() )
				{
					// not interested in this line at all
					// write it out as is..
					outs << s << endl;
				}
				// we have seen this variable, but since we are setting the
				// whole line - we skip this as it will be a += line.
			}
			else
			{
				// we are interested in this line..
				QString rhs = re.cap ( 4 ).stripWhiteSpace();
				if ( rhs[ rhs.length() - 1 ] == '\\' )
				{
					// save it for when we have the whole line..
					multiLine = true;
					lastLhs = lhs;
				}
				else
				{
					// deal with it now - a single line
					// we are adding our interested values to this line and writing it
					// now write the line out if it is not going to be empty.
					QString newLine ( lhs );
					newLine += " = ";
					bool added = false;
					int len = newLine.length();
					QStringList variableList = QStringList::split ( ' ', variables[lhs] );
					for ( uint count = 0; count < variableList.size(); count++ )
					{
						len += variableList[count].length() + 1;
						if ( len > 80 )
						{
							newLine += "\\\n\t";
							len = 8;
						}
						newLine += variableList[count];
						newLine += ' ';
						added = true;

					}
					// only print it out if there was a value to add..
					if ( added )
					{
						newLine.setLength ( newLine.length() - 1 );
						outs << newLine << endl;
					}
					seenLhs[lhs] = "done";
					variables.erase ( lhs );
				}
			}
		}
		else if ( multiLine )
		{
			s = s.stripWhiteSpace();
			// we are only here if were interested in this line..
			if ( s[s.length()-1] == '\\' )
			{
				s.setLength ( s.length() - 1 );
				// still more multi line we wait for..
			}
			else
			{
				// end of the multi line..
				multiLine = false;
			}

			if ( !multiLine )
			{
				// we are adding our interested values to this line and writing it
				// now write the line out if it is not going to be empty.
				QString newLine ( lastLhs );
				newLine += " = ";
				bool added = false;
				int len = newLine.length();
				QStringList variableList = QStringList::split ( ' ', variables[lastLhs] );
				for ( uint count = 0; count < variableList.size(); count++ )
				{
					len += variableList[count].length() + 1;
					if ( len > 80 )
					{
						newLine += "\\\n\t";
						len = 8;
					}
					newLine += variableList[count];
					newLine += ' ';
					added = true;
				}
				// only print it out if there was a value to add..
				if ( added )
				{
					newLine.setLength ( newLine.length() - 1 );
					outs << newLine << endl;
				}
				seenLhs[lastLhs] = "done";
				variables.erase ( lastLhs );
				lastLhs.setLength ( 0 );
			}
		}
		else
		{
			// can write this line out..
			// not a match, not a multi line,
			outs << s << endl;
		}
	}

	for ( QMap<QString, QString>::Iterator it0 = variables.begin(); it0 != variables.end(); ++it0 )
	{
		QString newLine ( it0.key() );
		newLine += " = ";
		bool added = false;
		int len = newLine.length();
		QStringList variableList = QStringList::split ( ' ', it0.data() );
		for ( uint count = 0; count < variableList.size(); count++ )
		{
			len += variableList[count].length() + 1;
			if ( len > 80 )
			{
				newLine += "\\\n\t";
				len = 8;
			}
			newLine += variableList[count];
			newLine += ' ';
			added = true;

		}
		// only print it out if there was a value to add..
		if ( added )
		{
			newLine.setLength ( newLine.length() - 1 );
			outs << newLine << endl;
		}
	}

	fin.close();
	fout.close();

	QDir().rename ( fileName + "#", fileName );
}
Example #24
0
//------------------------------------------------------------------------------
MetaInfo BibleQuoteModule::readInfo(QFile &file)
{
    bool useShortName = false;
    m_moduleName.clear();
    m_moduleShortName.clear();
    int countlines = 0;

    QString encoding = getEncodingFromFile(file.fileName());
    m_codec = QTextCodec::codecForName(encoding.toStdString().c_str());

    QTextDecoder *decoder = m_codec->makeDecoder();
    while(!file.atEnd())
    {
        /*if (countlines > 50) { //wenn eine ini datei ungueltig ist soll damit nicht zuviel zeit verguedet werden
            break;
        }*/
        QByteArray byteline = file.readLine();
        QString line = decoder->toUnicode(byteline);
        if(!line.startsWith("//"))
        {
            countlines++;
        }
        else
        {
            continue;
        }

        if(line.contains("BibleName", Qt::CaseInsensitive) and m_moduleName.isEmpty())
        {
            m_moduleName = formatFromIni(line.
                                         remove(QRegExp("BibleName(\\s*)=(\\s*)",
                                                        Qt::CaseInsensitive)));
            if(m_moduleName.isEmpty())
            {
                useShortName = true;
            }
            if(useShortName && !m_moduleShortName.isEmpty())
            {
                break;
            }
            /// what is ?
            //            else if(!useShortName)
            //            {
            //                break;
            //            }
        }
        if(line.contains("BibleShortName", Qt::CaseInsensitive) and m_moduleShortName.isEmpty())
        {
            m_moduleShortName = formatFromIni(line.
                                              remove(QRegExp("BibleShortName(\\s*)=(\\s*)",
                                                             Qt::CaseInsensitive)));
            if(useShortName)
                break;
        }
    }
    file.close();
    if(useShortName)
    {
        m_moduleName = m_moduleShortName;
    }
    if(m_moduleName.isEmpty())
    {
        myWarning() << "invalid ini File " << file.fileName();
    }

    MetaInfo ret;
    ret.setName(m_moduleName);
    ret.setShortName(m_moduleShortName);

    if (m_typeModule == "Apocrypha")
        ret.type = OBVCore::Type_BibleQuoteApocrypha;

    if (m_typeModule == "Comments")
        ret.type = OBVCore::Type_BibleQuoteComments;

    if (m_typeModule == "Bible")
        ret.type = OBVCore::Type_BibleQuoteModule;

    if (m_typeModule == "Book")
        ret.type = OBVCore::Type_BibleQuoteBook;

    return ret;
    return MetaInfo();
}
Example #25
0
void ODBCDialog::updateStatistics()
{
	// Variables...
	int pidTotal = 0;
	bool statsFail = FALSE;
	int handleNum = 0;
	QString tempString;
	QString processUser = "";
	QString processName = "";
	QFile processFile;
	uid_t userID;
	struct passwd* passwdItem;

	// Set file name...
	processFile.setName("status");

	// Get statistics...
	if (!statsHandle)
	{
		if (uodbc_open_stats(&statsHandle, UODBC_STATS_READ) != 0)
		{
			statsFail = TRUE;
			statsHandle = 0;
		}
	}

	if (statsFail == FALSE)
	{
		// Get stats for summary tab...
		if (uodbc_get_stats(statsHandle, -1, statsResult, 4) == 4)
		{
			// Get progress bars max value...
			if (statsResult[0].value.l_value > progressMaxValue)
				progressMaxValue = statsResult[0].value.l_value;
			if (statsResult[1].value.l_value > progressMaxValue)
				progressMaxValue = statsResult[1].value.l_value;
			if (statsResult[2].value.l_value > progressMaxValue)
				progressMaxValue = statsResult[2].value.l_value;
			if (statsResult[3].value.l_value > progressMaxValue)
				progressMaxValue = statsResult[3].value.l_value;

			// Set progress bars and label values...
			envProgress->setProgress(statsResult[0].value.l_value, progressMaxValue);
			envLabel->setText(QString::number(statsResult[0].value.l_value));
			conProgress->setProgress(statsResult[1].value.l_value, progressMaxValue);
			conLabel->setText(QString::number(statsResult[1].value.l_value));
			staProgress->setProgress(statsResult[2].value.l_value, progressMaxValue);
			staLabel->setText(QString::number(statsResult[2].value.l_value));
			desProgress->setProgress(statsResult[3].value.l_value, progressMaxValue);
			desLabel->setText(QString::number(statsResult[3].value.l_value));

			// Get stats for details tab...
			pidTotal = uodbc_get_stats(statsHandle, 0, pidResults, MAXPROCESSES);
			detailsTable->setNumRows(pidTotal);

			// Update stat details table...
			for (int pidNumber = 0; pidNumber < pidTotal; pidNumber++)
        	{
				// Reset variables...
				processUser = "";
				processName = "";


				handleNum = uodbc_get_stats(statsHandle, pidResults[pidNumber].value.l_value, handleResult, MAXHANDLES);
				if (handleNum > 0)
				{
					// Get Process information (program name, username)...
					tempString = "/proc/";
					tempString.append(QString::number(pidResults[pidNumber].value.l_value));
					QDir::setCurrent(tempString);
					if (processFile.open(IO_ReadOnly))
					{
						while ((processFile.atEnd() == FALSE) && ((processName.isEmpty() == TRUE) || (processUser.isEmpty() == TRUE)))
						{
							processFile.readLine(tempString, 500);
							if (tempString.contains("Name:") > 0)
							{
								processName = tempString.right(tempString.length() - 6);
							}
							if (tempString.contains("Uid:") > 0)
							{
								processUser = tempString.mid(5, (tempString.find((char)9, 6) - 5));
								userID = processUser.toInt();
								passwdItem = getpwuid(userID);
								processUser = passwdItem->pw_name;
							}
						}
						processFile.close();
					}

					// Update the table...
					detailsTable->setText(pidNumber, 0, processUser);
					detailsTable->setText(pidNumber, 1, processName);
					detailsTable->setText(pidNumber, 2, QString::number(pidResults[pidNumber].value.l_value));
					for (int handle = 0; handle < MAXHANDLES; handle++)
					{
						detailsTable->setText(pidNumber, handle + 3, QString::number(handleResult[handle].value.l_value));
					}
				}
				else
				{
					clearDetailRow(pidNumber);
				}
			}
		}
		else
		{
			statsFail = TRUE;
		}
	}
}
Example #26
0
int main(int argc, char *argv[])
{
    // Под Windows устанавливаем кодировку cp1251
    #ifdef Q_WS_WIN
    QTextCodec *codec = QTextCodec::codecForName("Windows-1251");
    // Под остальными ОС - utf8
    #else
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    #endif

    QString param;

    QString org_file_name;
    org_file_name = "org_name.conf";
    for (int i = 0; i<argc; i++) {
        param = codec->toUnicode(argv[i]);
        if (check_extention(param, ".conf")) {
                    //ключ c - передается файл с названием организации
                    org_file_name = param;
        }
    }

    bool get_name = false;
    QString org_name = "IP_Volkov";
    QString app_name = "CenGen";
    QFile *file = new QFile(org_file_name);
    if (!file->exists()) get_name = true;
    file->open(QFile::ReadOnly);
    if (!file->isOpen()) get_name = true;
    if (get_name) {
        //открываем диалоговое окно, вводим название организации

        //сохраняем полученный результат в файл
        file->open(QFile::WriteOnly);
        QTextStream out(file);
        out << "org_name = " + org_name + "\n";
        out << "app_name = " + app_name + "\n";

    } else {
        //читаем название организации из файла
        QString name;
        QByteArray line;
        while (!file->atEnd()) {
            line = file->readLine();
            if (line.at(0) != '#') {
                if (line.contains("org_name")) {
                    name = line;
                    if (name.split("=").count()>1) {
                        name = name.split("=").at(1).trimmed();
                        org_name = name;
                    }
                }
                if (line.contains("app_name")) {
                    name = line;
                    if (name.split("=").count()>1) {
                        name = name.split("=").at(1).trimmed();
                        app_name = name;
                    }
                }
            }
        }
    }
    file->close();
    //qDebug() << "Org name " << org_name;

    //устанавливаем название организации
    QCoreApplication::setOrganizationName(org_name);
    QCoreApplication::setApplicationName(app_name);

    QFileInfo *fi = new QFileInfo;
    fi->setFile(org_file_name);

    QString path = fi->absolutePath();

    QApplication a(argc, argv);

    QTranslator myTranslator;
    myTranslator.load("cengen_ru.qm", path);
    a.installTranslator(&myTranslator);

    cengen w;
    w.set_org_name(org_name, app_name);

    for (int i = 0; i<argc; i++) {
        param = codec->toUnicode(argv[i]);

        if (check_extention(param, ".tov")) {
            w.open_tovar_list(param);
        }
        if (check_extention(param, ".fli")) {
            w.turn_filter_ON();
            w.load_filter_settings_file(param);
        }
        if (check_extention(param, ".das")) {
            w.load_source_settings_file(param);
        }
        if (check_extention(param, ".dbf")) {
            qDebug() << "Trying to load dbf file";
            w.save_source_settings_file("_$tmp.das");
            bool good = w.set_source_from_dbf(param);
            if (good) w.load_all_records();
            w.load_source_settings_file("_$tmp.das");
            w.repaint();
        }
        if (check_extention(param, "frf")) {
            w.set_ext_shablon_name(param);
        }
        if (check_extention(param, "csf")) {
            QLabel *lbl = new QLabel("Please wait! Executing scenarium file");
            lbl->show();
            lbl->repaint();
            w.execute_macro_file(param);
            lbl->hide();
        }
    }

    w.show();
    return a.exec();
}
Example #27
0
void menu::recurse(QMenu *cm, QFile &istr)
{
	QString p1,p2,p3;
	
	while(! istr.atEnd())
	{
		QTextStream til(istr.readLine(1024));

		til >> p1;  // command 
		if(p1.isEmpty() || p1 == "#")
			continue;
		
		if(p1 == "End")
			return;

		if(p1 == "Separator")
		{
			cm->addSeparator();
			continue;
		}	

		til >> p2;            // menu label
		
		if(p2.isEmpty())
			continue;

		p3 = til.readLine();  // command line

		if(p2[0] == '"')
		{
			if(p2[p2.length()-1] != '"')
			{
				int i = p3.indexOf('"');
				if(i == -1)
					continue;
				
				p2 += p3.left(i);
				p2 = p2.mid(1, p2.length()-1);
				p3 = p3.right(p3.length()-i-1);
			}
			else p2 = p2.mid(1, p2.length()-2);
		}
		
		if(p1 == "Menu")
		{
			QMenu *nm = new QMenu(p2);
			Q_CHECK_PTR(nm);
			cm->addMenu(nm);
			recurse(nm, istr);
			continue;
		}

		if(p1 == "Quit")
		{
			act_quit->setText(p2);
			cm->addAction(act_quit);
			continue;
		}
		
		if(p1 == "Kill")
		{
			act_kill->setText(p2);
			cm->addAction(act_kill);
			continue;
		}	

		if(p1 == "Restart")
		{
			act_rest->setText(p2);
			cm->addAction(act_rest);
			continue;
		}	
		
		if(p1 != "Entry")
			continue;

		p3 = p3.simplified();
		
		if(p3.isEmpty())
			continue;
			
		QAction *act_run = new QAction(p2, cm);
		act_run->setData(QVariant(p3));
		cm->addAction(act_run);
	}
}	
Example #28
0
void txCommonParameters::readConfigFile(const QString &cfgFileName) {

    createNeededFiles();

    QFile cfgFile1(cfgFileName);
    QFile cfgFile2(QDir::homePath() + QDir::separator() + cfgFileName);
    QFile cfgFile;

    if ( cfgFile1.exists() ) {
        cfgFile.setFileName(cfgFile1.fileName());
    }
    else if ( cfgFile2.exists() ) {
        cfgFile.setFileName(cfgFile2.fileName());
    }
    else {

        const QString myPreferences =
                "//\n// This is r49 configuration file. "
                "Parameter-Value delimeter is \"=\" symbol.\n// "
                "Text after \"//\" is comment.\n//\n\n"
                "// Temporary rewrited source data files\nsrc_file_name_EU3="
                + m_srcFileNameEU3
                + "\n"
                "src_file_name_EU0="
                + m_srcFileNameEU0
                + "\n"
                "src_file_name_points="
                + m_srcFileNamePoints
                + "\n"
                "src_file_name_redpwr="
                + m_srcFileNameRedPwr
                + "\n\n"
                "// Directory for calculation results\nreports_dir_name="
                + m_reportsDirName
                + "\n\n"
                "// Measuring nozzle diameter "
                "(engine inlet air mass flow calculation)\nDn="
                + QString::number(m_Dn)
                + "\n\n"
                "// Air oxygen concentration\nconc_O2air="
                + QString::number(m_concO2air)
                + "\n\n"
                "//\nRr="
                + QString::number(m_Rr)
                + "\n\n"
                "// Stoichiometric air/fuel ratio\nL0="
                + QString::number(m_L0)
                + "\n\n"
                "// Opacimeter effective base\nL="
                + QString::number(m_L)
                + "\n\n"
                "// Air carbon dioxide concentration\nconc_CO2air="
                + QString::number(m_concCO2air)
                + "\n\n"
                "// Fuel percentage\nWH="
                + QString::number(m_WH)
                + "\n"
                "WO2="
                + QString::number(m_WO2)
                + "\n"
                "WN="
                + QString::number(m_WN)
                + "\n\n"
                "// Molecular weights\nmuNO2="
                + QString::number(m_muNO2)
                + "\n"
                "muCO="
                + QString::number(m_muCO)
                + "\n"
                "muCH="
                + QString::number(m_muCH)
                + "\n";

        if ( cfgFile1.open(QIODevice::WriteOnly | QIODevice::Text) ) {

            cfgFile1.write(myPreferences.toUtf8());
            cfgFile1.close();

            cfgFile.setFileName(cfgFile1.fileName());
        }
        else if ( cfgFile2.open(QIODevice::WriteOnly | QIODevice::Text) ) {

            cfgFile2.write(myPreferences.toUtf8());
            cfgFile2.close();

            cfgFile.setFileName(cfgFile2.fileName());
        }
        else {
            throw txError("Can not create config file!");
        }

        return;
    }

    if ( !cfgFile.open(QIODevice::ReadOnly | QIODevice::Text) ) {
        throw txError("Can not open config file " + cfgFileName + "!");
    }

    QString s;
    QStringList elements;
    QRegExp rx("^//");

    while ( !cfgFile.atEnd() ) {

        s = cfgFile.readLine().trimmed();

        if ( s.isEmpty() || s.contains(rx) ) {
            continue;
        }

        elements = s.split("=");

        if ( elements[0] == "src_file_name_EU3" ) {
            m_srcFileNameEU3 = elements[1];
        }
        else if ( elements[0] == "src_file_name_EU0" ) {
            m_srcFileNameEU0 = elements[1];
        }
        else if ( elements[0] == "src_file_name_points" ) {
            m_srcFileNamePoints = elements[1];
        }
        else if ( elements[0] == "src_file_name_redpwr" ) {
            m_srcFileNameRedPwr = elements[1];
        }
        else if ( elements[0] == "reports_dir_name" ) {
            m_reportsDirName = elements[1];
        }
        else if ( elements[0] == "Dn" ) {
            m_Dn = (elements[1]).toDouble();
        }
        else if ( elements[0] == "conc_O2air" ) {
            m_concO2air = (elements[1]).toDouble();
        }
        else if ( elements[0] == "Rr" ) {
            m_Rr = (elements[1]).toDouble();
        }
        else if ( elements[0] == "L0" ) {
            m_L0 = (elements[1]).toDouble();
        }
        else if ( elements[0] == "L" ) {
            m_L = (elements[1]).toDouble();
        }
        else if ( elements[0] == "conc_CO2air" ) {
            m_concCO2air = (elements[1]).toDouble();
        }
        else if ( elements[0] == "WH" ) {
            m_WH = (elements[1]).toDouble();
        }
        else if ( elements[0] == "WO2" ) {
            m_WO2 = (elements[1]).toDouble();
        }
        else if ( elements[0] == "WN" ) {
            m_WN = (elements[1]).toDouble();
        }
        else if ( elements[0] == "muNO2" ) {
            m_muNO2 = (elements[1]).toDouble();
        }
        else if ( elements[0] == "muCO" ) {
            m_muCO = (elements[1]).toDouble();
        }
        else if ( elements[0] == "muCH" ) {
            m_muCH = (elements[1]).toDouble();
        }

        elements.clear();
    }

    elements.clear();

    cfgFile.close();
}
Example #29
0
vector<Triangle*> PlyFileParser::ParseFile(string fileName, double scale, Vector3D translation)
{
    VertexCache.clear();
    ModelCache.clear();
    QString qfileName = QString::fromStdString(fileName);
    QFile qFile (qfileName);
    qFile.open(QIODevice::ReadOnly);

    QRegularExpression elementTag = QRegularExpression("(element)\\s(.*?)\\s([0-9]*)");
    QRegularExpression propertyTag = QRegularExpression("(property)\\s(.*?)\\s(.*)");
    QRegularExpression dataLine = QRegularExpression("[0-9\\.\\-]*[\\s\\n]");
    QRegularExpression endHeader = QRegularExpression("end.*");
    
    queue<ElementInfo> elementTypes;
    
    bool finishedParsingHeader = false;
    
    //QTextStream qCout (stdout);
    
    while (!qFile.atEnd())
    {
        QString line = qFile.readLine();
        
        QRegularExpressionMatch elementMatches = elementTag.match(line);

        if(!finishedParsingHeader)
        {
            if (elementMatches.hasMatch())
            {
                ElementInfo elementInfo;
                
                elementInfo.elementName = elementMatches.captured(2).toStdString();
                elementInfo.elementCount = elementMatches.captured(3).toInt();
                
                elementTypes.push(elementInfo);
            }
            
            QRegularExpressionMatch propertyMatch = propertyTag.match(line);
            
            if (propertyMatch.hasMatch())
            {
                PropertyInfo propertyInfo;
                propertyInfo.type = propertyMatch.captured(2).toStdString();
                propertyInfo.name = propertyMatch.captured(3).toStdString();
                
                elementTypes.front().properties.push(propertyInfo);
            }
        }
        else
        {
            ParseDataLine(line, elementTypes.front(), scale, translation);

            elementTypes.front().elementCount--;
            
            if (elementTypes.front().elementCount == 0)
            {
                elementTypes.pop();
            }
        }
        
        if(line.contains(QRegularExpression("end.*")))
        {
            finishedParsingHeader = true;
        }
        
        //qCout << line;
        //qCout.flush();
    }
    
    qFile.close();
    
    return ConvertToVector(ModelCache);
}
Example #30
0
void UpdateAlgePap::updatedata() {

    updatemessage[0] << "Update failed, verify your Internet connexion ...";
    updatemessage[1] << QString::fromUtf8("فشل التحديث، تحقق من اتصال الانترنت ...");

    updatemessage[0] << "Your databases are up to date ...";
    updatemessage[1] << QString::fromUtf8("قاعدة البيانات حديثة ...");

    updatemessage[0] << " : was updated with succeed.\n";
    updatemessage[1] << QString::fromUtf8(" : تم تحديثها بنجاح.\n");

    updatemessage[0] << " : not updated (shucksums failed).\n";
    updatemessage[1] << QString::fromUtf8(" : لم يتم تحديثها (تشفير الملف خاطئ).\n");

    updatemessage[0] << " : not updated (connexion failed).\n";
    updatemessage[1] << QString::fromUtf8("لم يتم تحديثها (الاتصال فشل).\n");

    if(!checkupdate()) {
        QMessageBox::information(this, updatealgepapwindowlabel[*languageindex],
                 updatemessage[*languageindex].at(0));
        return;
    }

    if(!linkdownload.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    if(linkdownload.atEnd()) {
        QMessageBox::information(this, updatealgepapwindowlabel[*languageindex],
                 updatemessage[*languageindex].at(1));
        iniVisible();
        return;
    }
    QString listresult("");
    QString loc, scope[2], link, hash;
        bool update(true);
    while(!linkdownload.atEnd()) {
        loc = scope[0] = scope[1] = link = hash = "";
        loc = QString::fromUtf8(linkdownload.readLine());
        scope[0] = QString::fromUtf8(linkdownload.readLine());
        link = QString::fromUtf8(linkdownload.readLine());
        hash = QString::fromUtf8(linkdownload.readLine());
        scope[1] = QString::fromUtf8(linkdownload.readLine());
        loc.remove("\n");
        scope[0].remove("\n");
        scope[0].remove("downloadscript/Dnd");
        scope[0].remove("information/Dni");
        link.remove("\n");
        hash.remove("\n");
        scope[1].remove("\n");
        QString linkupdate = "wget -t5 \""+link+"\" --output-document \""+DirPath+"/TMP/"+scope[0]+"\"";
        if(!system(linkupdate.toAscii().constData())) {
            QFile tmp(DirPath+"/TMP/"+scope[0]);
            if(!tmp.open(QIODevice::ReadOnly | QIODevice::Text))
                return;
            QByteArray array = tmp.readAll();
            tmp.close();
            QString newhash(QCryptographicHash::hash(array,QCryptographicHash::Sha1).toHex());
            if(newhash == hash) {
                QString commandmv = "mv -f \""+DirPath+"/TMP/"+scope[0]+"\" \""+DirPath+loc+"\"";
                system(commandmv.toAscii().constData());
                listresult+=scope[*languageindex] + updatemessage[*languageindex][2];
            }
            else {
                listresult+=scope[*languageindex] + updatemessage[*languageindex][3];
                update = false;
            }
        }
        else {
            listresult+=scope[*languageindex] + updatemessage[*languageindex][4];
            update = false;
        }
    }
    l->setText(listresult);
    if(update) {
        settings = new QSettings("AlgePap","UpdateAlgePap");
        settings->setValue("Update/LastUpdate",QDate::currentDate().toString());
        settings->setValue("Update/LastUpdatear",QDate::currentDate().toString());
        delete(settings);
    }
}