Ejemplo n.º 1
1
void ProcessesList::produzirListaProcessos(){
    this->listaProcessos.clear();

    QDir *directory;
    QFile *arquivo;
    QString *S;

    QStringList files;
    std::string data;

    QDir aDir("/proc");

    aDir.setFilter(QDir::Dirs);
    QStringList entries = aDir.entryList();
    this->numThreads = 0;

    for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry)
    {
        S = new QString("/proc/" + QString(*entry));

        if((S->compare("/proc/.") == 0) || (S->compare("/proc/..") == 0)){
            continue;
        }

        directory = new QDir(*S);

        if(!directory->exists()){
            continue;
        } else if(!((S->toStdString()[6] >= '0') && (S->toStdString()[6] <= '9'))){
            continue;
        }

        directory->setFilter(QDir::Files);

        arquivo = new QFile(*S + "/status");

        if((!arquivo)){
            qDebug() << "ERRO 1! (" << *S << ")";
            continue;
        } else if(!arquivo->open(QIODevice::ReadOnly | QIODevice::Text)){
            qDebug() << arquivo->errorString();
            qDebug() << "ERRO 2! (" << *S << ")";
            continue;
        }

        process P;

        QTextStream buffer(arquivo);
        QStringList fileContent = buffer.readAll().split("\n");
        QString buf;

        P.nome = processName(fileContent.at(0));
        P.status = processStatus(fileContent.at(1));

        P.pid = processPid(fileContent.at(3));
        P.ppid = processPPid(fileContent.at(4));

        P.user = processUser(fileContent.at(6));

        for (int var = 7; var < fileContent.size(); ++var) {
            buf = fileContent.at(var);
            if(buf.startsWith("Threads")){
                break;
            }
        }

        P.threads = processThreadsNumber(buf);
        this->numThreads += P.threads;

        P.trocas_contexto = processTrocasContexto(fileContent.at(fileContent.size()-3),fileContent.at(fileContent.size()-2));

        this->listaProcessos.push_back(P);

        arquivo->close();
    }

    delete arquivo;
    delete directory;
    delete S;
}
Ejemplo n.º 2
1
/**
 *	計算およびDB構築
 *
 *	@param[in] n			サンプル数
 */
void RMAThread::Calcuration(int n)
{
	// 変数宣言
	QString readFileName;			// 読み込みファイル名
	QFile readFile;					// 読み込みファイル
	QString readFileLine;			// 読み込みファイル行
	QString writeFileName;			// 書き込みファイル名
	QFile writeFile;				// 書き込みファイル
	vector <PliceData> pliceData;	// 時系列データ
	double ma_open;					// MA(Open)
	double ma_high;					// MA(High)
	double ma_low;					// MA(Low)
	double ma_close;				// MA(Close)
	double ma_volume;				// MA(Volume)
	double ma_aClose;				// MA(AClose)
	double pMa_open;				// 前日のMA(Open)
	double pMa_high;				// 前日のMA(High)
	double pMa_low;					// 前日のMA(Low)
	double pMa_close;				// 前日のMA(Close)
	double pMa_volume;				// 前日のMA(Volume)
	double pMa_aClose;				// 前日のMA(AClose)
	PliceData tempData;				// 一時保存用時系列データ
	QString temp_1;					// 一時保存用文字列
	QString temp_2;					// 一時保存用文字列

	// ディレクトリ生成
	_mkdir("DB\\RMA_" + temp_1.setNum(n).toLocal8Bit());

	// 各IDについて処理実行
	for (int i = 1000; i < 1000000; i++) {
		if (((i > 10000) && !((i == 998405) || (i == 998407)))) {
			continue;
		}

		// 変数初期化
		pliceData.clear();

		// 読み込み用ファイルオープン
		readFileName = "Yahoo\\" + temp_1.setNum(i) + ".csv";
		readFile.setFileName(readFileName);
		if (readFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
			// 宣言&初期化
			QTextStream readFileReader(&readFile);
			readFileLine = "";

			// 時系列データの読み取り
			while (!readFileReader.atEnd()) {
				readFileLine = readFileReader.readLine();
				// データ取得
				if (readFileLine != "") {
					tempData.mDate		= QDate::fromString((readFileLine.split(",").at(0)), "yyyy/M/d");
					tempData.mOpen		= readFileLine.split(",").at(1).toDouble();
					tempData.mHigh		= readFileLine.split(",").at(2).toDouble();
					tempData.mLow		= readFileLine.split(",").at(3).toDouble();
					tempData.mClose		= readFileLine.split(",").at(4).toDouble();
					tempData.mVolume	= readFileLine.split(",").at(5).toDouble();
					tempData.mAClose	= readFileLine.split(",").at(6).toDouble();
					pliceData.push_back(tempData);
				}
			}

			// 書き込み用ファイルオープン
			writeFileName = "DB\\RMA_" + temp_1.setNum(n) + "\\" + temp_2.setNum(i) + ".dat";
			writeFile.setFileName(writeFileName);
			if (!writeFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
				return;
			}

			// 書き込み処理
			for (int j = n; j < (int)pliceData.size(); j++) {
				QTextStream out(&writeFile);

				// RMA計算
				ma_open		= 0;
				ma_high		= 0;
				ma_low		= 0;
				ma_close	= 0;
				ma_volume	= 0;
				ma_aClose	= 0;
				if (j == n) {
					for (int k = 0; k < n; k++) {
						ma_open		+= pliceData[j-k].mOpen;
						ma_high		+= pliceData[j-k].mHigh;
						ma_low		+= pliceData[j-k].mLow;
						ma_close	+= pliceData[j-k].mClose;
						ma_volume	+= pliceData[j-k].mVolume;
						ma_aClose	+= pliceData[j-k].mAClose;
					}
					ma_open		= ma_open / n;
					ma_high		= ma_high / n;
					ma_low		= ma_low / n;
					ma_close	= ma_close / n;
					ma_volume	= ma_volume / n;
					ma_aClose	= ma_aClose / n;
				}
				else {
					ma_open		= ((n - 1) * pMa_open + pliceData[j].mOpen) / n;
					ma_high		= ((n - 1) * pMa_high + pliceData[j].mHigh) / n;
					ma_low		= ((n - 1) * pMa_low + pliceData[j].mLow) / n;
					ma_close	= ((n - 1) * pMa_close + pliceData[j].mClose) / n;
					ma_volume	= ((n - 1) * pMa_volume + pliceData[j].mVolume) / n;
					ma_aClose	= ((n - 1) * pMa_aClose + pliceData[j].mAClose) / n;
				}

				// RMAおよび乖離率の書き込み
				out << (pliceData[j].mDate.toString("yyyy/M/d")) << ","
					<< ma_open << ","
					<< ma_high << ","
					<< ma_low << ","
					<< ma_close << ","
					<< ma_volume << ","
					<< ma_aClose << ","
					<< (pliceData[j-1].mOpen - ma_open) / ma_open * 100 << ","
					<< (pliceData[j-1].mHigh - ma_high) / ma_high * 100 << ","
					<< (pliceData[j-1].mLow - ma_low) / ma_low * 100 << ","
					<< (pliceData[j-1].mClose - ma_close) / ma_close * 100 << ","
					<< (pliceData[j-1].mVolume - ma_volume) / ma_volume * 100 << ","
					<< (pliceData[j-1].mAClose - ma_aClose) / ma_aClose * 100 << "\n";
				pMa_open = ma_open;
				pMa_high = ma_high;
				pMa_low = ma_low;
				pMa_close = ma_close;
				pMa_volume = ma_volume;
				pMa_aClose = ma_aClose;
			}

			writeFile.close();
		}

		readFile.close();
	}
}
Ejemplo n.º 3
0
int CueSheetModel::parseCueFile(QFile &cueFile, const QDir &baseDir, QCoreApplication *application, const QTextCodec *codec)
{
	cueFile.reset();
	qDebug("\n[Cue Sheet Import]");
	bool bForceLatin1 = false;

	//Reject very large files, as parsing might take until forever
	if(cueFile.size() >= 10485760i64)
	{
		qWarning("File is very big. Probably not a Cue Sheet. Rejecting...");
		return 2;
	}

	//Test selected Codepage for decoding errors
	qDebug("Character encoding is: %s.", codec->name().constData());
	const QString replacementSymbol = QString(QChar(QChar::ReplacementCharacter));
	QByteArray testData = cueFile.peek(1048576);
	if((!testData.isEmpty()) && codec->toUnicode(testData.constData(), testData.size()).contains(replacementSymbol))
	{
		qWarning("Decoding error using selected codepage (%s). Enforcing Latin-1.", codec->name().constData());
		bForceLatin1 = true;
	}
	testData.clear();

	//Init text stream
	QTextStream cueStream(&cueFile);
	cueStream.setAutoDetectUnicode(false);
	cueStream.setCodec(bForceLatin1 ? "latin1" : codec->name());
	cueStream.seek(0i64);

	//Create regular expressions
	QRegExp rxFile("^FILE\\s+(\"[^\"]+\"|\\S+)\\s+(\\w+)$", Qt::CaseInsensitive);
	QRegExp rxTrack("^TRACK\\s+(\\d+)\\s(\\w+)$", Qt::CaseInsensitive);
	QRegExp rxIndex("^INDEX\\s+(\\d+)\\s+([0-9:]+)$", Qt::CaseInsensitive);
	QRegExp rxTitle("^TITLE\\s+(\"[^\"]+\"|\\S+)$", Qt::CaseInsensitive);
	QRegExp rxPerformer("^PERFORMER\\s+(\"[^\"]+\"|\\S+)$", Qt::CaseInsensitive);
	QRegExp rxGenre("^REM\\s+GENRE\\s+(\"[^\"]+\"|\\S+)$", Qt::CaseInsensitive);
	QRegExp rxYear("^REM\\s+DATE\\s+(\\d+)$", Qt::CaseInsensitive);
	
	bool bPreamble = true;
	bool bUnsupportedTrack = false;

	CueSheetFile *currentFile = NULL;
	CueSheetTrack *currentTrack = NULL;

	m_albumTitle.clear();
	m_albumPerformer.clear();
	m_albumGenre.clear();
	m_albumYear = 0;

	//Loop over the Cue Sheet until all lines were processed
	for(int lines = 0; lines < INT_MAX; lines++)
	{
		if(application)
		{
			application->processEvents();
			if(lines < 128) Sleep(10);
		}
		
		if(cueStream.atEnd())
		{
			qDebug("End of Cue Sheet file.");
			break;
		}

		QString line = cueStream.readLine().trimmed();
		
		/* --- FILE --- */
		if(rxFile.indexIn(line) >= 0)
		{
			qDebug("%03d File: <%s> <%s>", lines, rxFile.cap(1).toUtf8().constData(), rxFile.cap(2).toUtf8().constData());
			if(currentFile)
			{
				if(currentTrack)
				{
					if(currentTrack->isValid())
					{
						currentFile->addTrack(currentTrack);
						currentTrack = NULL;
					}
					else
					{
						LAMEXP_DELETE(currentTrack);
					}
				}
				if(currentFile->isValid())
				{
					m_files.append(currentFile);
					currentFile = NULL;
				}
				else
				{
					LAMEXP_DELETE(currentFile);
				}
			}
			else
			{
				LAMEXP_DELETE(currentTrack);
			}
			if(!rxFile.cap(2).compare("WAVE", Qt::CaseInsensitive) || !rxFile.cap(2).compare("MP3", Qt::CaseInsensitive) || !rxFile.cap(2).compare("AIFF", Qt::CaseInsensitive))
			{
				currentFile = new CueSheetFile(baseDir.absoluteFilePath(UNQUOTE(rxFile.cap(1))));
				qDebug("%03d File path: <%s>", lines, currentFile->fileName().toUtf8().constData());
			}
			else
			{
				bUnsupportedTrack = true;
				qWarning("%03d Skipping unsupported file of type '%s'.", lines, rxFile.cap(2).toUtf8().constData());
				currentFile = NULL;
			}
			bPreamble = false;
			currentTrack = NULL;
			continue;
		}
		
		/* --- TRACK --- */
		if(rxTrack.indexIn(line) >= 0)
		{
			if(currentFile)
			{
				qDebug("%03d   Track: <%s> <%s>", lines, rxTrack.cap(1).toUtf8().constData(), rxTrack.cap(2).toUtf8().constData());
				if(currentTrack)
				{
					if(currentTrack->isValid())
					{
						currentFile->addTrack(currentTrack);
						currentTrack = NULL;
					}
					else
					{
						LAMEXP_DELETE(currentTrack);
					}
				}
				if(!rxTrack.cap(2).compare("AUDIO", Qt::CaseInsensitive))
				{
					currentTrack = new CueSheetTrack(currentFile, rxTrack.cap(1).toInt());
				}
				else
				{
					bUnsupportedTrack = true;
					qWarning("%03d   Skipping unsupported track of type '%s'.", lines, rxTrack.cap(2).toUtf8().constData());
					currentTrack = NULL;
				}
			}
			else
			{
				LAMEXP_DELETE(currentTrack);
			}
			bPreamble = false;
			continue;
		}
		
		/* --- INDEX --- */
		if(rxIndex.indexIn(line) >= 0)
		{
			if(currentFile && currentTrack)
			{
				qDebug("%03d     Index: <%s> <%s>", lines, rxIndex.cap(1).toUtf8().constData(), rxIndex.cap(2).toUtf8().constData());
				if(rxIndex.cap(1).toInt() == 1)
				{
					currentTrack->setStartIndex(parseTimeIndex(rxIndex.cap(2)));
				}
			}
			continue;
		}

		/* --- TITLE --- */
		if(rxTitle.indexIn(line) >= 0)
		{
			if(bPreamble)
			{
				m_albumTitle = UNQUOTE(rxTitle.cap(1)).simplified();
			}
			else if(currentFile && currentTrack)
			{
				qDebug("%03d     Title: <%s>", lines, rxTitle.cap(1).toUtf8().constData());
				currentTrack->setTitle(UNQUOTE(rxTitle.cap(1)).simplified());
			}
			continue;
		}

		/* --- PERFORMER --- */
		if(rxPerformer.indexIn(line) >= 0)
		{
			if(bPreamble)
			{
				m_albumPerformer = UNQUOTE(rxPerformer.cap(1)).simplified();
			}
			else if(currentFile && currentTrack)
			{
				qDebug("%03d     Title: <%s>", lines, rxPerformer.cap(1).toUtf8().constData());
				currentTrack->setPerformer(UNQUOTE(rxPerformer.cap(1)).simplified());
			}
			continue;
		}

		/* --- GENRE --- */
		if(rxGenre.indexIn(line) >= 0)
		{
			if(bPreamble)
			{
				QString temp = UNQUOTE(rxGenre.cap(1)).simplified();
				for(int i = 0; g_lamexp_generes[i]; i++)
				{
					if(temp.compare(g_lamexp_generes[i], Qt::CaseInsensitive) == 0)
					{
						m_albumGenre = QString(g_lamexp_generes[i]);
						break;
					}
				}
			}
			else if(currentFile && currentTrack)
			{
				qDebug("%03d     Genre: <%s>", lines, rxGenre.cap(1).toUtf8().constData());
				QString temp = UNQUOTE(rxGenre.cap(1).simplified());
				for(int i = 0; g_lamexp_generes[i]; i++)
				{
					if(temp.compare(g_lamexp_generes[i], Qt::CaseInsensitive) == 0)
					{
						currentTrack->setGenre(QString(g_lamexp_generes[i]));
						break;
					}
				}
			}
			continue;
		}

		/* --- YEAR --- */
		if(rxYear.indexIn(line) >= 0)
		{
			if(bPreamble)
			{
				bool ok = false;
				unsigned int temp = rxYear.cap(1).toUInt(&ok);
				if(ok) m_albumYear =  temp;
			}
			else if(currentFile && currentTrack)
			{
				qDebug("%03d     Year: <%s>", lines, rxPerformer.cap(1).toUtf8().constData());
				bool ok = false;
				unsigned int temp = rxYear.cap(1).toUInt(&ok);
				if(ok) currentTrack->setYear(temp);
			}
			continue;
		}
	}

	//Append the very last track/file that is still pending
	if(currentFile)
	{
		if(currentTrack)
		{
			if(currentTrack->isValid())
			{
				currentFile->addTrack(currentTrack);
				currentTrack = NULL;
			}
			else
			{
				LAMEXP_DELETE(currentTrack);
			}
		}
		if(currentFile->isValid())
		{
			m_files.append(currentFile);
			currentFile = NULL;
		}
		else
		{
			LAMEXP_DELETE(currentFile);
		}
	}

	//Finally calculate duration of each track
	int nFiles = m_files.count();
	for(int i = 0; i < nFiles; i++)
	{
		if(application)
		{
			application->processEvents();
			Sleep(10);
		}

		CueSheetFile *currentFile = m_files.at(i);
		int nTracks = currentFile->trackCount();
		if(nTracks > 1)
		{
			for(int j = 1; j < nTracks; j++)
			{
				CueSheetTrack *currentTrack = currentFile->track(j);
				CueSheetTrack *previousTrack = currentFile->track(j-1);
				double duration = currentTrack->startIndex() - previousTrack->startIndex();
				previousTrack->setDuration(qMax(0.0, duration));
			}
		}
	}
	
	//Sanity check of track numbers
	if(nFiles > 0)
	{
		bool hasTracks = false;
		int previousTrackNo = -1;
		bool trackNo[100];
		for(int i = 0; i < 100; i++)
		{
			trackNo[i] = false;
		}

		for(int i = 0; i < nFiles; i++)
		{
			if(application)
			{
				application->processEvents();
				Sleep(10);
			}
			CueSheetFile *currentFile = m_files.at(i);
			int nTracks = currentFile->trackCount();
			if(nTracks > 1)
			{
				for(int j = 0; j < nTracks; j++)
				{
					int currentTrackNo = currentFile->track(j)->trackNo();
					if(currentTrackNo > 99)
					{
						qWarning("Track #%02d is invalid (maximum is 99), Cue Sheet is inconsistent!", currentTrackNo);
						return ErrorInconsistent;
					}
					if(currentTrackNo <= previousTrackNo)
					{
						qWarning("Non-increasing track numbers (%02d -> %02d), Cue Sheet is inconsistent!", previousTrackNo, currentTrackNo);
						return ErrorInconsistent;
					}
					if(trackNo[currentTrackNo])
					{
						qWarning("Track #%02d exists multiple times, Cue Sheet is inconsistent!", currentTrackNo);
						return ErrorInconsistent;
					}
					trackNo[currentTrackNo] = true;
					previousTrackNo = currentTrackNo;
					hasTracks = true;
				}
			}
		}
		
		if(!hasTracks)
		{
			qWarning("Could not find at least one valid track in the Cue Sheet!");
			return ErrorInconsistent;
		}

		return ErrorSuccess;
	}
	else
	{
		qWarning("Could not find at least one valid input file in the Cue Sheet!");
		return bUnsupportedTrack ? ErrorUnsupported : ErrorBadFile;
	}
}
Ejemplo n.º 4
0
void HuggleTest::testCaseScores()
{
    Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.clear();
    Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("f**k", 10));
    Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("f*****g", 20));
    Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("v****a", 50));
    Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("f**k this bitch", 20));
    Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("suck", 60));
    Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("ass", 60));
    Huggle::Configuration::HuggleConfiguration->SystemConfig_WordSeparators << " " << "." << "," << "(" << ")" << ":" << ";" << "!" << "?" << "/";
    Huggle::GC::gc = new Huggle::GC();
    Huggle::WikiEdit *edit = new Huggle::WikiEdit();
    edit->Page = new Huggle::WikiPage("test");
    edit->User = new Huggle::WikiUser("Harry, the vandal");
    edit->DiffText = "f**k this v****a!";
    edit->Score = 0;
    edit->ProcessWords();
    QVERIFY2(edit->Score == 60, QString("01 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    QVERIFY2(edit->ScoreWords.contains("v****a"), "02 Invalid result for score words");
    QVERIFY2(edit->ScoreWords.contains("f**k"), "03 Invalud result for score words");
    edit->DiffText = "fuc_k v****a!";
    edit->Score = 0;
    edit->ProcessWords();
    QVERIFY2(edit->Score == 50, QString("04 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    QVERIFY2(edit->ScoreWords.contains("v****a"), "05 Invalid result for score words");
    edit->DiffText = "Hey bob, (f**k) there is some v****a.";
    edit->Score = 0;
    edit->ProcessWords();
    QVERIFY2(edit->Score == 60, "06 Invalid result for score words");
    QVERIFY2(edit->ScoreWords.contains("v****a"), "07 Invalid result for score words");
    QVERIFY2(edit->ScoreWords.contains("f**k"), "08 Invalid result for score words");
    edit->DiffText = "Hey bob, f**k this bitch over.";
    edit->Score = 0;
    edit->ProcessWords();
    QVERIFY2(edit->Score == 30, "06 Invalid result for score words");
    edit->DiffText = "Hey bob, (f**k) there is some v****a, let's f**k that v****a.";
    edit->Score = 0;
    edit->ProcessWords();
    QVERIFY2(edit->Score == 60, QString("09 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    QVERIFY2(edit->ScoreWords.contains("v****a"), "10 Invalid result for score words");
    QVERIFY2(edit->ScoreWords.contains("f**k"), "12 Invalid result for score words");
    edit->DiffText = "Hey bob, there are vaginas over there";
    edit->Score = 0;
    edit->ProcessWords();
    QVERIFY2(edit->Score == 0, QString("14 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    edit->DiffText = "Hey bob, mind if I'd be f*****g with you?";
    edit->Score = 0;
    edit->ProcessWords();
    QVERIFY2(edit->Score == 20, QString("16 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    edit->DiffText = "Hey bob, stop f****n that v****a!!";
    edit->Score = 0;
    edit->ProcessWords();
    QVERIFY2(edit->Score == 50, QString("18 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    QFile *vf = new QFile(":/test/wikipage/page01.txt");
    vf->open(QIODevice::ReadOnly);
    edit->DiffText = QString(vf->readAll());
    edit->Score = 0;
    edit->ProcessWords();
    delete vf;
    QVERIFY2(edit->Score == 0, QString("20 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    vf = new QFile(":/test/wikipage/page02.txt");
    vf->open(QIODevice::ReadOnly);
    edit->DiffText = QString(vf->readAll());
    edit->Score = 0;
    edit->ProcessWords();
    delete vf;
    QVERIFY2(edit->Score == 0, QString("22 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    vf = new QFile(":/test/wikipage/page03.txt");
    vf->open(QIODevice::ReadOnly);
    edit->DiffText = QString(vf->readAll());
    edit->Score = 0;
    edit->ProcessWords();
    delete vf;
    QVERIFY2(edit->Score == 60, QString("26 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    vf = new QFile(":/test/wikipage/page04.txt");
    vf->open(QIODevice::ReadOnly);
    edit->DiffText = QString(vf->readAll());
    edit->Score = 0;
    edit->ProcessWords();
    delete vf;
    QVERIFY2(edit->Score == 10, QString("26 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
    edit->SafeDelete();
    delete Huggle::GC::gc;
    Huggle::GC::gc = NULL;
}
void DataJson::createJsonStandard()
{
    QJsonObject ambitCat, ambitEsp, ambitFran;
    QJsonObject ejeCat, ejeEsp,ejeFran;
    QJsonArray ejecutablesCat,ejecutablesEsp,ejecutablesFran;

    //Crear QJsonObject ambitCat
    ambitCat.insert("Nombreambito",QJsonValue(QString("Catalunya lidar 2 metres")));
    if(_objectSettingPref->existPathImageCatSett())
    {
        ambitCat.insert("Path",_objectSettingPref->getSettingImageCat());
    }
    else
    {
        ambitCat.insert("Path",QJsonValue(QString("//nas02/treballcompartit/dtmdbdad/BD_CAT2MLID_ET.RF")));
    }
        ambitCat.insert("TamanyoPixel",QJsonValue(int(1)));
    ambitCat.insert("Utm",QJsonValue(int(31)));
    ejeCat.insert("Nombre",QJsonValue(QString("exeExtraction")));
    if(_objectSettingPref->existExeExtraSett())
        {ejeCat.insert("Path",_objectSettingPref->getExeExtraction());}
    else
        {ejeCat.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCDTMOperations/exe/ICCADBDTMEXTRACTIONCONSOLEVERSION.exe")));
    }
            ejecutablesCat.append(ejeCat);
    ejeCat.insert("Nombre",QJsonValue(QString("exeResize")));
    if(_objectSettingPref->existExeResiSett())
        {ejeCat.insert("Path",_objectSettingPref->getExeResize());}
    else
       { ejeCat.insert("Path",QJsonValue(QString("//empuries/PRODUCCIO/DFApplications/ICCImageOperations/exe/ICCImageresize.exe")));
    }
            ejecutablesCat.append(ejeCat);
    ejeCat.insert("Nombre",QJsonValue(QString("exeFootPrintMask")));
    if(_objectSettingPref->existExeFootPSett())
       { ejeCat.insert("Path",_objectSettingPref->getExeFootPrintMask());}
    else
        {ejeCat.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageFootPrintMask.exe")));
    }
            ejecutablesCat.append(ejeCat);
    ejeCat.insert("Nombre",QJsonValue(QString("exeSubScene")));
    if(_objectSettingPref->existExeSubeSett())
        {ejeCat.insert("Path",_objectSettingPref->getExeSubScene());}
    else
        {ejeCat.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageSubescenes.exe")));
    }
            ejecutablesCat.append(ejeCat);
    ejeCat.insert("Nombre",QJsonValue(QString("exeGeoTransform")));
    if(_objectSettingPref->existExeImaOpeoSett())
        {ejeCat.insert("Path",_objectSettingPref->getExeImaOpeGeo());}
    else
        {ejeCat.insert("Path",QJsonValue(QString("//nas03/geoproces/DFApplications/ICCImageOperationsGeoCorrection/exe/ICCImageGeoTransformation.exe")));
    }
            ejecutablesCat.append(ejeCat);
    ambitCat.insert("Ejecutables",ejecutablesCat);

    //Crear QJsonObject ambitEsp
    ambitEsp.insert("Nombreambito",QJsonValue(QString("Espanya 5 metres")));
    if(_objectSettingPref->existPathImageEspSett())
        {
        ambitEsp.insert("Path",_objectSettingPref->getSettingImageEsp());
    }
    else
       {
        ambitEsp.insert("Path",QJsonValue(QString("//Pedros/Disc_E/Antonio/mosaicMetEspanya.rf")));
    }
    ambitEsp.insert("TamanyoPixel",QJsonValue(int(5)));
    ambitEsp.insert("Utm",QJsonValue(int(30)));
    ejeEsp.insert("Nombre",QJsonValue(QString("exeFootPrintMask")));
    if(_objectSettingPref->existExeFootPSett())
       { ejeEsp.insert("Path",_objectSettingPref->getExeFootPrintMask());}
    else
        {ejeEsp.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageFootPrintMask.exe")));
    }
            ejecutablesEsp.append(ejeEsp);
    ejeEsp.insert("Nombre",QJsonValue(QString("exeResize")));
    if(_objectSettingPref->existExeResiSett())
       { ejeEsp.insert("Path",_objectSettingPref->getExeResize());}
    else
        {ejeEsp.insert("Path",QJsonValue(QString("//empuries/PRODUCCIO/DFApplications/ICCImageOperations/exe/ICCImageresize.exe")));
    }
            ejecutablesEsp.append(ejeEsp);
    ejeEsp.insert("Nombre",QJsonValue(QString("exeSubScene")));
    if(_objectSettingPref->existExeSubeSett())
       { ejeEsp.insert("Path",_objectSettingPref->getExeSubScene());}
    else
       { ejeEsp.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageSubescenes.exe")));
    }
            ejecutablesEsp.append(ejeEsp);
    ejeEsp.insert("Nombre",QJsonValue(QString("exeGeoTransform")));
    if(_objectSettingPref->existExeImaOpeoSett())
        {ejeEsp.insert("Path",_objectSettingPref->getExeImaOpeGeo());}
    else
        {ejeEsp.insert("Path",QJsonValue(QString("//nas03/geoproces/DFApplications/ICCImageOperationsGeoCorrection/exe/ICCImageGeoTransformation.exe")));
   }
            ejecutablesEsp.append(ejeEsp);
    ambitEsp.insert("Ejecutables",ejecutablesEsp);

    //Crear QJsonObject ambitFran
    ambitFran.insert("Nombreambito",QJsonValue(QString("Francia Farmstar")));
    if(_objectSettingPref->existPathImageFraSett())
       { ambitFran.insert("Path",_objectSettingPref->getSettingImageFran());}
    else
       { ambitFran.insert("Path",QJsonValue(QString("//Pedros/Disc_E/Antonio/MosaicMetFarmstar_NTF_ELIP.rf")));}
    ambitFran.insert("TamanyoPixel",QJsonValue(int(10)));
    ambitFran.insert("Utm",QJsonValue(int(-2)));

    ejeFran.insert("Nombre",QJsonValue(QString("exeFootPrintMask")));
    if(_objectSettingPref->existExeFootPSett())
        {ejeFran.insert("Path",_objectSettingPref->getExeFootPrintMask());}
    else
       { ejeFran.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageFootPrintMask.exe")));
    }
            ejecutablesFran.append(ejeFran);

    ejeFran.insert("Nombre",QJsonValue(QString("exeResize")));
    if(_objectSettingPref->existExeResiSett())
        {ejeFran.insert("Path",_objectSettingPref->getExeResize());}
    else
       { ejeFran.insert("Path",QJsonValue(QString("//empuries/PRODUCCIO/DFApplications/ICCImageOperations/exe/ICCImageresize.exe")));
    }
            ejecutablesFran.append(ejeFran);
    ejeFran.insert("Nombre",QJsonValue(QString("exeSubScene")));
    if(_objectSettingPref->existExeSubeSett())
       { ejeFran.insert("Path",_objectSettingPref->getExeSubScene());}
    else
       { ejeFran.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageSubescenes.exe")));
    }
            ejecutablesFran.append(ejeFran);
    ejeFran.insert("Nombre",QJsonValue(QString("exeResize")));
    if(_objectSettingPref->existExeResiSett())
        {ejeFran.insert("Path",_objectSettingPref->getExeResize());}
    else
        {ejeFran.insert("Path",QJsonValue(QString("//empuries/PRODUCCIO/DFApplications/ICCImageOperations/exe/ICCImageresize.exe")));
    }
            ejecutablesFran.append(ejeFran);
    ambitFran.insert("Ejecutables",ejecutablesFran);

    QJsonArray array;
    array.prepend((ambitCat));
    array.prepend((ambitFran));
    array.prepend((ambitEsp));
    QJsonDocument documento;
    documento.setArray(array);
    QFile documentoTexto;
    QTextStream value;
    QString PathFileJsonDefecto=qApp->applicationDirPath()+"/dataAplicationToolsPcot.txt";
    documentoTexto.setFileName(PathFileJsonDefecto);
    documentoTexto.open(QFile::WriteOnly | QFile::Text);
    value.setDevice(&documentoTexto);
    value << documento.toJson();
}
Ejemplo n.º 6
0
//----------------------------------------------------------------------
// Silently save ride and convert to GC format without warning user
//----------------------------------------------------------------------
void
MainWindow::saveSilent(RideItem *rideItem)
{
    QFile   currentFile(rideItem->path + QDir::separator() + rideItem->fileName);
    QFileInfo currentFI(currentFile);
    QString currentType =  currentFI.completeSuffix().toUpper();
    QFile   savedFile;
    bool    convert;

    // Do we need to convert the file type?
    if (currentType != "JSON") convert = true;
    else convert = false;

    // Has the date/time changed?
    QDateTime ridedatetime = rideItem->ride()->startTime();
    QChar zero = QLatin1Char ( '0' );
    QString targetnosuffix = QString ( "%1_%2_%3_%4_%5_%6" )
                               .arg ( ridedatetime.date().year(), 4, 10, zero )
                               .arg ( ridedatetime.date().month(), 2, 10, zero )
                               .arg ( ridedatetime.date().day(), 2, 10, zero )
                               .arg ( ridedatetime.time().hour(), 2, 10, zero )
                               .arg ( ridedatetime.time().minute(), 2, 10, zero )
                               .arg ( ridedatetime.time().second(), 2, 10, zero );

    // if there is a notes file we need to rename it (cpi we will ignore)
    QFile notesFile(currentFI.path() + QDir::separator() + currentFI.baseName() + ".notes");
    if (notesFile.exists()) notesFile.remove();

    // When datetime changes we need to update
    // the filename & rename/delete old file
    // we also need to preserve the notes file
    if (currentFI.baseName() != targetnosuffix) {

        // rename as backup current if converting, or just delete it if its already .gc
        // unlink previous .bak if it is already there
        if (convert) {
            QFile::remove(currentFile.fileName()+".bak"); // ignore errors if not there
            currentFile.rename(currentFile.fileName(), currentFile.fileName() + ".bak");
        } else currentFile.remove();
        convert = false; // we just did it already!

        // set the new filename & Start time everywhere
        currentFile.setFileName(rideItem->path + QDir::separator() + targetnosuffix + ".json");
        rideItem->setFileName(QFileInfo(currentFile).path(), QFileInfo(currentFile).fileName());
    }

    // set target filename
    if (convert) {
        // rename the source
        savedFile.setFileName(currentFI.path() + QDir::separator() + currentFI.baseName() + ".json");
    } else {
        savedFile.setFileName(currentFile.fileName());
    }

    // update the change history
    QString log = rideItem->ride()->getTag("Change History", "");
    log +=  tr("Changes on ");
    log +=  QDateTime::currentDateTime().toString() + ":";
    log += '\n' + rideItem->ride()->command->changeLog();
    rideItem->ride()->setTag("Change History", log);

    // save in GC format
    JsonFileReader reader;
    reader.writeRideFile(this, rideItem->ride(), savedFile);

    // rename the file and update the rideItem list to reflect the change
    if (convert) {

        // rename on disk
        QFile::remove(currentFile.fileName()+".bak"); // ignore errors if not there
        currentFile.rename(currentFile.fileName(), currentFile.fileName() + ".bak");

        // rename in memory
        rideItem->setFileName(QFileInfo(savedFile).path(), QFileInfo(savedFile).fileName());
    }


    // mark clean as we have now saved the data
    rideItem->ride()->emitSaved();
}
Ejemplo n.º 7
0
#if 1
    if ((longitude != std::numeric_limits<double>::infinity()) && (latitude != std::numeric_limits<double>::infinity())) {
        network_manager = new QNetworkAccessManager();
        QObject::connect(network_manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(dataReceived(QNetworkReply*)));
        network_manager->get(QNetworkRequest(QUrl("http://api.yr.no/weatherapi/locationforecast/1.9/?lat=" + QString::number(latitude,'f',2) + ";lon=" + QString::number(longitude,'f',2))));
        fetch_timer = new QTimer();
        QObject::connect(fetch_timer,SIGNAL(timeout()),this,SLOT(fetchAgain()));
    }

#else
    /******** Dummy ***********/



    QDomDocument doc;
    QFile f(QStringLiteral("c:/temp/api.yr.no.xml"));
    f.open(QIODevice::ReadOnly);
    doc.setContent(f.readAll());
    f.close();
    qDebug() << "constr onXML";
    onXMLReceived(doc.documentElement());


    /******** End Dummy ***********/
#endif
}

void QVWeather::dataReceived(QNetworkReply* reply) {
    if (reply->isRunning()) {
        return;
    }
Ejemplo n.º 8
0
bool KNMusicTagWav::parseTag(QFile &musicFile,
                             QDataStream &musicDataStream,
                             KNMusicAnalysisItem &analysisItem)
{
    //Check file size.
    if(musicFile.size()<12)
    {
        //It cannot be a wav format file, until a valid one.
        return false;
    }
    //Gernerate the header cache.
    char rawHeader[12];
    //Read the header.
    musicDataStream.readRawData(rawHeader, 12);
    //Check the riff header and the wave header.
    if(memcmp(rawHeader, m_riffHeader, 4)!=0 ||
            memcmp(rawHeader+8, m_waveHeader, 4)!=0)
    {
        //This is not a wav file.
        return false;
    }
    /*
     * WAV file is a combination of several chunks.
     * Read all the chunks, and find LIST and id32 chunk.
     */
    //Get the music file size.
    qint64 fileSize=musicFile.size();
    //Generate the chunk header cache.
    char chunkHeader[8];
    //Initial the chunk found flag.
    bool listFound=false, id32Found=false;
    //We have to prepare the list here and write the data after parse all the
    //data, we want the id32 chunk has a higher priority than list chunk.
    //Prepare the wav item list for list chunk.
    QList<WAVItem> listData;
    //Generate the raw frame linked list for id32 chunk.
    QLinkedList<ID3v2Frame> frames;
    //Generate the id3v2 frame function set for id32 chunk.
    ID3v2FunctionSet functionSet;
    //Start finding the chunk.
    while(musicDataStream.device()->pos()<fileSize && !listFound && !id32Found)
    {
        //Read chunk head.
        musicDataStream.readRawData(chunkHeader, 8);
        //Calculate the chunk size.
        quint32 chunkSize=KNMusicUtil::inverseCharToInt32(chunkHeader+4);
        //Check if it's list chunk
        if(memcmp(chunkHeader, m_listChunk, 4)==0)
        {
            //Set list chunk found flag to true.
            listFound=true;
            //Generate chunk size cache.
            char *listRawData=new char[chunkSize];
            //Read the raw data.
            musicDataStream.readRawData(listRawData, chunkSize);
            //Parse list chunk.
            parseListChunk(listRawData, chunkSize, listData);
            //Recover memory.
            delete[] listRawData;
        }
        //Check if it's id32 chunk.
        else if(memcmp(chunkHeader, m_id32Chunk, 4)==0)
        {
            //Generate ID3v2 header cache.
            char rawHeader[10];
            //Generate ID3v2 header structure.
            ID3v2Header header;
            //Read ID3v2 header data.
            musicDataStream.readRawData(rawHeader, 10);
            //Parse the ID3v2 header.
            //and then Check is chunk size smaller than tag size.
            if(!parseID3v2Header(rawHeader, header) ||
                    chunkSize<(header.size+10))
            {
                //If we cannot parse it, skip the whole chunk.
                musicDataStream.skipRawData(chunkSize-10);
                //Continue to next chunk.
                continue;
            }
            //Generate the raw tag data field.
            char *rawTagData=new char[header.size];
            //Read the raw tag data.
            musicDataStream.readRawData(rawTagData, header.size);
            //Get the function set according to the minor version of the header.
            getId3v2FunctionSet(header.major, functionSet);
            //Parse the raw data.
            parseID3v2RawData(rawTagData, header, functionSet, frames);
            //Recover the memory.
            delete[] rawTagData;
            //Set the id32 chunk find flag to true.
            id32Found=true;
        }
        //For all the other chunks.
        else
        {
            //Skip the data.
            musicDataStream.skipRawData(chunkSize);
        }
    }
    //Check if the list data is not empty, first.
    //The data can be overwrite by id32 chunk data.
    if(!listData.isEmpty())
    {
        //Check all the data in the wav item list.
        for(auto i : listData)
        {
            //Get the index of current item.
            int chunkIndex=m_listKeyIndex.value(i.key, -1);
            //Check the validation of chunk index.
            if(chunkIndex==-1)
            {
                //Abandon the current index.
                continue;
            }
            //Set the data.
            analysisItem.detailInfo.textLists[chunkIndex]=
                    QVariant(i.value);
        }
    }
    //Check id32 chunk data then.
    if(!frames.isEmpty())
    {
        //Write the tag to analysis info.
        writeFrameToDetails(frames, functionSet, analysisItem);
    }
    //Mission complete.
    return true;
}
Ejemplo n.º 9
0
std::ifstream QFileToifstream(QFile & file) {
    Q_ASSERT(file.isReadable());
    return std::ifstream(::_fdopen(file.handle(), "r"));
}
Ejemplo n.º 10
0
void cProfileSettings::save ()
{
  cProfileManager *pm = cProfileManager::self();

  QString path = pm->profilePath (d->profileId);
  QDir dir = QDir (path);
  if (!dir.exists()) QDir::root().mkpath (dir.absolutePath());

  dir.remove ("settings.backup");
  
  if (!QFile(path + "/settings.xml").copy (path + "/settings.backup")) {
    kDebug() << "Unable to backup settings.xml." << endl;  // not fatal, may simply not exist
  }
  
  QFile f (path + "/settings.xml");
  if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
    kDebug() << "Unable to open settings.xml for writing." << endl;
    return;  // problem
  }
  // save the profile file
  QXmlStreamWriter *writer = new QXmlStreamWriter (&f);

  writer->setAutoFormatting (true);  // make the generated XML more readable
  writer->writeStartDocument ();

  writer->writeStartElement ("profile");
  writer->writeAttribute ("version", "1.0");

  // boolean values
  map<QString, bool>::iterator itb;
  for (itb = d->boolVals.begin(); itb != d->boolVals.end(); ++itb) {
    writer->writeStartElement ("setting");
    writer->writeAttribute ("type", "bool");
    writer->writeAttribute ("name", itb->first);
    writer->writeAttribute ("value", itb->second ? "true" : "false");
    writer->writeEndElement ();
  }

  // integer values
  map<QString, int>::iterator it;
  for (it = d->intVals.begin(); it != d->intVals.end(); ++it) {
    writer->writeStartElement ("setting");
    writer->writeAttribute ("type", "integer");
    writer->writeAttribute ("name", it->first);
    writer->writeAttribute ("value", QString::number (it->second));
    writer->writeEndElement ();
  }

  // string values
  map<QString, QString>::iterator it2;
  for (it2 = d->strVals.begin(); it2 != d->strVals.end(); ++it2) {
    writer->writeStartElement ("setting");
    writer->writeAttribute ("type", "string");
    writer->writeAttribute ("name", it2->first);
    writer->writeAttribute ("value", it2->second);
    writer->writeEndElement ();
  }

  writer->writeEndElement ();
  writer->writeEndDocument ();

  f.close ();
  delete writer;
}
Ejemplo n.º 11
0
static void dumpOutput(const QByteArray &data, FILE *fh)
{
    QFile file;
    file.open(fh, QIODevice::WriteOnly);
    file.write(data);
}
/*!
    \overload

    Sets the file that the QFileInfo provides information about to \a
    file.

    If \a file includes a relative path, the QFileInfo will also have
    a relative path.

    \sa isRelative()
*/
void QFileInfo::setFile(const QFile &file)
{
    setFile(file.fileName());
}
/*!
    Constructs a new QFileInfo that gives information about file \a
    file.

    If the \a file has a relative path, the QFileInfo will also have a
    relative path.

    \sa isRelative()
*/
QFileInfo::QFileInfo(const QFile &file) : d_ptr(new QFileInfoPrivate(file.fileName()))
{
}
Ejemplo n.º 14
0
qint64 StateImport::parseVICESnapshot(QFile& file, quint8* buffer64k)
{
    struct VICESnapshotHeader header;
    struct VICESnapshoptModule module;
    struct VICESnapshoptC64Mem c64mem;

    static const char VICE_MAGIC[] = "VICE Snapshot File\032";
    static const char VICE_C64MEM[] = "C64MEM";

    auto state = State::getInstance();

    if (!file.isOpen())
        file.open(QIODevice::ReadOnly);

    auto size = file.size();
    if (size < (qint64)sizeof(VICESnapshotHeader))
    {
        state->setErrorMessage(QObject::tr("Error: VICE file too small"));
        return -1;
    }

    file.seek(0);
    size = file.read((char*)&header, sizeof(header));
    if (size != sizeof(header))
    {
        state->setErrorMessage(QObject::tr("Error: VICE header too small"));
        return -1;
    }

    if (memcmp(header.id, VICE_MAGIC, sizeof(header.id)) != 0)
    {
        state->setErrorMessage(QObject::tr("Error: Invalid VICE header Id"));
        return -1;
    }

    int offset = file.pos();
    bool found = false;

    while (1) {
        size = file.read((char*)&module, sizeof(module));
        if (size != sizeof(module))
            break;

        /* Found?  */
        if (memcmp(module.moduleName, VICE_C64MEM, sizeof(VICE_C64MEM)) == 0 &&
                module.major == 0)
        {
            found = true;
            break;
        }
        offset += qFromLittleEndian(module.lenght);
        if (!file.seek(offset))
            break;
    }

    if (found)
    {
        size = file.read((char*)&c64mem, sizeof(c64mem));
        if (size != sizeof(c64mem))
        {
            state->setErrorMessage(QObject::tr("Error: Invalid VICE C64MEM segment"));
            return -1;
        }

        memcpy(buffer64k, c64mem.ram, sizeof(c64mem.ram));
    }
    else
    {
        state->setErrorMessage(QObject::tr("Error: VICE C64MEM segment not found"));
        return -1;
    }

    return 0;
}
Ejemplo n.º 15
0
			int TorrentPlugin::AddJob (Entity e)
			{
				QString suggestedFname;

				if (e.Entity_.canConvert<QUrl> ())
				{
					QUrl resource = e.Entity_.toUrl ();
					if (resource.scheme () == "magnet")
					{
						QString at = XmlSettingsManager::Instance ()->
							property ("AutomaticTags").toString ();
						QStringList tags = e.Additional_ [" Tags"].toStringList ();
						Q_FOREACH (QString tag, Core::Instance ()->GetProxy ()->
								GetTagsManager ()->Split (at))
							tags << Core::Instance ()->GetProxy ()->
								GetTagsManager ()->GetID (tag);

						QList<QPair<QString, QString> > queryItems = resource.queryItems ();
						for (QList<QPair<QString, QString> >::const_iterator i = queryItems.begin (),
								end = queryItems.end (); i != end; ++i)
							if (i->first == "kt")
							{
								QStringList humanReadable = i->second
									.split ('+', QString::SkipEmptyParts);
								Q_FOREACH (QString hr, humanReadable)
									tags += Core::Instance ()->GetProxy ()->
										GetTagsManager ()->GetID (hr);
							}

						return Core::Instance ()->AddMagnet (resource.toString (),
								e.Location_,
								tags,
								e.Parameters_);
					}
					else if (resource.scheme () == "file")
						suggestedFname = resource.toLocalFile ();
				}

				QByteArray entity = e.Entity_.toByteArray ();

				QFile file (suggestedFname);
				if ((!file.exists () ||
						!file.open (QIODevice::ReadOnly)) &&
						Core::Instance ()->IsValidTorrent (entity))
				{
					QTemporaryFile file ("lctemporarybittorrentfile.XXXXXX");
					if (!file.open  ())
						return -1;
					file.write (entity);
					suggestedFname = file.fileName ().toUtf8 ();
					file.setAutoRemove (false);
				}

				AddTorrentDialog_->Reinit ();
				AddTorrentDialog_->SetFilename (suggestedFname);
				if (!e.Location_.isEmpty ())
					AddTorrentDialog_->SetSavePath (e.Location_);

				QString path;
				QStringList tags = e.Additional_ [" Tags"].toStringList ();
				QVector<bool> files;
				QString fname;
				bool tryLive = e.Additional_ ["TryToStreamLive"].toBool ();
				if (e.Parameters_ & FromUserInitiated)
				{
					if (!tags.isEmpty ())
						AddTorrentDialog_->SetTags (tags);

					if (AddTorrentDialog_->exec () == QDialog::Rejected)
						return -1;

					fname = AddTorrentDialog_->GetFilename (),
					path = AddTorrentDialog_->GetSavePath ();
					tryLive = AddTorrentDialog_->GetTryLive ();
					files = AddTorrentDialog_->GetSelectedFiles ();
					tags = AddTorrentDialog_->GetTags ();
					if (AddTorrentDialog_->GetAddType () == Core::Started)
						e.Parameters_ &= ~NoAutostart;
					else
						e.Parameters_ |= NoAutostart;
				}
				else
				{
					fname = suggestedFname;
					path = e.Location_;
					QString at = XmlSettingsManager::Instance ()->
						property ("AutomaticTags").toString ();
					Q_FOREACH (QString tag, Core::Instance ()->GetProxy ()->
							GetTagsManager ()->Split (at))
						tags << Core::Instance ()->GetProxy ()->
							GetTagsManager ()->GetID (tag);
				}
				int result = Core::Instance ()->AddFile (fname,
						path,
						tags,
						tryLive,
						files,
						e.Parameters_);
				setActionsEnabled ();
				file.remove ();
				return result;
			}
Ejemplo n.º 16
0
ClientSocketOpt::ClientSocketOpt(QObject *parent) : QObject(parent)
{
    timerid = -1;
    recvCounts = 0;
    socket = nullptr;
    socketThread = new QThread;
    socketThread->setObjectName("client socket thread");
    this->moveToThread(socketThread);

    connect(socketThread, &QThread::finished, this, [=] () {
        this->deleteLater();
        socketThread->deleteLater();
    });

    connect(this, &ClientSocketOpt::connectHost,
            this, [=] (QString ip, quint16 port) {
        socket = new QTcpSocket(this);
        connect(socket, &QTcpSocket::connected,
                this, [=] () {
            // connected
            emit connected();
        });
        socket->connectToHost(ip, port);
        if (!socket->waitForConnected())
        {
            emit recvInformation(cn("接收终止"));
            emit disconnected();
            socketThread->quit();
            return;
        }


        QFile *file = new QFile(this);
        TcpDataDeal *deal = new TcpDataDeal(this);
        MessageDataDeal *msg = new MessageDataDeal(this);
        connect(deal, &TcpDataDeal::fullFrameData,
                msg, &MessageDataDeal::ParserFrameData);

        connect(msg, &MessageDataDeal::recvMessageData,
                this, [=] (MessageData data) {
            if (data.datatype() != FileSendType &&
                data.datatype() != commonStr)
                return;
            if (data.datatype() == commonStr)
            {
                MessageCharData *charconent = dynamic_cast<MessageCharData*>(data.content());
                if (charconent && charconent->type() == FileInfo)
                {
                    QString strinfo = QString::fromLocal8Bit(charconent->content());
                    emit recvInformation(strinfo);
                }
                return;
            }
            // write file
            FileDataContent *content = dynamic_cast<FileDataContent*>(data.content());
            if (!content)
                return;
            FileDataContent::FileHead *head = content->sendInfo();
            FileDataContent::FileNameHead *namehead = content->fileName();
            emit recvProgress(head->totalProgress >= 100 ? 99 : head->totalProgress, head->currentProgress / 100.0);
            QString filename = namehead->name.replace(namehead->path, savePath + "/");
            QFileInfo info(filename);
            emit recvInformation(cn("正在接收 %1").arg(info.fileName()));
            QDir dir(info.absolutePath());
            if (!dir.exists())
                dir.mkpath(info.absolutePath());
            if (file->fileName() != filename)
            {
                file->close();
                if (info.exists())
                {
                    QString dt = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
                    filename = info.absolutePath() + "/" +
                            info.bundleName() + dt + "." + info.suffix();
                }
                file->setFileName(filename);
            }
            if (!file->isOpen())
            {
                file->open(QIODevice::WriteOnly | QIODevice::Append);
            }
            if (file->isWritable())
            {
                file->write(content->data(), head->fileCurrentSize);
                if (head->currentProgress == 100)
                    file->close();
            }
            if (socketThread->isInterruptionRequested())
            {
                emit recvInformation(cn("接收终止"));
                file->close();
                socket->disconnectFromHost();
                socket->abort();
                socketThread->quit();
            }
            if (head->currentProgress == 100 && head->totalProgress == 100)
            {
                file->close();
                emit recvProgress(100, 1);
                emit recvInformation(cn("接收完成"));
                emit disconnected();
                socket->disconnectFromHost();
                socket->abort();
                socketThread->quit();
            }
        });

        connect(socket, &QTcpSocket::disconnected,
                this, [=] () {
            // disconnected
        });
        connect(socket, static_cast<void(QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error),
                this, [=] () {
            emit recvInformation(cn("接收终止"));
            emit disconnected();
            socketThread->quit();
        });
        connect(this, &ClientSocketOpt::senddata,
                this, [=] (QByteArray ba) {
            if (socket->state() != QAbstractSocket::ConnectedState)
                return;
            socket->write(ba);
            socket->waitForBytesWritten();
            socket->flush();
        });
        connect(socket, &QTcpSocket::readyRead,
                this, [=] () {
            // read data
            QByteArray ba = socket->readAll();
            recvCounts += ba.length();
            NetworkData nd(ba.data(), ba.length());
            deal->slotPosData(nd);
        });

        timerid = startTimer(1000);
    });
    socketThread->start();
}
Ejemplo n.º 17
0
int XmlGspInterface::readFile(const QString &fileName)
{
	QFile* file = new QFile(fileName);
	QFileInfo fi(fileName);
	QString path = (fi.path().length() > 3) ? QString(fi.path() + "/") : fi.path();

	QFileInfo si(QString::fromStdString(_schemaName));
	QString schemaPath(si.absolutePath() + "/");

	if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
	{
		std::cout << "XmlGspInterface::readFile() - Can't open xml-file " <<
		fileName.toStdString() << "." << std::endl;
		delete file;
		return 0;
	}
	if (!checkHash(fileName))
	{
		delete file;
		return 0;
	}

	QDomDocument doc("OGS-PROJECT-DOM");
	doc.setContent(file);
	QDomElement docElement = doc.documentElement(); //OpenGeoSysProject
	if (docElement.nodeName().compare("OpenGeoSysProject"))
	{
		std::cout << "XmlGspInterface::readFile() - Unexpected XML root." << std::endl;
		delete file;
		return 0;
	}

	QDomNodeList fileList = docElement.childNodes();

	for(int i = 0; i < fileList.count(); i++)
	{
		const QString file_node(fileList.at(i).nodeName());
		if (file_node.compare("geo") == 0)
		{
			XmlGmlInterface gml(_project, schemaPath.toStdString() + "OpenGeoSysGLI.xsd");
			const QDomNodeList childList = fileList.at(i).childNodes();
			for(int j = 0; j < childList.count(); j++)
			{
				const QDomNode child_node (childList.at(j));
				if (child_node.nodeName().compare("file") == 0)
				{
					std::cout << "path: " << path.toStdString() << "#" << std::endl;
					std::cout << "file name: " << (child_node.toElement().text()).toStdString() << "#" << std::endl;
					gml.readFile(QString(path + child_node.toElement().text()));
				}
			}
		}
		else if (file_node.compare("stn") == 0)
		{
			XmlStnInterface stn(_project, schemaPath.toStdString() + "OpenGeoSysSTN.xsd");
			const QDomNodeList childList = fileList.at(i).childNodes();
			for(int j = 0; j < childList.count(); j++)
				if (childList.at(j).nodeName().compare("file") == 0)
					stn.readFile(QString(path + childList.at(j).toElement().text()));
		}
		else if (file_node.compare("msh") == 0)
		{
			const std::string msh_name = path.toStdString() +
			                       fileList.at(i).toElement().text().toStdString();
			FileIO::MeshIO meshIO;
			MeshLib::Mesh* msh = meshIO.loadMeshFromFile(msh_name);
			_project->addMesh(msh);
		}
	}

	return 1;
}
Ejemplo n.º 18
0
bool Zip::extract(const QString & filePath, const QString & extDirPath, const QString & singleFileName)
{
    QuaZip zip(filePath);

    if (!zip.open(QuaZip::mdUnzip)) {
        return false;
    }

    zip.setFileNameCodec("IBM866");

    QuaZipFileInfo info;

    QuaZipFile file(&zip);

    QFile out;
    QString name;
    char c;
    for (bool more = zip.goToFirstFile(); more; more = zip.goToNextFile()) {

        if (!zip.getCurrentFileInfo(&info)) {
            return false;
        }

        if (!singleFileName.isEmpty())
            if (!info.name.contains(singleFileName))
                continue;

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

        name = QString("%1/%2").arg(extDirPath).arg(file.getActualFileName());

        if (file.getZipError() != UNZ_OK) {
            return false;
        }

        out.setFileName(name);

        // this will fail if "name" contains subdirectories, but we don't mind that
        out.open(QIODevice::WriteOnly);
        // Slow like hell (on GNU/Linux at least), but it is not my fault.
        // Not ZIP/UNZIP package's fault either.
        // The slowest thing here is out.putChar(c).
        while (file.getChar(&c)) out.putChar(c);

        out.close();

        if (file.getZipError() != UNZ_OK) {
            return false;
        }

        if (!file.atEnd()) {
            return false;
        }

        file.close();

        if (file.getZipError() != UNZ_OK) {
            return false;
        }
    }

    zip.close();

    if (zip.getZipError() != UNZ_OK) {
        return false;
    }

    return true;
}
Ejemplo n.º 19
0
Xslt_Convert::Xslt_Convert( const QString xmlfile , const QString xsltfile ,  QString resulterxml )
 :EndingJob(false),xmlcodec(0),xsltcodec(0)
{
    ////////qDebug() << "### Start Xslt_Convert ...................  ->" << UmanTimeFromUnix(QTime_Null());
    qt_unlink(XMLERROR_FILE);  /* remove debug or error message from last */
    qt_unlink(resulterxml);  /* if exist */
    
    ///////QTimer::singleShot(1000, this, SLOT(CheckError()));
    QFile *xfile = new QFile( xmlfile );
    if (!xfile->exists()) {
    emit ErrorMsg(QString("File %1 not exist!").arg(xmlfile));
    return;
    }
    QFile *sfile = new QFile( xsltfile );
    if (!sfile->exists()) {
    emit ErrorMsg(QString("File %1 not exist!").arg(xsltfile));
    return;
    }
    xmlcodec = GetcodecfromXml(xmlfile);
    xsltcodec = GetcodecfromXml(xsltfile);
    
    ///////////qDebug() << "### xmlfile ..........................  " << xmlfile;
    ////////qDebug() << "### xsltfile ..........................  " << xsltfile;
  
    ////////qDebug() << "### codec ..........................  " << xmlcodec->mibEnum();
    ////////qDebug() << "### codec ..........................  " << xmlcodec->name();
    //////qDebug() << "### codec ..........................  " << xsltcodec->mibEnum();
    ////////qDebug() << "### codec ..........................  " << xsltcodec->name();
  
    const QString maildate = QString("\"%1\"").arg(UmanTimeFromUnix(QTime_Null()));
    const QString unixtime = QString("\"%1\"").arg(QTime_Null());
    
    const char* params[2];  
    params[0] = NULL;
    params[1] = NULL; 
    
    
    /* ######################################### */
         xsltStylesheetPtr cur = NULL;
         xmlDocPtr doc, outputDoc;
         xmlSubstituteEntitiesDefault(1);
         xmlLoadExtDtdDefaultValue = 1;
    /* ######################################### */
        char* xslt_errors;
        xsltSetGenericErrorFunc(&xslt_errors, qt_libxml_error_handler);
        xmlSetGenericErrorFunc(&xslt_errors, qt_libxml_error_handler);
        xsltSetGenericDebugFunc(&xslt_errors, qt_libxml_error_handler);
        QByteArray gocharxslt = QFile::encodeName(xsltfile); 
        cur = xsltParseStylesheetFile( (const xmlChar*)gocharxslt.data() );
        doc = xmlParseFile( QFile::encodeName(xmlfile) );
        outputDoc = xsltApplyStylesheet(cur, doc, params);
        xmlFreeDoc( doc ); /* free ram from xml! */
        doc = outputDoc; /* swap input and output */
        FILE* outfile = fopen( QFile::encodeName( resulterxml ), "w" );
        xsltSaveResultToFile( outfile, doc, cur );
        fclose( outfile );
        xsltFreeStylesheet(cur);
        xmlFreeDoc( outputDoc );
        xsltCleanupGlobals();
        xmlCleanupParser();
       //////// qDebug() << "### resulterxml ..........................  " << resulterxml;
       //////// qDebug() << "### XMLERROR_FILE ..........................  " << XMLERROR_FILE;
        Rstream = StreamFromFile(resulterxml);
        debug_msg = ReadFileUtf8Xml(XMLERROR_FILE);
        /////////qDebug() << "### resulterxml ..........................  " << debug_msg;
        qt_unlink(XMLERROR_FILE); 
        EndingJob = true;
        emit DebugMsg(debug_msg);

}
Ejemplo n.º 20
0
bool tiBackupService::install(const QString &path)
{
    qDebug() << "tiBackupService::install()";

    QFile *tiServicePath = new QFile(path);
    if(!tiServicePath->open(QIODevice::WriteOnly | QIODevice::Text))
        return false;
    QTextStream out(tiServicePath);

    QFile *tiServiceTemplate = new QFile(":/init/tibackup");
    if(!tiServiceTemplate->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        tiServicePath->close();
        tiServicePath->deleteLater();
        return false;
    }
    QTextStream in(tiServiceTemplate);

    out << in.readAll();
    out.flush();

    tiServicePath->setPermissions(QFile::ReadOwner | QFile::ExeOwner | QFile::ReadGroup | QFile::ExeGroup | QFile::ReadOther);
    tiServicePath->close();
    tiServiceTemplate->close();

    tiServicePath->deleteLater();
    tiServiceTemplate->deleteLater();

    emit serviceInstalled();
    return true;
}
Ejemplo n.º 21
0
void atlasMap::sHandleAtlas()
{
  _map->clear();

  if (_atlas->text().isEmpty())
    return;

  if (DEBUG)
    qDebug("atlasMap::sHandleAtlas() entered with %s and %s",
           qPrintable(_atlas->text()), qPrintable(_defaultDir));

  if (! _defaultDir.isEmpty() && _atlas->text().startsWith(_defaultDir))
    _atlas->setText(_atlas->text().remove(0, _defaultDir.length() + 1));

  QFile atlasfile;
  if (QFile::exists(_atlas->text()))
    atlasfile.setFileName(_atlas->text());
  else if (QFile::exists(_defaultDir + QDir::separator() + _atlas->text()))
    atlasfile.setFileName(_defaultDir + QDir::separator() + _atlas->text());
  else
  {
    QMessageBox::warning(this, tr("Could not find Atlas"),
                         tr("<p>Could not find the Atlas file to open to look "
                            "for CSV import Maps."));
    return;
  }

  if (! atlasfile.open(QIODevice::ReadOnly))
  {
    QMessageBox::critical(this, tr("Could not open Atlas"),
                          tr("<p>Could not open the Atlas file %1 (error %2).")
                          .arg(atlasfile.fileName(), atlasfile.errorString()));
    return;
  }

  QXmlQuery mapq;
  mapq.setMessageHandler(_msghandler);

  if (! mapq.setFocus(&atlasfile))
  {
    QMessageBox::critical(this, tr("No Focus"),
                          tr("<p>Could not set focus on the Atlas %1")
                          .arg(atlasfile.fileName()));
    return;
  }

  // string() at the end tells the query to generate a sequence of values
  mapq.setQuery("/CSVAtlas/CSVMap/Name/text()/string()");
  if (! mapq.isValid())
  {
    QMessageBox::critical(this, tr("Invalid Query"),
                          tr("<p>The query is not valid for some reason"));
    return;
  }

  QStringList maplist;
  if (! mapq.evaluateTo(&maplist))
  {
    QMessageBox::warning(this, tr("No Maps"),
                         tr("<p>Could not find any Maps in the Atlas %1")
                         .arg(atlasfile.fileName()));
    return;
  }
  else
    for (int i = 0; i < maplist.size(); i++)
      _map->append(i, maplist.at(i));
}
Ejemplo n.º 22
0
bool Map::loadMap()
{
	QFile file;
	for(int i = 0; i < mapImform.size(); i++)
	{
		if (!isMap(mapImform[i].filePath)) {
			return false;
		}

		file.setFileName(mapImform[i].filePath);
		if(!file.open(QIODevice::ReadOnly))
		{
			QMessageBox::warning(NULL,tr("Map editor"),
					     tr("failed to read file %1:\n%2")
					     .arg(file.fileName())
					     .arg(file.errorString()));
			return false;
		}

		//添加新层
		DoublemapBlockList newFloor;
		map.append(newFloor);


		QDataStream in(&file);
		in.setVersion(QDataStream::Qt_4_8);
		{
			quint32 magic;		//magic is garbage
			in >> magic;
		}
		quint32 totalColumn = 0;
		int columnIndex = 0;
		int rowIndex = 0;
		mapBlcok block;
		{
			quint32 tmp;
			in >> tmp;				//抛弃垃圾值
		}
		in >> totalColumn;
		//Get spawn point
		//		{
		//			quint32 spawn_row,spawn_column;
		//			in >> spawn_row >> spawn_column;
		//			spawnPoint.append(QPoint(spawn_column, spawn_row));

		//		}
		{
			QList<mapBlcok> newRow;
			map[i].append(newRow);
		}
		quint32 tmp;
		while(!in.atEnd())
		{
			if(columnIndex == (int)totalColumn)			//检查是否要换行
			{
				QList<mapBlcok> newRow;
				map[i].append(newRow);
				rowIndex++;
				columnIndex = 0;
			}
			in >> tmp >> tmp;			//抛弃垃圾值
			in >> block.id >> block.status;
			map[i][rowIndex].append(block);
			columnIndex++;
		}
		file.close();
	}
	return true;
}
void DataJson::createJson()
{
    QJsonObject ambitCat, ambitEsp, ambitFran;
    QJsonObject ejeCat, ejeEsp,ejeFran;
    QJsonArray ejecutablesCat,ejecutablesEsp,ejecutablesFran;

    //Crear QJsonObject ambitCat
    ambitCat.insert("Nombreambito",QJsonValue(QString("Catalunya lidar 2 metres")));
    ambitCat.insert("Path",QJsonValue(QString(getPathImageMetCat())));
    ambitCat.insert("TamanyoPixel",QJsonValue(int(1)));
    ambitCat.insert("Utm",QJsonValue(int(31)));
    ejeCat.insert("Nombre",QJsonValue(QString("exeExtraction")));
    ejeCat.insert("Path",QJsonValue(QString(getExeExtraction())));
    ejecutablesCat.append(ejeCat);
    ejeCat.insert("Nombre",QJsonValue(QString("exeResize")));
    ejeCat.insert("Path",QJsonValue(QString(getExeResize())));
    ejecutablesCat.append(ejeCat);
    ejeCat.insert("Nombre",QJsonValue(QString("exeFootPrintMask")));
    ejeCat.insert("Path",QJsonValue(QString(getExeFootPrintMask())));
    ejecutablesCat.append(ejeCat);
    ejeCat.insert("Nombre",QJsonValue(QString("exeSubScene")));
    ejeCat.insert("Path",QJsonValue(QString(getExeSubScene())));
    ejecutablesCat.append(ejeCat);
    ejeCat.insert("Nombre",QJsonValue(QString("exeGeoTransform")));
    ejeCat.insert("Path",QJsonValue(QString(getExeImaOpeGeo())));
    ejecutablesCat.append(ejeCat);
    ambitCat.insert("Ejecutables",ejecutablesCat);

    //Crear QJsonObject ambitEsp
    ambitEsp.insert("Nombreambito",QJsonValue(QString("Espanya 5 metres")));
    ambitEsp.insert("Path",QJsonValue(QString(getPathImageMetEsp())));
    ambitEsp.insert("TamanyoPixel",QJsonValue(int(5)));
    ambitEsp.insert("Utm",QJsonValue(int(30)));
    ejeEsp.insert("Nombre",QJsonValue(QString("exeFootPrintMask")));
    ejeEsp.insert("Path",QJsonValue(QString(getExeFootPrintMask())));
    ejecutablesEsp.append(ejeEsp);
    ejeEsp.insert("Nombre",QJsonValue(QString("exeResize")));
    ejeEsp.insert("Path",QJsonValue(QString(getExeResize())));
    ejecutablesEsp.append(ejeEsp);
    ejeEsp.insert("Nombre",QJsonValue(QString("exeSubScene")));
    ejeEsp.insert("Path",QJsonValue(QString(getExeSubScene())));
    ejecutablesEsp.append(ejeEsp);
    ejeEsp.insert("Nombre",QJsonValue(QString("exeGeoTransform")));
    ejeEsp.insert("Path",QJsonValue(QString(getExeImaOpeGeo())));
    ejecutablesEsp.append(ejeEsp);
    ambitEsp.insert("Ejecutables",ejecutablesEsp);

    //Crear QJsonObject ambitFran
    ambitFran.insert("Nombreambito",QJsonValue(QString("Francia Farmstar")));
    ambitFran.insert("Path",QJsonValue(QString(getPathImageMetFran())));
    ambitFran.insert("TamanyoPixel",QJsonValue(int(10)));
    ambitFran.insert("Utm",QJsonValue(int(-2)));
    ejeFran.insert("Nombre",QJsonValue(QString("exeFootPrintMask")));
    ejeFran.insert("Path",QJsonValue(QString(getExeFootPrintMask())));
    ejecutablesFran.append(ejeFran);
    ejeFran.insert("Nombre",QJsonValue(QString("exeResize")));
    ejeFran.insert("Path",QJsonValue(QString(getExeResize())));
    ejecutablesFran.append(ejeFran);
    ejeFran.insert("Nombre",QJsonValue(QString("exeSubScene")));
    ejeFran.insert("Path",QJsonValue(QString(getExeSubScene())));
    ejecutablesFran.append(ejeFran);
    ejeFran.insert("Nombre",QJsonValue(QString("exeResize")));
    ejeFran.insert("Path",QJsonValue(QString(getExeResize())));
    ejecutablesFran.append(ejeFran);
    ambitFran.insert("Ejecutables",ejecutablesFran);

    QJsonArray array;
    array.prepend((ambitCat));
    array.prepend((ambitFran));
    array.prepend((ambitEsp));
    QJsonDocument documento;
    documento.setArray(array);
    QFile documentoTexto;
    QTextStream value;
    QString PathFileJsonDefecto=qApp->applicationDirPath()+"/dataAplicationToolsPcot.txt";
    documentoTexto.setFileName(PathFileJsonDefecto);
    documentoTexto.open(QFile::WriteOnly | QFile::Text);
    value.setDevice(&documentoTexto);
    value << documento.toJson();
}
Ejemplo n.º 24
0
frmServerManager::frmServerManager(QString languagePath, bool designedMode, QWidget *parent) :
    QMainWindow(parent), languagePath(languagePath), designedMode(designedMode), ui(new Ui::frmServerManager)
{
    ui->setupUi(this);
    iconWTDefined = false;
    smgr = new ServerManager(this);
    standardIcon = QIcon(ProductImg);
    QIcon windowIcon = QIcon(ProductIcon);
    windowIcon.addPixmap(QPixmap(ProductImg));
    windowIcon.addPixmap(QPixmap(ProductPixmap));
    this->setWindowTitle(ProductName);
    this->setWindowIcon(windowIcon);

    // Change Window Size
#ifdef SM_ANDROID
    this->setMinimumSize(QSize(0, 0));
    this->setMaximumSize(QSize(16777215, 16777215));
#endif

    // Change Page IDs
#ifdef SM_ANDROID
    pageLogin = 3;
    pageInterface = 4;
    pagePleaseWait = 5;
#else
    pageLogin = 0;
    pageInterface = 1;
    pagePleaseWait = 2;
#endif

    // Change Text and Version things
    ui->labSMVersion->setText(ui->labSMVersion->text().arg(ProductVersion));

    // Change Visibles
    ui->swSM->setCurrentIndex(pageLogin);
    ui->labTop->setVisible(false);
    ui->statusBar->setVisible(false);
    ui->labDesignedLoginDes->setVisible(false);
    setAdminMode(false);

    // Add widgets to status bar
    labStats = new KPTLabel();
    ui->statusBar->addWidget(labStats,1);
    ui->statusBar->layout()->setContentsMargins(2,0,6,0);
    labStats->setText(tr("Welcome to Syping's %1").arg(ProductName));

    // SM Style designedMode
    QFile *SLStyleFile = new QFile(":/smstyle/pLogin.qss");
    if (SLStyleFile->open(QFile::ReadOnly))
    {
        SLStyleSheet = QString::fromUtf8(SLStyleFile->readAll());
        SLStyleFile->close();
    }
    QFile *SMStyleFile = new QFile(":/smstyle/pServerManager.qss");
    if (SMStyleFile->open(QFile::ReadOnly))
    {
        SMStyleSheet = QString::fromUtf8(SMStyleFile->readAll());
        SMStyleFile->close();
    }
    if (designedMode)
    {
        ui->pLogin->setStyleSheet(SLStyleSheet);
        ui->pServerManager->setStyleSheet(SMStyleSheet);
        ui->txtHostnameDesigned->setFrame(false);
        ui->txtPasswordDesigned->setFrame(false);
    }

    // Change Designed Mode Font size
    QFont designedFont;
    designedFont.setPixelSize(15);
    ui->txtHostnameDesigned->setFont(designedFont);
    ui->txtPasswordDesigned->setFont(designedFont);
    ui->cmdDesignedLogin->setFont(designedFont);
    ui->labPleaseWait->setFont(designedFont);
    ui->labDesignedLoginDes->setFont(designedFont);
    ui->cbStayLoggedInDesigned->setFont(designedFont);
    ui->cbUseEncryptedConnectionDesigned->setFont(designedFont);
    mouseOverLogin = false;
#ifdef DISABLE_SSL
    ui->cbUseEncryptedConnectionDesigned->setVisible(false);
#endif

    // Change Designed Mode Style
    SMStyleTweaks *SMStyle = new SMStyleTweaks;
    ui->lwServerAndroid->setStyle(SMStyle);
    if (designedMode)
    {
        ui->cmdDesignedLogin->setStyle(SMStyle);
        ui->pServerManager->setStyle(SMStyle);
    }

    // Change Active ListWidget
#ifdef SM_ANDROID
    activeLW = ui->lwServerAndroid;
#else
    activeLW = ui->lwServer;
#endif

    // Change Icon size
#ifdef SM_ANDROID
    izSquare = 48;
    activeLW->setIconSize(QSize(izSquare, izSquare));
#else
    izSquare = 24;
    activeLW->setIconSize(QSize(izSquare, izSquare));
#endif

    // Check for Autologin
    if (smgr->autologinEnabled())
    {
        QTimer::singleShot(10,this,SLOT(connectToServer()));
    }

}
Ejemplo n.º 25
0
void WriteCPlusPlusClass::writeInclude(QFile &file, JsonClass newClass)
{
    //QFile file("/tmp/test.h");

    file.write("#include\"../../JsonClassInterface.h\"");
    file.write("\n");

    for (int i = 0; i < newClass.fields.size(); i++) {
        if (!defaultType.contains(newClass.fields.at(i).type)) {
            if (newClass.fields.at(i).type == "string") {
                file.write(QString("#include<QString>\n").toStdString().c_str());
                // write QString
            } else {
                // write name type
            }
        }
    }
    file.write("\n");
    file.write(QString("class " + newClass.name +":public JsonClassInterface {\n").toStdString().c_str());
    file.write("private:\n");
    for (int i = 0; i < newClass.fields.size(); i++) {
        if (newClass.fields.at(i).type == "integer") {
           file.write(QString("\tint " + newClass.fields.at(i).name + ";\n").toStdString().c_str());
        }
        else if (newClass.fields.at(i).type == "string") {
            file.write(QString("\tQString " + newClass.fields.at(i).name + ";\n").toStdString().c_str());
            // write QString
        } else {
            file.write(QString("\t" + newClass.fields.at(i).type + " " + newClass.fields.at(i).name + ";\n").toStdString().c_str());
        }

    }

    // write methods

    file.write("\npublic:\n");

    file.write(QString(QString("\t") + newClass.name +"();\n").toStdString().c_str());

    for (int i = 0; i < newClass.fields.size(); i++) {


        if (newClass.fields.at(i).type == "integer") {

           file.write(QString("\tint " + createGet(newClass.fields.at(i)) + ";\n").toStdString().c_str());
        }
        else if (newClass.fields.at(i).type == "string") {
            file.write(QString("\tQString " + createGet(newClass.fields.at(i)) + ";\n").toStdString().c_str());
            // write QString
        } else {
            file.write(QString("\t" + newClass.fields.at(i).type + " " + createGet(newClass.fields.at(i)) + ";\n").toStdString().c_str());
        }

    }

    for (int i = 0; i < newClass.fields.size(); i++) {


        if (newClass.fields.at(i).type == "integer") {

           file.write(QString("\t" + createSet(newClass.fields.at(i), "int") + ";\n").toStdString().c_str());
        }
        else if (newClass.fields.at(i).type == "string") {
            file.write(QString("\t" + createSet(newClass.fields.at(i), "QString") + ";\n").toStdString().c_str());
            // write QString
        } else {
            file.write(QString("\t" + createSet(newClass.fields.at(i), newClass.fields.at(i).type) + ";\n").toStdString().c_str());
        }

    }

    file.write(QString("\tvoid read(const QJsonObject &json);\n").toStdString().c_str());
    file.write(QString("\tvoid write(QJsonObject &json) const;\n").toStdString().c_str());
    file.write("};\n");
}
Ejemplo n.º 26
0
void Config::init(QString file_name) {
    this->file_name = file_name;

	QFile file;
    file.setFileName(this->file_name);
	file.open(QIODevice::ReadOnly | QIODevice::Text);
	
    QByteArray data = file.readAll();
	
	file.close();

    QJsonParseError error;

    json = QJsonDocument::fromJson(data, &error);

    if (!json.isObject()) {
        return;
    }

    QJsonObject obj = json.object();

    QStringList keys = obj.keys();

    if (!keys.contains("config") || !obj["config"].isObject()) {
        return;
    }

    obj = obj["config"].toObject();

    keys = obj.keys(); //movList idxs

    for (int i = 0; i < keys.size(); ++i) {
        QString key = keys.at(i);

        if (!obj[key].isObject()) {
            continue;
        }

        QJsonObject coll_item = obj[key].toObject();
        QStringList coll_keys = coll_item.keys();

        if (coll_keys.contains("text") && coll_item["text"].isString()) {
            this->text[key] = coll_item["text"].toString();
        }

        if (coll_keys.contains("video") && coll_item["video"].isArray()) {
            QJsonArray videos = coll_item["video"].toArray();
            QStringList v_list;

            for (int j = 0; j < videos.size(); ++j) {
                if (!videos.at(j).isString()) {
                    continue;
                }

                v_list.append(videos.at(j).toString());
            }

            this->video[key] = v_list;
        }
    }

    return;
}
Ejemplo n.º 27
0
/*!
    If the currently assigned device is a QFile, or if setFileName()
    has been called, this function returns the name of the file
    QImageReader reads from. Otherwise (i.e., if no device has been
    assigned or the device is not a QFile), an empty QString is
    returned.

    \sa setFileName(), setDevice()
*/
QString QImageReader::fileName() const
{
    QFile *file = qobject_cast<QFile *>(d->device);
    return file ? file->fileName() : QString();
}
Ejemplo n.º 28
0
int main( int argc, char **argv )
{
    if ( argc < 2 ) {
	qWarning( "Usage:\n\t%s [--images] files", argv[0] );
	return 1;
    }

    QFile output;
    bool  images = FALSE;
    output.open( IO_WriteOnly, stdout );
    QTextStream out( &output );

    EmbedImageList list_image;
    QList<Embed> list;
    list.setAutoDelete( TRUE );
    list_image.setAutoDelete( TRUE );

  // Embed data for all input files

    out << "/* Generated by qembed */\n";
    srand( time(0) );
    long l = rand();
    out << "#ifndef _" << l << endl;
    out << "#define _" << l << endl;

    for ( int i=1; i<argc; i++ ) {
	QString arg = argv[i];
	if ( arg == "--images" ) {
	    if ( !images ) {
		out << "#include <qimage.h>\n";
		out << "#include <stdlib.h>\n";
		images = TRUE;
	    }
	} else {
	    QFile f( argv[i] );
	    if ( !f.open(IO_ReadOnly) ) {
		qWarning( "Cannot open file %s, ignoring it", argv[i] );
		continue;
	    }
	    QByteArray a( f.size() );
	    if ( f.readBlock(a.data(), f.size()) != (int)f.size() ) {
		qWarning( "Cannot read file %s, ignoring it", argv[i] );
		f.close();
		continue;
	    }
	    if ( images ) {
		QImage img;
		if ( !img.loadFromData(a) ) {
		    qWarning( "Cannot read image from file %s, ignoring it", argv[i] );
		    f.close();
		    continue;
		}
		EmbedImage *e = new EmbedImage;
		e->width = img.width();
		e->height = img.height();
		e->depth = img.depth();
		e->numColors = img.numColors();
		e->colorTable = new QRgb[e->numColors];
		e->alpha = img.hasAlphaBuffer();
		memcpy(e->colorTable, img.colorTable(), e->numColors*sizeof(QRgb));
		QFileInfo fi(argv[i]);
		e->name = fi.baseName();
		e->cname = convertFileNameToCIdentifier( e->name.latin1() );
		list_image.append( e );
		QString s;
		if ( e->depth == 32 ) {
		    out << s.sprintf( "static const QRgb %s_data[] = {",
				   (const char *)e->cname );
		    embedData( (QRgb*)img.bits(), e->width*e->height, &output );
		} else {
		    if ( e->depth == 1 )
			img = img.convertBitOrder(QImage::BigEndian);
		    out << s.sprintf( "static const unsigned char %s_data[] = {",
				   (const char *)e->cname );
		    embedData( img.bits(), img.numBytes(), &output );
		}
		out << "\n};\n\n";
		if ( e->numColors ) {
		    out << s.sprintf( "static const QRgb %s_ctable[] = {",
				   (const char *)e->cname );
		    embedData( e->colorTable, e->numColors, &output );
		    out << "\n};\n\n";
		}
	    } else {
		Embed *e = new Embed;
		e->size = f.size();
		e->name = argv[i];
		e->cname = convertFileNameToCIdentifier( argv[i] );
		list.append( e );
		QString s;
		out << s.sprintf( "static const unsigned int  %s_len = %d;\n",
			       (const char *)e->cname, e->size );
		out << s.sprintf( "static const unsigned char %s_data[] = {",
			       (const char *)e->cname );
		embedData( a, &output );
		out << "\n};\n\n";
	    }

	    f.close();
	}
    }

  // Generate summery

    if ( list.count() > 0 ) {
	out << "#include <qcstring.h>\n";
	if ( !images )
	    out << "#include <qdict.h>\n";

	out << "static struct Embed {\n"
	       "    unsigned int         size;\n"
	       "    const unsigned char *data;\n"
	       "    const char          *name;\n"
	       "} embed_vec[] = {\n";
	Embed *e = list.first();
	while ( e ) {
	    out << "    { " << e->size << ", " << e->cname << "_data, "
		 << "\"" << e->name << "\" },\n";
	    e = list.next();
	}
	out << "    { 0, 0, 0 }\n};\n";

	out << "\n"
	    "inline const QByteArray& qembed_findData(const char* name)\n"
	    "{\n"
	    "    static QDict<QByteArray> dict;\n"
	    "    QByteArray* ba = dict.find(name);\n"
	    "    if ( !ba ) {\n"
	    "        for (int i=0; embed_vec[i].data; i++) {\n"
	    "    	if ( 0==strcmp(embed_vec[i].name, name) ) {\n"
	    "    	    ba = new QByteArray;\n"
	    "    	    ba->setRawData( (char*)embed_vec[i].data,\n"
	    "    			    embed_vec[i].size );\n"
	    "    	    break;\n"
	    "    	}\n"
	    "        }\n"
	    "        if ( !ba ) {\n"
	    "            static QByteArray dummy;\n"
	    "            return dummy;\n"
	    "        }\n"
	    "    }\n"
	    "    return *ba;\n"
	    "}\n\n";
    }

    if ( list_image.count() > 0 ) {
	out << "static struct EmbedImage {\n"
	       "    int width, height, depth;\n"
	       "    const unsigned char *data;\n"
	       "    int numColors;\n"
	       "    const QRgb *colorTable;\n"
	       "    bool alpha;\n"
	       "    const char *name;\n"
	       "} embed_image_vec[] = {\n";
	list_image.sort();
	EmbedImage *e = list_image.first();
	while ( e ) {
	    out << "    { "
		<< e->width << ", "
		<< e->height << ", "
		<< e->depth << ", "
		<< "(const unsigned char*)" << e->cname << "_data, "
		<< e->numColors << ", ";
	    if ( e->numColors )
		out << e->cname << "_ctable, ";
	    else
		out << "0, ";
	    if ( e->alpha )
		out << "TRUE, ";
	    else
		out << "FALSE, ";
	    out << "\"" << e->name << "\" },\n";
	    e = list_image.next();
	}
	out << "};\n";

	out << "\n"
	    "static int cmpEmbedImage(const void *a, const void *b)\n"
	    "{\n"
	    "    const EmbedImage* ea = (const EmbedImage*)a;\n"
	    "    const EmbedImage* eb = (const EmbedImage*)b;\n"
	    "    return strcmp(ea->name,eb->name);\n"
	    "}\n"
	    "inline const QImage& qembed_findImage(const char* name)\n"
	    "{\n"
	    "    EmbedImage key; key.name = name;\n"
	    "    EmbedImage* r = (EmbedImage*)bsearch( &key, embed_image_vec,\n"
	    "        sizeof(embed_image_vec)/sizeof(EmbedImage), sizeof(EmbedImage), cmpEmbedImage );\n"
	    "    QImage* img;\n"
	    "    if ( r ) {\n"
	    "        img = new QImage((uchar*)r->data,\n"
	    "                            r->width,\n"
	    "                            r->height,\n"
	    "                            r->depth,\n"
	    "                            (QRgb*)r->colorTable,\n"
	    "                            r->numColors,\n"
	    "                            QImage::BigEndian\n"
	    "                    );\n"
	    "        if ( r->alpha )\n"
	    "            img->setAlphaBuffer(TRUE);\n"
	    "    } else {\n"
	    "        static QImage dummy;\n"
	    "        img = &dummy;\n"
	    "    }\n"
	    "    return *img;\n"
	    "}\n\n";
    }

    out << "#endif" << endl;

    return 0;
}
Ejemplo n.º 29
0
int ThemeLoader::loadLayout(const QString& themeName, const QString& path)
{

//     const KArchiveDirectory * KArchive::directory	(		)	 const


    QFile themeFile;



    QDomDocument doc;

    themeFile.setFileName(QString(path + "%1.xml").arg(themeName));

    if (!themeFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::information(0, "Error", QString("Unable to open theme xml file: %1").arg(themeFile.fileName()));
        return -1;
    }
    if (!doc.setContent(&themeFile)) {
        QMessageBox::information(0, "Error", QString("Unable to parse theme xml file: %1").arg(themeFile.fileName()));
        return -2;
    }
    themeFile.close();


    QDomElement docElem = doc.documentElement();

    QDomNodeList wList = docElem.elementsByTagName("buttonWidth");
    QDomNode wNode = wList.at(0);

    //read default button width
    defaultWidth = wNode.attributes().namedItem("width").toAttr().value().toInt();

    QDomNodeList nList = (wNode.toElement()).elementsByTagName("item");
    for (int a=0; a<nList.count(); a++) {
        QDomNode node = nList.at(a);
        int width = node.attributes().namedItem("width").toAttr().value().toInt();
        QString hintName = node.attributes().namedItem("name").toAttr().value();
        widthMap.insert(hintName, width);
        //cout  << "widths[" << qPrintable(hintName) << "]=>"<< width << endl;
    }

    wList = docElem.elementsByTagName("buttonHeight");
    wNode = wList.at(0);
    nList = (wNode.toElement()).elementsByTagName("item");
    for (int a=0; a<nList.count(); a++) {
        QDomNode node = nList.at(a);
        int height = node.attributes().namedItem("height").toAttr().value().toInt();
        QString hintName = node.attributes().namedItem("name").toAttr().value();
        heightMap.insert(hintName, height);
        //cout  << "heights[" << qPrintable(hintName) << "]=>"<< height << endl;
    }


    wList = docElem.elementsByTagName("spacingHints");
    wNode = wList.at(0);
    nList = (wNode.toElement()).elementsByTagName("item");
    for (int a=0; a<nList.count(); a++) {
        QDomNode node = nList.at(a);
        int width = node.attributes().namedItem("width").toAttr().value().toInt();
        QString hintName = node.attributes().namedItem("name").toAttr().value();
        spacingMap.insert(hintName, width);
        //cout  << "spacing[" << qPrintable(hintName) << "]=>"<< width << endl;
    }


    wList = docElem.elementsByTagName("part");
    wNode = wList.at(0);

    //insert main part to widget
    QString partName = wNode.attributes().namedItem("name").toAttr().value();

    MainWidget *part = new MainWidget((QWidget*)parent());
    part->setProperty("part", "main");


    loadKeys(part, wNode);

    wList = wNode.childNodes();

    for (int a=0; a<wList.size(); a++) {

        QDomNode wNode = wList.at(a);
        if (wNode.toElement().tagName() == "extension") {
            MainWidget *widget1 = new MainWidget((QWidget*)parent());
            widget1->setProperty("part", "extension");
            loadKeys(widget1, wNode);
            break;
        }
    }



    return 0;
}
Ejemplo n.º 30
0
/** \fn copy(QFile&,QFile&,uint)
 *  \brief Copies src file to dst file.
 *
 *   If the dst file is open, it must be open for writing.
 *   If the src file is open, if must be open for reading.
 *
 *   The files will be in the same open or close state after
 *   this function runs as they were prior to this function being called.
 *
 *   This function does not care if the files are actual files.
 *   For compatibility with pipes and socket streams the file location
 *   will not be reset to 0 at the end of this function. If the function
 *   is successful the file pointers will be at the end of the copied
 *   data.
 *
 *  \param dst Destination QFile
 *  \param src Source QFile
 *  \param block_size Optional block size in bytes, must be at least 1024,
 *                    otherwise the default of 16 KB will be used.
 *  \return bytes copied on success, -1 on failure.
 */
long long copy(QFile &dst, QFile &src, uint block_size)
{
    uint buflen = (block_size < 1024) ? (16 * 1024) : block_size;
    char *buf = new char[buflen];
    bool odst = false, osrc = false;

    if (!buf)
        return -1LL;

    if (!dst.isWritable() && !dst.isOpen())
        odst = dst.open(QIODevice::Unbuffered|QIODevice::WriteOnly|QIODevice::Truncate);

    if (!src.isReadable() && !src.isOpen())
        osrc = src.open(QIODevice::Unbuffered|QIODevice::ReadOnly);

    bool ok = dst.isWritable() && src.isReadable();
    long long total_bytes = 0LL;
    while (ok)
    {
        long long rlen, wlen, off = 0;
        rlen = src.read(buf, buflen);
        if (rlen<0)
        {
            VERBOSE(VB_IMPORTANT, "util.cpp:copy: read error");
            ok = false;
            break;
        }
        if (rlen==0)
            break;

        total_bytes += (long long) rlen;

        while ((rlen-off>0) && ok)
        {
            wlen = dst.write(buf + off, rlen - off);
            if (wlen>=0)
                off+= wlen;
            if (wlen<0)
            {
                VERBOSE(VB_IMPORTANT, "util.cpp:copy: write error");
                ok = false;
            }
        }
    }
    delete[] buf;

    if (odst)
        dst.close();

    if (osrc)
        src.close();

    return (ok) ? total_bytes : -1LL;
}