Example #1
0
static QList<ProjectExplorer::Abi> guessGccAbi(const QString &m)
{
    QList<ProjectExplorer::Abi> abiList;

    QString machine = m.toLower();
    if (machine.isEmpty())
        return abiList;

    QStringList parts = machine.split(QRegExp(QLatin1String("[ /-]")));

    ProjectExplorer::Abi::Architecture arch = ProjectExplorer::Abi::UnknownArchitecture;
    ProjectExplorer::Abi::OS os = ProjectExplorer::Abi::UnknownOS;
    ProjectExplorer::Abi::OSFlavor flavor = ProjectExplorer::Abi::UnknownFlavor;
    ProjectExplorer::Abi::BinaryFormat format = ProjectExplorer::Abi::UnknownFormat;
    int width = 0;
    int unknownCount = 0;

    foreach (const QString &p, parts) {
        if (p == QLatin1String("unknown") || p == QLatin1String("pc") || p == QLatin1String("none")
                || p == QLatin1String("gnu") || p == QLatin1String("uclibc")
                || p == QLatin1String("86_64") || p == QLatin1String("redhat") || p == QLatin1String("gnueabi")) {
            continue;
        } else if (p == QLatin1String("i386") || p == QLatin1String("i486") || p == QLatin1String("i586")
                   || p == QLatin1String("i686") || p == QLatin1String("x86")) {
            arch = ProjectExplorer::Abi::X86Architecture;
            width = 32;
        } else if (p.startsWith(QLatin1String("arm"))) {
            arch = ProjectExplorer::Abi::ArmArchitecture;
            width = 32;
        } else if (p == QLatin1String("mipsel")) {
            arch = ProjectExplorer::Abi::MipsArchitecture;
            width = 32;
        } else if (p == QLatin1String("x86_64") || p == QLatin1String("amd64")) {
            arch = ProjectExplorer::Abi::X86Architecture;
            width = 64;
        } else if (p == QLatin1String("powerpc")) {
            arch = ProjectExplorer::Abi::PowerPCArchitecture;
        } else if (p == QLatin1String("w64")) {
            width = 64;
        } else if (p == QLatin1String("linux") || p == QLatin1String("linux6e")) {
            os = ProjectExplorer::Abi::LinuxOS;
            if (flavor == Abi::UnknownFlavor)
                flavor = ProjectExplorer::Abi::GenericLinuxFlavor;
            format = ProjectExplorer::Abi::ElfFormat;
        } else if (p.startsWith(QLatin1String("freebsd"))) {
            os = ProjectExplorer::Abi::BsdOS;
            if (flavor == Abi::UnknownFlavor)
                flavor = ProjectExplorer::Abi::FreeBsdFlavor;
            format = ProjectExplorer::Abi::ElfFormat;
        } else if (p == QLatin1String("meego")) {
            os = ProjectExplorer::Abi::LinuxOS;
            flavor = ProjectExplorer::Abi::MeegoLinuxFlavor;
            format = ProjectExplorer::Abi::ElfFormat;
        } else if (p == QLatin1String("symbianelf")) {
            os = ProjectExplorer::Abi::SymbianOS;
            flavor = ProjectExplorer::Abi::SymbianDeviceFlavor;
            format = ProjectExplorer::Abi::ElfFormat;
            width = 32;
        } else if (p == QLatin1String("mingw32") || p == QLatin1String("win32") || p == QLatin1String("mingw32msvc")) {
            arch = ProjectExplorer::Abi::X86Architecture;
            os = ProjectExplorer::Abi::WindowsOS;
            flavor = ProjectExplorer::Abi::WindowsMSysFlavor;
            format = ProjectExplorer::Abi::PEFormat;
            if (width == 0)
                width = 32;
        } else if (p == QLatin1String("apple")) {
            os = ProjectExplorer::Abi::MacOS;
            flavor = ProjectExplorer::Abi::GenericMacFlavor;
            format = ProjectExplorer::Abi::MachOFormat;
        } else if (p == QLatin1String("darwin10")) {
            width = 64;
        } else if (p == QLatin1String("darwin9")) {
            width = 32;
        } else if (p == QLatin1String("gnueabi")) {
            format = ProjectExplorer::Abi::ElfFormat;
        } else {
            ++unknownCount;
        }
    }

    if (unknownCount == parts.count())
        return abiList;

    if (os == Abi::MacOS && arch != Abi::ArmArchitecture) {
        // Apple does PPC and x86!
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, width);
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, width == 64 ? 32 : 64);
        abiList << ProjectExplorer::Abi(arch == Abi::X86Architecture ? Abi::PowerPCArchitecture : Abi::X86Architecture, os, flavor, format, width);
        abiList << ProjectExplorer::Abi(arch == Abi::X86Architecture ? Abi::PowerPCArchitecture : Abi::X86Architecture, os, flavor, format, width == 64 ? 32 : 64);
    } else if (width == 64) {
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, width);
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, 32);
    } else {
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, width);
    }
    return abiList;
}
Example #2
0
void createHeatImage1(int argc, char *argv[])
{
    if (argc < 9)
    {
        printf("Usage: imager.exe -w 100 -h 100 -i filename.txt -o filename.png -min 0.0 -max 5.0\n");
        return;
    }

    unsigned int width = QString(argv[2]).toInt();
    unsigned int height = QString(argv[4]).toInt();
    QString inFile = QString(argv[6]);
    QString outFile = QString(argv[8]);
    double min = QString(argv[10]).toDouble();
    double max = QString(argv[12]).toDouble();

    qDebug() << width << height << inFile << outFile << min << max;

    QFile file(inFile);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream in(&file);

    double maximum = -9999.9;
    double minimum = +9999.9;

    DoubleMatrix m(height, width);

    unsigned int j=0;
    QString line = in.readLine();
    while (!line.isNull() && !line.isEmpty())
    {
        unsigned int i=0;
        QStringList list = line.split(" ");
        for (int k=0; k<list.size(); k++)
        {
            QString str = list[k];
            if (!str.isNull() && !str.isEmpty())
            {
                double u = str.toDouble();
                m[j][i] = u;
                if (u<=minimum) minimum = u;
                if (u>=maximum) maximum = u;
                i++;
            }
        }
        line = in.readLine();
        j++;
    }
    file.close();

    if (min != max)
    {
        minimum = min;
        maximum = max;
    }

    minimum = -0.3892016224094016;
    maximum = +0.3951541064046917;

    printf("File: %s Minimum: %.10f Maximum: %.10f width: %d height %d\n", inFile.toLatin1().data(), minimum, maximum, width, height);


    QPixmap pixmap;
    MatrixHeatImaging(m, minimum, maximum, pixmap, width, height);
    pixmap.save(outFile, "PNG");
}
Example #3
0
QString Serveur::parseCommande(QString comm,bool serveur)
{
    if(comm.startsWith("/"))
    {
        comm.remove(0,1);
        QString pref=comm.split(" ").first();
        QStringList args=comm.split(" ");
        args.removeFirst();
        QString destChan=tab->tabText(tab->currentIndex());
        QString msg=args.join(" ");

        if(pref=="me")
            return "PRIVMSG "+destChan+" ACTION " + msg + "";
        else if(pref=="join")
        {
            join(msg);
            return " ";
        }
        else if(pref=="quit")
        {
            if(msg == "")
                return "QUIT "+msgQuit;
            else
                return "QUIT "+msg;
        }
        else if(pref=="part")
        {
            tab->removeTab(tab->currentIndex());

            if(msg == "")
            {
                if(msg.startsWith("#"))
                    destChan=msg.split(" ").first();

                if(msgQuit=="")
                    return "PART "+destChan+" using IrcLightClient";
                else
                    return "PART "+destChan+" "+msgQuit;
            }
            else
                return "PART "+destChan+" "+msg;

            conversations.remove(destChan);
        }
        else if(pref=="kick")
        {
            QStringList tableau=msg.split(" ");
            QString c1,c2,c3;
            if(tableau.count() > 0) c1=" "+tableau.first();
            else c1="";
            if(tableau.count() > 1) c2=" "+tableau.at(1);
            else c2="";
            if(tableau.count() > 2) c3=" "+tableau.at(2);
            else c3="";

            if(c1.startsWith("#"))
                return "KICK"+c1+c2+c3;
            else
                return "KICK "+destChan+c1+c2;
        }
        else if(pref=="update")
        {
            updateUsers=true;
            return "WHO "+destChan;
        }
        else if(pref=="ns")
        {
            return "NICKSERV "+msg;
        }
        else if(pref=="nick")
        {
            emit pseudoChanged(msg);
                        ecrire("-> Nickname changed to "+msg);
            return "NICK "+msg;
        }
        else
            return pref+" "+msg;
    }
    else if(!serveur)
	{
        QString destChan=tab->tabText(tab->currentIndex());
                if(comm.endsWith("<br />"))
                    comm=comm.remove(QRegExp("<br />$"));
                ecrire("<b>&lt;"+pseudo+"&gt;</b> "+comm,destChan);

        if(comm.startsWith(":"))
            comm.insert(0,":");

        return "PRIVMSG "+destChan+" "+comm.replace(" ",".")+"";
    }
	else
	{
		return "";
	}
}
Example #4
0
void TagComparator::averageTags(const Tags& t1In, double w1, const Tags& t2In, double w2,
                                Tags& result, bool keepAllUnknownTags)
{
  //LOG_WARN("score: " << OsmSchema::getInstance().score("highway=road", "highway=unclassified"));
  result.clear();
  OsmSchema& schema = OsmSchema::getInstance();

  Tags t1 = t1In;
  Tags t2 = t2In;

  set<QString> k1, k2;

  mergeNames(t1, t2, result);

  // Merge any text fields by concatenating the lists.
  _mergeText(t1, t2, result);

  if (keepAllUnknownTags)
  {
    _mergeUnrecognizedTags(t1, t2, result);
  }

  for (Tags::const_iterator it1 = t1.begin(); it1 != t1.end(); it1++)
  {
    QString kvp1 = it1.key() + "=" + it1.value();
    QString kvp2;
    double bestScore = 0;
    QString bestKvp;
    QString bestK2;
    for (Tags::const_iterator it2 = t2.begin(); it2 != t2.end(); it2++)
    {
      kvp2 = it2.key() + "=" + it2.value();
      double score;
      QString thisKvp = schema.average(kvp1, w1, kvp2, w2, score);
      if (score > bestScore && k2.find(it2.key()) == k2.end())
      {
        bestScore = score;
        bestKvp = thisKvp;
        bestK2 = it2.key();
      }
    }
    if (bestKvp.isEmpty() == false)
    {
      k1.insert(it1.key());
      k2.insert(bestK2);

      if (bestKvp.contains("="))
      {
        QStringList sl = bestKvp.split("=");
        result[sl[0]] = sl[1];
      }
      else
      {
        result[it1.key()] = it1.value();
      }
    }
  }

  for (Tags::const_iterator it2 = t2.begin(); it2 != t2.end(); it2++)
  {
    if (k2.find(it2.key()) == k2.end())
    {
      result[it2.key()] = it2.value();
    }
  }

  for (Tags::const_iterator it1 = t1.begin(); it1 != t1.end(); it1++)
  {
    if (k1.find(it1.key()) == k1.end())
    {
      result[it1.key()] = it1.value();
    }
  }
}
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
	qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../qrmc", mLogicalRepoApi);

	IdList const metamodels = mLogicalRepoApi->children(Id::rootId());

	QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QApplication::processEvents();
	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);

	int forEditor = 60 / metamodels.size();

	foreach (Id const &key, metamodels) {
		QString const objectType = key.element();
		if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) {
			QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory");
			QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name");
			QString nameOfPlugin = nameOfTheDirectory.split("/").last();

			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading..")
					, QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin)
					, QMessageBox::Yes, QMessageBox::No)
					== QMessageBox::No)
			{
				continue;
			}

			progress->setValue(5);

			if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels
				QMessageBox::warning(mMainWindowInterface->windowWidget()
						, tr("error")
						, tr("Cannot generate source code for editor ") + nameOfPlugin);
				continue;
			}
			progress->setValue(20);

			QProcess builder;
			builder.setWorkingDirectory("../qrmc/plugins");
			builder.start(SettingsManager::value("pathToQmake").toString());
			qDebug()  << "qmake";
			if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
				progress->setValue(40);

				builder.start(SettingsManager::value("pathToMake").toString());

				bool finished = builder.waitForFinished(100000);
				qDebug()  << "make";
				if (finished && (builder.exitCode() == 0)) {
					qDebug()  << "make ok";

					progress->setValue(progress->value() + forEditor / 2);

					QString normalizedName = nameOfPlugin.at(0).toUpper() + nameOfPlugin.mid(1);
					if (!nameOfPlugin.isEmpty()) {
						if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
							QMessageBox::warning(mMainWindowInterface->windowWidget()
									, tr("error")
									, tr("cannot unload plugin ") + normalizedName);
							progress->close();
							delete progress;
							continue;
						}
					}

					QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
							+ nameOfPlugin
							+ "."
							+ SettingsManager::value("pluginExtension").toString()
							;

					if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
						progress->setValue(progress->value() + forEditor / 2);
					}
				}
				progress->setValue(100);
			}
		}
	}
Example #6
0
void Matrix::pasteSelection()
{
	QString the_text = QApplication::clipboard()->text();
	if (the_text.isEmpty())
		return;

	allow_modification_signals = false;
	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

	QTextStream ts( &the_text, QIODevice::ReadOnly );
	QString s = ts.readLine();
	QStringList cellTexts = s.split("\t");
	int cols = cellTexts.count();
	int rows = 1;
	while(!ts.atEnd())
	{
		rows++;
		s = ts.readLine();
	}
	ts.reset();

	int i, j, top, bottom, right, left, firstCol;

	QList<QTableWidgetSelectionRange> sel = d_table->selectedRanges();
	QListIterator<QTableWidgetSelectionRange> it(sel);
	QTableWidgetSelectionRange cur;

	if (!sel.isEmpty())
	{
		cur = it.next();
		top = cur.topRow();
		bottom = cur.bottomRow();
		left = cur.leftColumn();
		right = cur.rightColumn();
	}
	else
	{
		top = 0;
		bottom = numRows() - 1;
		left = 0;
		right = numCols() - 1;

		firstCol = firstSelectedColumn();

		if (firstCol >= 0)
		{ // columns are selected
			left = firstCol;
			int selectedColsNumber = 0;
			for(i=0; i<numCols(); i++)
			{
				if (isColumnSelected(i, true))
					selectedColsNumber++;
			}
			right = firstCol + selectedColsNumber - 1;
		}
	}

	QTextStream ts2( &the_text, QIODevice::ReadOnly );
	int r = bottom-top+1;
	int c = right-left+1;

	QApplication::restoreOverrideCursor();
	if (rows>r || cols>c)
	{
		// TODO: I find the insert cells option awkward
		// I would prefer the behavior of OpenOffice Calc
		// here - thzs
		switch( QMessageBox::information(0,"QtiPlot",
					tr("The text in the clipboard is larger than your current selection!\
						\nDo you want to insert cells?"),
					tr("Yes"), tr("No"), tr("Cancel"), 0, 0) )
		{
			case 0:
				if(cols > c )
					for(int i=0; i<(cols-c); i++)
						d_table->insertColumn(left);

				if(rows > r)
				{
					if (firstCol >= 0)
						for(int i=0; i<(rows-r); i++)
							d_table->insertRow(top);
					else
						for(int i=0; i<(rows-r+1); i++)
							d_table->insertRow(top);
				}
				break;
			case 1:
				rows = r;
				cols = c;
				break;
			case 2:
				allow_modification_signals = true;
				return;
				break;
		}
	}

	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
	bool numeric;
	double value;
	QLocale system_locale = QLocale::system();
	for(i=top; i<top+rows; i++)
	{
		s = ts2.readLine();
		cellTexts=s.split("\t");
		for(j=left; j<left+cols; j++)
		{
			value = system_locale.toDouble(cellTexts[j-left], &numeric);
			if (numeric)
				setText(i, j, QLocale().toString(value, txt_format.toAscii(), num_precision));
			else
				setText(i, j, cellTexts[j-left]);
		}
	}

	allow_modification_signals = true;
	emit modifiedWindow(this);
	QApplication::restoreOverrideCursor();
}
 static EnumValue parseEnumString(const QString &enumString)
 {
   EnumValue value;
   value.nameParts = enumString.split(QLatin1String("::"));
   return value;
 }
Example #8
0
void RichTextHtmlEdit::insertFromMimeData(const QMimeData *source) {
	QString uri;
	QString title;
	QRegExp newline(QLatin1String("[\\r\\n]"));

#ifndef QT_NO_DEBUG
	qWarning() << "RichTextHtmlEdit::insertFromMimeData" << source->formats();
	foreach(const QString &format, source->formats())
		qWarning() << format << decodeMimeString(source->data(format));
#endif

	if (source->hasImage()) {
		QImage img = qvariant_cast<QImage>(source->imageData());
		QString html = Log::imageToImg(img);
		if (! html.isEmpty())
			insertHtml(html);
		return;
	}

	QString mozurl = decodeMimeString(source->data(QLatin1String("text/x-moz-url")));
	if (! mozurl.isEmpty()) {
		QStringList lines = mozurl.split(newline);
		qWarning() << mozurl << lines;
		if (lines.count() >= 2) {
			uri = lines.at(0);
			title = lines.at(1);
		}
	}

	if (uri.isEmpty())
		uri = decodeMimeString(source->data(QLatin1String("text/x-moz-url-data")));
	if (title.isEmpty())
		title = decodeMimeString(source->data(QLatin1String("text/x-moz-url-desc")));

	if (uri.isEmpty()) {
		QStringList urls;
#ifdef Q_OS_WIN
		urls = decodeMimeString(source->data(QLatin1String("application/x-qt-windows-mime;value=\"UniformResourceLocatorW\""))).split(newline);
		if (urls.isEmpty())
#endif
			urls = decodeMimeString(source->data(QLatin1String("text/uri-list"))).split(newline);
		if (! urls.isEmpty())
			uri = urls.at(0);
		uri = urls.at(0).trimmed();
	}

	if (uri.isEmpty()) {
		QUrl url(source->text(), QUrl::StrictMode);
		if (url.isValid() && ! url.isRelative()) {
			uri = url.toString();
		}
	}

#ifdef Q_OS_WIN
	if (title.isEmpty() && source->hasFormat(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""))) {
		QByteArray qba = source->data(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""));
		if (qba.length() == sizeof(FILEGROUPDESCRIPTORW)) {
			const FILEGROUPDESCRIPTORW *ptr = reinterpret_cast<const FILEGROUPDESCRIPTORW *>(qba.constData());
			title = QString::fromWCharArray(ptr->fgd[0].cFileName);
			if (title.endsWith(QLatin1String(".url"), Qt::CaseInsensitive))
				title = title.left(title.length() - 4);
		}
	}
#endif

	if (! uri.isEmpty()) {
		if (title.isEmpty())
			title = uri;
		uri = Qt::escape(uri);
		title = Qt::escape(title);

		insertHtml(QString::fromLatin1("<a href=\"%1\">%2</a>").arg(uri, title));
		return;
	}

	QString html = decodeMimeString(source->data(QLatin1String("text/html")));
	if (! html.isEmpty()) {
		insertHtml(html);
		return;
	}

	QTextEdit::insertFromMimeData(source);
}
Example #9
0
void VLMWrapper::EditSchedule( const QString& name, const QString& input,
                               const QString& inputOptions, const QString& output,
                               QDateTime _schetime, QDateTime _schedate,
                               int _scherepeatnumber, int _repeatDays,
                               bool b_enabled, const QString& mux )
{
    vlm_message_t *message;
    QString command;

    if( !input.isEmpty() )
    {
        command = "setup \"" + name + "\" input \"" + input + "\"";
        vlm_ExecuteCommand( p_vlm, qtu( command ), &message );
        vlm_MessageDelete( message );

        QStringList options = inputOptions.split( " :", QString::SkipEmptyParts );
        for( int i = 0; i < options.count(); i++ )
        {
            command = "setup \"" + name + "\" option \"" + options[i].trimmed() + "\"";
            vlm_ExecuteCommand( p_vlm, qtu( command ), &message );
            vlm_MessageDelete( message );
        }
    }

    if( !output.isEmpty() )
    {
        command = "setup \"" + name + "\" output \"" + output + "\"";
        vlm_ExecuteCommand( p_vlm, qtu( command ), &message );
        vlm_MessageDelete( message );
    }

    if( b_enabled )
    {
        command = "setup \"" + name + "\" enabled";
        vlm_ExecuteCommand( p_vlm, qtu( command ), &message );
        vlm_MessageDelete( message );
    }

    if( !mux.isEmpty() )
    {
        command = "setup \"" + name + "\" mux \"" + mux + "\"";
        vlm_ExecuteCommand( p_vlm, qtu( command ), &message );
        vlm_MessageDelete( message );
    }

    command = "setup \"" + name + "\" date \"" +
        _schedate.toString( "yyyy/MM/dd" )+ "-" +
        _schetime.toString( "hh:mm:ss" ) + "\"";
    vlm_ExecuteCommand( p_vlm, qtu( command ), &message );
    vlm_MessageDelete( message );

    if( _scherepeatnumber > 0 )
    {
       command = "setup \"" + name + "\" repeat \"" + _scherepeatnumber + "\"";
       vlm_ExecuteCommand( p_vlm, qtu( command ), &message );
       vlm_MessageDelete( message );
    }

    if( _repeatDays > 0 )
    {
       command = "setup \"" + name + "\" period \"" + _repeatDays + "\"";
       vlm_ExecuteCommand( p_vlm, qtu( command ), &message );
       vlm_MessageDelete( message );
    }
}
Example #10
0
/**
 *	計算およびDB構築
 *
 *	@param[in] n			サンプル数
 */
void SMAThread::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)
	PliceData tempData;				// 一時保存用時系列データ
	QString temp_1;					// 一時保存用文字列
	QString temp_2;					// 一時保存用文字列

	// ディレクトリ生成
	_mkdir("DB\\SMA_" + 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\\SMA_" + 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);

				// SMA計算
				ma_open		= 0;
				ma_high		= 0;
				ma_low		= 0;
				ma_close	= 0;
				ma_volume	= 0;
				ma_aClose	= 0;
				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;

				// SMAおよび乖離率の書き込み
				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";
			}

			writeFile.close();
		}

		readFile.close();
	}
}
Example #11
0
bool Moves::loadFromFile(const QString &name)
{
    /// Removes current moves from sequence.
    moves.clear();
    current = 0;
    time = 0.0f;
    start = Punkt();

    /// Loads from file.
    QFile file(name);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::critical(view, "Plik formatu animacji nie istnieje", "Animacja nie może zostać wczytana. ");
        return false;
    }

    QTextStream in(&file);

    /// Split text to lines.
    /// Reads line-by-line.
    /// Each line is split to tokens.
    QString line;
    QStringList data;

    int lineNumber = 0;
    while (!in.atEnd()) {
        ++lineNumber;
        line = in.readLine();
        data = line.split(" ");

        if(data.size() == 0 || (data.size() == 1 && data[0] == ""))
            continue;

        /// First letter specifies move type: f - forward, b - backward, s - stand, o - rotate
        Move move;
        if(data[0] == "f")
            move.state = STATE_GO_FRONT;
        else if(data[0] == "b")
            move.state = STATE_GO_BACK;
        else if(data[0] == "s")
            move.state = STATE_STAND;
        else if(data[0] == "o")
            move.state = STATE_ROTATE;
        else
        {
            loadError(lineNumber);
            return false;
        }

        /// Loads data after letter (duration time, rotation angle). If there is no such data, gets default value.
        if(data.size() > 1)
            move.time = data[1].toFloat();
        else
            move.time = 1.0f;
        if(data.size() > 2)
            move.rad = data[2].toFloat();
        else
            move.rad = 0.0;

        /// Adds move to sequence of moves.
        moves.push_back(move);
    }

    return true;
}
QgsDelimitedTextProvider::QgsDelimitedTextProvider( QString uri )
    : QgsVectorDataProvider( uri ),
    mXFieldIndex( -1 ), mYFieldIndex( -1 ),
    mShowInvalidLines( true )
{
  // Get the file name and mDelimiter out of the uri
  mFileName = uri.left( uri.indexOf( "?" ) );
  // split the string up on & to get the individual parameters
  QStringList parameters = uri.mid( uri.indexOf( "?" ) ).split( "&", QString::SkipEmptyParts );

  QgsDebugMsg( "Parameter count after split on &" + QString::number( parameters.size() ) );

  // get the individual parameters and assign values
  QStringList temp = parameters.filter( "delimiter=" );
  mDelimiter = temp.size() ? temp[0].mid( temp[0].indexOf( "=" ) + 1 ) : "";
  temp = parameters.filter( "delimiterType=" );
  mDelimiterType = temp.size() ? temp[0].mid( temp[0].indexOf( "=" ) + 1 ) : "";
  temp = parameters.filter( "xField=" );
  QString xField = temp.size() ? temp[0].mid( temp[0].indexOf( "=" ) + 1 ) : "";
  temp = parameters.filter( "yField=" );
  QString yField = temp.size() ? temp[0].mid( temp[0].indexOf( "=" ) + 1 ) : "";
  // Decode the parts of the uri. Good if someone entered '=' as a delimiter, for instance.
  mFileName  = QUrl::fromPercentEncoding( mFileName.toUtf8() );
  mDelimiter = QUrl::fromPercentEncoding( mDelimiter.toUtf8() );
  mDelimiterType = QUrl::fromPercentEncoding( mDelimiterType.toUtf8() );
  xField    = QUrl::fromPercentEncoding( xField.toUtf8() );
  yField    = QUrl::fromPercentEncoding( yField.toUtf8() );

  QgsDebugMsg( "Data source uri is " + uri );
  QgsDebugMsg( "Delimited text file is: " + mFileName );
  QgsDebugMsg( "Delimiter is: " + mDelimiter );
  QgsDebugMsg( "Delimiter type is: " + mDelimiterType );
  QgsDebugMsg( "xField is: " + xField );
  QgsDebugMsg( "yField is: " + yField );

  // if delimiter contains some special characters, convert them
  if ( mDelimiterType == "regexp" )
    mDelimiterRegexp = QRegExp( mDelimiter );
  else
    mDelimiter.replace( "\\t", "\t" ); // replace "\t" with a real tabulator

  // Set the selection rectangle to null
  mSelectionRectangle = QgsRectangle();
  // assume the layer is invalid until proven otherwise
  mValid = false;
  if ( mFileName.isEmpty() || mDelimiter.isEmpty() || xField.isEmpty() || yField.isEmpty() )
  {
    // uri is invalid so the layer must be too...
    QString( "Data source is invalid" );
    return;
  }

  // check to see that the file exists and perform some sanity checks
  if ( !QFile::exists( mFileName ) )
  {
    QgsDebugMsg( "Data source " + dataSourceUri() + " doesn't exist" );
    return;
  }

  // Open the file and get number of rows, etc. We assume that the
  // file has a header row and process accordingly. Caller should make
  // sure the the delimited file is properly formed.
  mFile = new QFile( mFileName );
  if ( !mFile->open( QIODevice::ReadOnly ) )
  {
    QgsDebugMsg( "Data source " + dataSourceUri() + " could not be opened" );
    delete mFile;
    return;
  }

  // now we have the file opened and ready for parsing

  // set the initial extent
  mExtent = QgsRectangle();

  QMap<int, bool> couldBeInt;
  QMap<int, bool> couldBeDouble;

  mStream = new QTextStream( mFile );
  QString line;
  mNumberFeatures = 0;
  int lineNumber = 0;
  bool firstPoint = true;
  bool hasFields = false;
  while ( !mStream->atEnd() )
  {
    lineNumber++;
    line = mStream->readLine(); // line of text excluding '\n', default local 8 bit encoding.
    if ( !hasFields )
    {
      // Get the fields from the header row and store them in the
      // fields vector
      QgsDebugMsg( "Attempting to split the input line: " + line + " using delimiter " + mDelimiter );

      QStringList fieldList;
      if ( mDelimiterType == "regexp" )
        fieldList = line.split( mDelimiterRegexp );
      else
        fieldList = line.split( mDelimiter );
      QgsDebugMsg( "Split line into " + QString::number( fieldList.size() ) + " parts" );

      // We don't know anything about a text based field other
      // than its name. All fields are assumed to be text
      int fieldPos = 0;
      for ( QStringList::Iterator it = fieldList.begin();
            it != fieldList.end(); ++it )
      {
        QString field = *it;
        if ( field.length() > 0 )
        {
          // for now, let's set field type as text
          attributeFields[fieldPos] = QgsField( *it, QVariant::String, "Text" );

          // check to see if this field matches either the x or y field
          if ( xField == *it )
          {
            QgsDebugMsg( "Found x field: " + ( *it ) );
            mXFieldIndex = fieldPos;
          }
          else if ( yField == *it )
          {
            QgsDebugMsg( "Found y field: " + ( *it ) );
            mYFieldIndex = fieldPos;
          }

          QgsDebugMsg( "Adding field: " + ( *it ) );
          // assume that the field could be integer or double
          couldBeInt.insert( fieldPos, true );
          couldBeDouble.insert( fieldPos, true );
          fieldPos++;
        }
      }
      QgsDebugMsg( "Field count for the delimited text file is " + QString::number( attributeFields.size() ) );
      hasFields = true;
    }
    else if ( mXFieldIndex != -1 && mYFieldIndex != -1 )
    {
      mNumberFeatures++;

      // split the line on the delimiter
      QStringList parts;
      if ( mDelimiterType == "regexp" )
        parts = line.split( mDelimiterRegexp );
      else
        parts = line.split( mDelimiter );

      // Skip malformed lines silently. Report line number with nextFeature()
      if ( attributeFields.size() != parts.size() )
      {
        continue;
      }

      // Get the x and y values, first checking to make sure they
      // aren't null.
      QString sX = parts[mXFieldIndex];
      QString sY = parts[mYFieldIndex];

      bool xOk = true;
      bool yOk = true;
      double x = sX.toDouble( &xOk );
      double y = sY.toDouble( &yOk );

      if ( xOk && yOk )
      {
        if ( !firstPoint )
        {
          mExtent.combineExtentWith( x, y );
        }
        else
        { // Extent for the first point is just the first point
          mExtent.set( x, y, x, y );
          firstPoint = false;
        }
      }

      int i = 0;
      for ( QStringList::iterator it = parts.begin(); it != parts.end(); ++it, ++i )
      {
        // try to convert attribute values to integer and double
        if ( couldBeInt[i] )
        {
          it->toInt( &couldBeInt[i] );
        }
        if ( couldBeDouble[i] )
        {
          it->toDouble( &couldBeDouble[i] );
        }
      }
    }
  }

  // now it's time to decide the types for the fields
  for ( QgsFieldMap::iterator it = attributeFields.begin(); it != attributeFields.end(); ++it )
  {
    if ( couldBeInt[it.key()] )
    {
      it->setType( QVariant::Int );
      it->setTypeName( "integer" );
    }
    else if ( couldBeDouble[it.key()] )
    {
      it->setType( QVariant::Double );
      it->setTypeName( "double" );
    }
  }

  if ( mXFieldIndex != -1 && mYFieldIndex != -1 )
  {
    QgsDebugMsg( "Data store is valid" );
    QgsDebugMsg( "Number of features " + QString::number( mNumberFeatures ) );
    QgsDebugMsg( "Extents " + mExtent.toString() );

    mValid = true;
  }
  else
  {
    QgsDebugMsg( "Data store is invalid. Specified x,y fields do not match those in the database" );
  }
  QgsDebugMsg( "Done checking validity" );

}
bool QgsDelimitedTextProvider::nextFeature( QgsFeature& feature )
{
  // before we do anything else, assume that there's something wrong with
  // the feature
  feature.setValid( false );
  while ( ! mStream->atEnd() )
  {
    double x = 0.0;
    double y = 0.0;
    QString line = mStream->readLine(); // Default local 8 bit encoding

    // lex the tokens from the current data line
    QStringList tokens;
    if ( mDelimiterType == "regexp" )
      tokens = line.split( mDelimiterRegexp );
    else
      tokens = line.split( mDelimiter );

    bool xOk = false;
    bool yOk = false;

    // Skip indexing malformed lines.
    if ( attributeFields.size() == tokens.size() )
    {
      x = tokens[mXFieldIndex].toDouble( &xOk );
      y = tokens[mYFieldIndex].toDouble( &yOk );
    }

    if ( !( xOk && yOk ) )
    {
      // Accumulate any lines that weren't ok, to report on them
      // later, and look at the next line in the file, but only if
      // we need to.
      QgsDebugMsg( "Malformed line : " + line );
      if ( mShowInvalidLines )
        mInvalidLines << line;

      continue;
    }

    // Give every valid line in the file an id, even if it's not
    // in the current extent or bounds.
    ++mFid;             // increment to next feature ID

    // skip the feature if it's out of current bounds
    if ( ! boundsCheck( x, y ) )
      continue;

    // at this point, one way or another, the current feature values
    // are valid
    feature.setValid( true );

    feature.setFeatureId( mFid );

    QByteArray  buffer;
    QDataStream s( &buffer, static_cast<QIODevice::OpenMode>( QIODevice::WriteOnly ) ); // open on buffers's data

    switch ( QgsApplication::endian() )
    {
      case QgsApplication::NDR :
        // we're on a little-endian platform, so tell the data
        // stream to use that
        s.setByteOrder( QDataStream::LittleEndian );
        s << ( quint8 )1; // 1 is for little-endian
        break;
      case QgsApplication::XDR :
        // don't change byte order since QDataStream is big endian by default
        s << ( quint8 )0; // 0 is for big-endian
        break;
      default :
        qDebug( "%s:%d unknown endian", __FILE__, __LINE__ );
        //delete [] geometry;
        return false;
    }

    s << ( quint32 )QGis::WKBPoint;
    s << x;
    s << y;

    unsigned char* geometry = new unsigned char[buffer.size()];
    memcpy( geometry, buffer.data(), buffer.size() );

    feature.setGeometryAndOwnership( geometry, sizeof( wkbPoint ) );

    for ( QgsAttributeList::const_iterator i = mAttributesToFetch.begin();
          i != mAttributesToFetch.end();
          ++i )
    {
      QVariant val;
      switch ( attributeFields[*i].type() )
      {
        case QVariant::Int:
          val = QVariant( tokens[*i].toInt() );
          break;
        case QVariant::Double:
          val = QVariant( tokens[*i].toDouble() );
          break;
        default:
          val = QVariant( tokens[*i] );
          break;
      }
      feature.addAttribute( *i, val );
    }

    // We have a good line, so return
    return true;

  } // ! textStream EOF

  // End of the file. If there are any lines that couldn't be
  // loaded, display them now.

  if ( mShowInvalidLines && !mInvalidLines.isEmpty() )
  {
    mShowInvalidLines = false;
    QgsMessageOutput* output = QgsMessageOutput::createMessageOutput();
    output->setTitle( tr( "Error" ) );
    output->setMessage( tr( "Note: the following lines were not loaded because Qgis was "
                            "unable to determine values for the x and y coordinates:\n" ),
                        QgsMessageOutput::MessageText );

    output->appendMessage( "Start of invalid lines." );
    for ( int i = 0; i < mInvalidLines.size(); ++i )
      output->appendMessage( mInvalidLines.at( i ) );
    output->appendMessage( "End of invalid lines." );

    output->showMessage();

    // We no longer need these lines.
    mInvalidLines.empty();
  }

  return false;

} // nextFeature
Example #14
0
	bool fromString(const QString & szValue, QStringList & buffer)
	{
		buffer = szValue.split(",");
		return true;
	}
Example #15
0
  bool ConfigBase::exportConfiguration( const QString &name, const Configuration  &config ) {

    if ( name.isNull() || name.isEmpty() ) {
      return false;
    }

    QString homePath = QDir::homePath();

    homePath.append( "/.dboxfe" );

    QDir exportDir( homePath + "/export/" + name );

    if ( exportDir.exists() ) {
      exportDir.mkpath( homePath + "/export/" + name );
    }

    writeConfiguration( homePath + "/export/" + name + "/" + name + ".conf", config );

    QSettings exportConf( homePath + "/export/" + name + "/" + name + ".conf", QSettings::IniFormat );
    exportConf.beginGroup( "dosbox" );
    QString language = exportConf.value( "language" ).toString();
    QString captures = exportConf.value( "captures" ).toString();
    exportConf.endGroup();

    // autoexec
    QFile configFile( homePath + "/export/" + name + "/" + name + ".conf" );

    if ( !configFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) {
      return false;
    }

    QTextStream in( &configFile );

    QString line = QString( "" );
    QString autoexec = QString( "" );
    QString mountDirectory = QString( "" );

    while ( !in.atEnd() ) {
      line = in.readLine();

      if ( line == "[autoexec]" ) {
        while ( !in.atEnd() ) {
          autoexec = in.readAll();
          mountDirectory = autoexec.split( " " ).value( 2 );

          QMap< QString, QString> zipData = exportDatas( mountDirectory );
          QMap< QString, QString>::const_iterator zipDataIt = zipData.constBegin();

          while ( zipDataIt != zipData.end() ) {
            QString fileDirectory = zipDataIt.key();
            QString fileName = zipDataIt.value();
            QString file = fileDirectory + fileName;

            // TODO make sure that you create directory before you create/copy file
            // insert code here ...

            QFile copyFile( file );

            if ( copyFile.exists() ) {
              QFileInfo copyFileInfo( copyFile );
              bool ok = copyFile.copy( homePath + "/export/" + name + "/" + fileName );

              if ( !ok ) {
                ++zipDataIt;
              }
            }

            ++zipDataIt;
          }

          if ( line.startsWith( "[" ) && line.endsWith( "]" ) )
            break;
        }
      }
    }

    configFile.close();

    // Create Ziparchive for D-Fend Reloaded
    Zip::ErrorCode ec;
    Zip iz;

    ec = iz.createArchive( homePath + "/export/" + name + ".zip" );

    if ( ec != Zip::Ok ) {

      qDebug() << QDateTime::currentDateTime().toString( Qt::LocaleDate ) << tr( " - [ERROR] Unable to create archive: " ) << iz.formatError( ec ).toAscii().data() << endl;
      return false;
    }

    ec = iz.addDirectory( homePath + "/export/" + name );

    if ( ec != Zip::Ok ) {

      qDebug() << QDateTime::currentDateTime().toString( Qt::LocaleDate ) << tr( " - [ERROR] Unable to add directory: " ) << iz.formatError( ec ).toAscii().data() << endl;
      return false;
    }

    QString zipComment = QString( "" );

    zipComment += tr( "This archive has been created using OSDaB Zip (http://osdab.sourceforge.net/)." ) + "\n";
    zipComment += tr( "This archive was created by DBoxFE." );

    iz.setArchiveComment( zipComment );

    if ( iz.closeArchive() != Zip::Ok ) {

      qDebug() << QDateTime::currentDateTime().toString( Qt::LocaleDate ) << tr( " - [ERROR] Unable to close the archive: " ) << iz.formatError( ec ).toAscii().data() << endl;
      return false;
    }

    return true;
  }
Example #16
0
bool
ClipObject::processCommand(QString cmd)
{
  bool ok;
  cmd = cmd.toLower();
  QStringList list = cmd.split(" ", QString::SkipEmptyParts);
  
  if (list[0] == "mop")
    {
      if (list.size() == 2 && list[1] == "clip")
	{
	  m_mopClip = true;
	  return true;
	}
      else
	return false;
    }
  else if (list[0] == "tfset")
    {
      int tf = 1000;
      if (list.size() == 2) tf = qMax(0, list[1].toInt());
      m_tfset = tf;
      return true;
    }
  else if (list[0] == "reorientcamera")
    {
      m_reorientCamera = true;
      return true;
    }
  else if (list[0] == "color")
    {
      QColor dcolor = QColor::fromRgbF(m_color.x,
				       m_color.y,
				       m_color.z);
      QColor color = DColorDialog::getColor(dcolor);
      if (color.isValid())
	{
	  float r = color.redF();
	  float g = color.greenF();
	  float b = color.blueF();
	  m_color = Vec(r,g,b);
	}
    }
  else if (list[0] == "solidcolor")
    {
      if (list.size() == 2 &&
	  list[1] == "no")
	m_solidColor = false;
      else
	m_solidColor = true;
      return true;
    }
  else if (list[0] == "savesliceimage")
    {
      m_resliceSubsample = 1;
      m_saveSliceImage = true;
      if (list.size() == 2) m_resliceSubsample = qMax(1, list[1].toInt(&ok));
      return true;
    }
  else if (list[0] == "reslice")
    {
      m_resliceSubsample = 1;
      m_resliceTag = -1;
      m_resliceVolume = true;
      if (list.size() > 1) m_resliceSubsample = qMax(1, list[1].toInt(&ok));
      if (list.size() > 2) m_resliceTag = list[2].toInt(&ok);
      return true;
    }
  else if (list[0] == "grid")
    {
      if (list.size() == 1)
	{
	  m_gridX = m_gridY = 10;
	}
      else if (list.size() == 2 && list[1] == "no")
	{
	  m_gridX = m_gridY = 0;
	}
      else if (list.size() == 3)
	{
	  m_gridX = list[1].toInt();
	  m_gridY = list[2].toInt();
	}
      return true;
    }
  else if (list[0] == "image")
    {
      if (list.size() == 2 &&
	  list[1] == "no")
	clearImage();
      else
	loadImage();
      return true;
    }
  else if (list[0] == "imageframe")
    {
      if (list.size() == 2)
	{
	  int frm = list[1].toInt(&ok);
	  if (frm >= 0)
	    {
	      loadImage(m_imageName, frm);
	    }
	  else
	    QMessageBox::information(0, "Error",
				     "ImageFrame not changed.  Positive values required");
	}
      else
	QMessageBox::information(0, "Error",
				 "Please specify ImageFrame number for the clipplane");
      return true;
    }
  else if (list[0] == "caption")
    {
      if (list.count() == 2 &&
	  list[1] == "no")
	clearCaption();
      else
	loadCaption();

      return true;
    }
  else if (list[0] == "vscale" ||
	   list[0] == "scale")
    {
      if (list.size() > 1)
	{
	  float scl1, scl2;
	  if (list.size() == 2)
	    {
	      scl1 = list[1].toFloat(&ok);
	      scl2 = scl1;
	    }
	  else
	    {
	      scl1 = list[1].toFloat(&ok);
	      scl2 = list[2].toFloat(&ok);
	    }
	  if (list[0] == "scale")
	    {
	      m_scale1 = -qAbs(scl1);
	      m_scale2 = -qAbs(scl2);
	    }
	  else
	    {
	      m_scale1 = scl1;
	      m_scale2 = scl2;
	    }
	}
      else
	QMessageBox::information(0, "Error",
				 "Please specify both scalings for the clipplane");
      return true;
    }
  else if (list[0] == "opacity")
    {
      if (list.size() == 2)
	{
	  float scl = list[1].toFloat(&ok);
	  if (scl >= 0 && scl <= 1)
	    {
	      m_opacity = scl;
	      m_opacity = qMax(0.02f, qMin(1.0f, m_opacity));
	    }
	  else
	    QMessageBox::information(0, "Error",
				     "Opacity not changed.  Value between 0 and 1 required");
	}
      else
	QMessageBox::information(0, "Error",
				 "Please specify opacity for the clipplane");
      return true;
    }
  else if (list[0] == "translate" ||
	   list[0] == "translatex" ||
	   list[0] == "translatey" ||
	   list[0] == "translatez" ||
	   list[0] == "move" ||
	   list[0] == "movex" ||
	   list[0] == "movey" ||
	   list[0] == "movez")
    {
      Vec pos;
      float x=0,y=0,z=0;

      if (list[0] == "translate" || list[0] == "move")
	{
	  if (list.size() > 1) x = list[1].toFloat(&ok);
	  if (list.size() > 2) y = list[2].toFloat(&ok);
	  if (list.size() > 3) z = list[3].toFloat(&ok);
	  pos = Vec(x,y,z);
	}
      else
	{
	  float v=0;
	  if (list.size() > 1) v = list[1].toFloat(&ok);
	  if (list[0] == "translatex" || list[0] == "movex")
	    pos = Vec(v,0,0);
	  else if (list[0] == "translatey" || list[0] == "movey")
	    pos = Vec(0,v,0);
	  else if (list[0] == "translatez" || list[0] == "movez")
	    pos = Vec(0,0,v);
	}

      if (list[0].contains("move"))
	{
	  Vec cpos = position();
	  pos = pos + cpos;
	}
      setPosition(pos);
      return true;
    }
  else if (list[0] == "rotatea" ||
	   list[0] == "rotateb" ||
	   list[0] == "rotatec")
    {
      float angle = 0;
      if (list.size() > 1)
	{
	  angle = list[1].toFloat(&ok);
	  if (list[0] == "rotatea") rotate(m_xaxis, angle);
	  if (list[0] == "rotateb") rotate(m_yaxis, angle);
	  if (list[0] == "rotatec") rotate(m_tang, angle);
	}
      else
	{
	  QMessageBox::information(0, "", "No angle specified");
	}       
      return true;
    }
  else if (list[0] == "movea" ||
	   list[0] == "moveb" ||
	   list[0] == "movec")
    {
      float shift = 0;
      if (list.size() > 1)
	{
	  shift = list[1].toFloat(&ok);
	  if (list[0] == "movea") translate(shift*m_xaxis);
	  if (list[0] == "moveb") translate(shift*m_yaxis);
	  if (list[0] == "movec") translate(shift*m_tang);
	}
      else
	{
	  QMessageBox::information(0, "", "No distance specified");
	}       
      return true;
    }
  else if (list[0] == "rotate" ||
	   list[0] == "rotatex" ||
	   list[0] == "rotatey" ||
	   list[0] == "rotatez" ||
	   list[0] == "addrotation" ||
	   list[0] == "addrotationx" ||
	   list[0] == "addrotationy" ||
	   list[0] == "addrotationz")
    {
      Quaternion rot;
      float x=0,y=0,z=0,a=0;
      if (list[0] == "rotate" || list[0] == "addrotation")
	{
	  if (list.size() > 1) x = list[1].toFloat(&ok);
	  if (list.size() > 2) y = list[2].toFloat(&ok);
	  if (list.size() > 3) z = list[3].toFloat(&ok);
	  if (list.size() > 4) a = list[4].toFloat(&ok);
	  rot = Quaternion(Vec(x,y,z), DEG2RAD(a));
	}
      else
	{
	  float a=0;
	  if (list.size() > 1) a = list[1].toFloat(&ok);
	  if (list[0] == "rotatex" || list[0] == "addrotationx")
	    rot = Quaternion(Vec(1,0,0), DEG2RAD(a));
	  else if (list[0] == "rotatey" || list[0] == "addrotationy")
	    rot = Quaternion(Vec(0,1,0), DEG2RAD(a));
	  else if (list[0] == "rotatez" || list[0] == "addrotationz")
	    rot = Quaternion(Vec(0,0,1), DEG2RAD(a));
	}

      if (list[0].contains("addrotation"))
	{
	  Quaternion orot = orientation();
	  rot = rot*orot;
	}
      setOrientation(rot);
      return true;
    }
  else
    QMessageBox::information(0, "Error",
			     QString("Cannot understand the command : ") +
			     cmd);

  return false;
}
Example #17
0
void MainWindow::checkInput()
{
    /*
    //DELETE THIS PART!
    ui->imagePath->insert("D:/WORKSPACE/PHOTO MOSAIC/StarWars.jpg");
    ui->subImgDir->insert("D:/WORKSPACE/PHOTO MOSAIC/PICTURES/StarWars");
    ui->pmWidth->insert("15360"); //15360
    ui->pmHeight->insert("8640"); //8640
    ui->numOfSub->insert("57600"); //57600
    ui->subRatio->insert("16:9"); //16:9
    ui->precisionBox->setValue(2); // precision
    */

    QString mainImgPath = ui->imagePath->text();
    QString subImgDir = ui->subImgDir->text();
    if (subImgDir.length() >= 1) {
        if (subImgDir.at(subImgDir.size() - 1) != '/') {
            subImgDir.insert(subImgDir.size(), '/');
        }
    }


    int precision = ui->precisionBox ->value();
    int mainWidth = ui->pmWidth->text().toInt();
    int mainHeight = ui->pmHeight->text().toInt();
    int numSubImg = ui->numOfSub->text().toInt();
    QString ratio = ui->subRatio->text();

    int wRatio = ratio.split(":").value(0).toInt();
    int hRatio = ratio.split(":").value(1).toInt();


    if (allValidInput(mainWidth,mainHeight,numSubImg,ratio,mainImgPath,subImgDir)) {

        ui->graphicsView->setScene(scene);
        QPixmap img(mainImgPath);
        scene->addPixmap(img);
//                ui->graphicsView->fitInView(0,00);
        ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);

        memberVariables.append(QString::number(mainWidth));
        memberVariables.append(QString::number(mainHeight));
        memberVariables.append(QString::number(wRatio));
        memberVariables.append(QString::number(hRatio));
        memberVariables.append(QString::number(numSubImg));
        memberVariables.append(mainImgPath);
        memberVariables.append(subImgDir);
        memberVariables.append(QString::number(precision));

        qDebug() << wRatio << hRatio;
        emit updateAll(memberVariables); //emits the signal

        // inputs are read-only.
        ui->pmWidth->setEnabled(false);
        ui->pmHeight->setEnabled(false);
        ui->subRatio->setEnabled(false);
        ui->numOfSub->setEnabled(false);
        ui->imagePath->setEnabled(false);
        ui->subImgDir->setEnabled(false);
        ui->precisionBox->setEnabled(false);

        qDebug() << "EMMITED;";
    }

}
Example #18
0
bool
ClipObject::commandEditor()
{
  PropertyEditor propertyEditor;
  QMap<QString, QVariantList> plist;
  QVariantList vlist;
  vlist.clear();
  plist["command"] = vlist;


  vlist.clear();
  vlist << QVariant("double");
  vlist << QVariant(m_opacity);
  vlist << QVariant(0.0);
  vlist << QVariant(1.0);
  vlist << QVariant(0.1); // singlestep
  vlist << QVariant(1); // decimals
  plist["opacity"] = vlist;
  
  vlist.clear();
  vlist << QVariant("color");
  Vec pcolor = m_color;
  QColor dcolor = QColor::fromRgbF(pcolor.x,
				   pcolor.y,
				   pcolor.z);
  vlist << dcolor;
  plist["color"] = vlist;
  
  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_apply);
  plist["apply clipping"] = vlist;

  vlist.clear();
  vlist << QVariant("int");
  vlist << QVariant(m_tfset);
  vlist << QVariant(-1);
  vlist << QVariant(15);
  plist["tfset"] = vlist;

  vlist.clear();
  vlist << QVariant("int");
  vlist << QVariant(m_thickness);
  vlist << QVariant(0);
  vlist << QVariant(200);
  plist["thickness"] = vlist;

  vlist.clear();
  vlist << QVariant("int");
  vlist << QVariant(m_opmod);
  vlist << QVariant(1);
  vlist << QVariant(10);
  plist["opmod"] = vlist;

  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_solidColor);
  plist["solid color"] = vlist;

  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_showSlice);
  plist["show slice"] = vlist;

  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_showThickness);
  plist["show thickness"] = vlist;

  vlist.clear();
  vlist << QVariant("combobox");
  if (m_viewportType)
    vlist << QVariant(1);
  else
    vlist << QVariant(0);
  vlist << QVariant("orthographic");
  vlist << QVariant("perspective");
  plist["camera type"] = vlist;

  vlist.clear();
  vlist << QVariant("double");
  vlist << QVariant(m_stereo);
  vlist << QVariant(0.0);
  vlist << QVariant(1.0);
  vlist << QVariant(0.1); // singlestep
  vlist << QVariant(1); // decimals
  plist["stereo"] = vlist;
  
  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_showOtherSlice);
  plist["show other slice"] = vlist;


  QString vpstr = QString("%1 %2 %3 %4").\
                  arg(m_viewport.x()).\
                  arg(m_viewport.y()).\
                  arg(m_viewport.z()).\
                  arg(m_viewport.w());
  vlist.clear();
  vlist << QVariant("string");
  vlist << QVariant(vpstr);
  plist["viewport"] = vlist;

  vlist.clear();
  vlist << QVariant("double");
  vlist << QVariant(m_viewportScale);
  vlist << QVariant(0.5);
  vlist << QVariant(30.0);
  vlist << QVariant(0.1); // singlestep
  vlist << QVariant(1); // decimals
  plist["viewport scale"] = vlist;  


  vlist.clear();
  QFile helpFile(":/clipobject.help");
  if (helpFile.open(QFile::ReadOnly))
    {
      QTextStream in(&helpFile);
      QString line = in.readLine();
      while (!line.isNull())
	{
	  if (line == "#begin")
	    {
	      QString keyword = in.readLine();
	      QString helptext;
	      line = in.readLine();
	      while (!line.isNull())
		{
		  helptext += line;
		  helptext += "\n";
		  line = in.readLine();
		  if (line == "#end") break;
		}
	      vlist << keyword << helptext;
	    }
	  line = in.readLine();
	}
    }
  
  plist["commandhelp"] = vlist;
  
  //---------------------
  vlist.clear();
  QString mesg;
  if (m_scale1 < 0 || m_scale2 < 0)
    mesg += QString("scales : %1 %2\n").arg(-m_scale1).arg(-m_scale2);
  else
    mesg += QString("vscales : %1 %2\n").arg(m_scale1).arg(m_scale2);

  mesg += QString("opacity : %1\n").arg(m_opacity);
  mesg += QString("position : %1 %2 %3\n").			\
    arg(m_position.x).arg(m_position.y).arg(m_position.z);

  Quaternion q = orientation();
  Vec axis;
  qreal angle;
  q.getAxisAngle(axis, angle);
  mesg += QString("rotation : %1 %2 %3 : %4\n").			\
    arg(axis.x).arg(axis.y).arg(axis.z).arg(RAD2DEG(angle));
  
  
  mesg += QString("Red axis : %1 %2 %3\n").		\
    arg(m_xaxis.x).arg(m_xaxis.y).arg(m_xaxis.z);
  mesg += QString("Green axis : %1 %2 %3\n").		\
    arg(m_yaxis.x).arg(m_yaxis.y).arg(m_yaxis.z);
  mesg += QString("Blue axis : %1 %2 %3\n").		\
    arg(m_tang.x).arg(m_tang.y).arg(m_tang.z);
  
  vlist << mesg;
  
  plist["message"] = vlist;
  //---------------------



  QStringList keys;
  keys << "apply clipping";
  keys << "solid color";
  keys << "show slice";
  keys << "show thickness";
  keys << "show other slice";
  keys << "gap";
  keys << "color";
  keys << "opacity";
  keys << "gap";
  keys << "viewport";
  keys << "tfset";
  keys << "opmod";
  keys << "thickness";
  keys << "viewport scale";
  keys << "camera type";
  keys << "stereo";
  keys << "gap";
  keys << "command";
  keys << "commandhelp";
  keys << "message";
  
  propertyEditor.set("Clip Plane Dialog", plist, keys);
  
  QMap<QString, QPair<QVariant, bool> > vmap;

  if (propertyEditor.exec() == QDialog::Accepted)
    vmap = propertyEditor.get();
  else
    return true;
	      
  keys = vmap.keys();

  for(int ik=0; ik<keys.count(); ik++)
    {
      QPair<QVariant, bool> pair = vmap.value(keys[ik]);
      
      
      if (pair.second)
	{
	  if (keys[ik] == "color")
	    {
	      QColor color = pair.first.value<QColor>();
	      float r = color.redF();
	      float g = color.greenF();
	      float b = color.blueF();
	      m_color = Vec(r,g,b);
	    }
	  else if (keys[ik] == "opacity")
	    m_opacity = pair.first.toDouble();
	  else if (keys[ik] == "solid color")
	    m_solidColor = pair.first.toBool();
	  else if (keys[ik] == "apply clipping")
	    m_apply = pair.first.toBool();
	  else if (keys[ik] == "show slice")
	    m_showSlice = pair.first.toBool();
	  else if (keys[ik] == "show thickness")
	    m_showThickness = pair.first.toBool();
	  else if (keys[ik] == "show other slice")
	    m_showOtherSlice = pair.first.toBool();
	  else if (keys[ik] == "tfset")
	    m_tfset = pair.first.toInt();
	  else if (keys[ik] == "thickness")
	    m_thickness = pair.first.toInt();
	  else if (keys[ik] == "viewport scale")
	    m_viewportScale = pair.first.toDouble();
	  else if (keys[ik] == "camera type")
	    m_viewportType = (pair.first.toInt() == 1);
	  else if (keys[ik] == "stereo")
	    m_stereo = pair.first.toDouble();
	  else if (keys[ik] == "opmod")
	    m_opmod = pair.first.toInt();
	  else if (keys[ik] == "viewport")
	    {
	      vpstr = pair.first.toString();
	      QStringList list = vpstr.split(" ", QString::SkipEmptyParts);
	      if (list.count() == 4)
		{
		  float x = list[0].toFloat();
		  float y = list[1].toFloat();
		  float z = list[2].toFloat();
		  float w = list[3].toFloat();
		  if (x < 0.0f || x > 1.0f ||
		      y < 0.0f || y > 1.0f ||
		      z < 0.0f || z > 1.0f ||
		      w < 0.0f || w > 1.0f)
		    QMessageBox::information(0, "",
		      QString("Values for viewport must be between 0.0 and 1.0 : %1 %2 %3 %4").\
					     arg(x).arg(y).arg(z).arg(w));
		  else
		    m_viewport = QVector4D(x,y,z,w);
		}
	      else if (list.count() == 3)
		{
		  float x = list[0].toFloat();
		  float y = list[1].toFloat();
		  float z = list[2].toFloat();
		  if (x < 0.0f || x > 1.0f ||
		      y < 0.0f || y > 1.0f ||
		      z < 0.0f || z > 1.0f)
		    QMessageBox::information(0, "",
		      QString("Values for viewport must be between 0.0 and 1.0 : %1 %2 %3").\
					     arg(x).arg(y).arg(z));
		  else
		    m_viewport = QVector4D(x,y,z,z);
		}
	      else if (list.count() == 2)
		{
		  float x = list[0].toFloat();
		  float y = list[1].toFloat();
		  if (x < 0.0f || x > 1.0f ||
		      y < 0.0f || y > 1.0f)
		    QMessageBox::information(0, "",
		      QString("Values for viewport must be between 0.0 and 1.0 : %1 %2").\
					     arg(x).arg(y));
		  else
		    m_viewport = QVector4D(x,y,0.5,0.5);
		}
	      else
		{
		  QMessageBox::information(0, "", "Switching off the viewport");
		  m_viewport = QVector4D(-1,-1,-1,-1);
		}
	    }
	}
    }

  QString cmd = propertyEditor.getCommandString();
  if (!cmd.isEmpty())
    return processCommand(cmd);
  else
    return true;

//  if (propertyEditor.exec() == QDialog::Accepted)
//    {
//      QString cmd = propertyEditor.getCommandString();
//      if (!cmd.isEmpty())
//	return processCommand(cmd);
//    }
//  else
//    return true;
}
QVector<double> MainWindow::read_CDB_positions(){
    QString CDB_file;
    if(ui->line_CDB_summary->text().isEmpty()){
        CDB_file = "run7469_parent_geometry_file.txt";
    }
    else{
        CDB_file = ui->line_CDB_summary->text();
    }


    QFile file(CDB_file);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        std::cerr << "Failed to read geometry file.\n";
        QVector<double> fail(3, 0.0);
        return fail;
    }

    QTextStream in(&file);
    double z_q7, z_q8, z_q9, z_TOF0, z_TOF1;
    double z_correction = 999.592;  // mm, correct for different starting definitions
                                    // we need the centre, the geometry gives the
                                    // start of the field
    while(!in.atEnd()){
        QString line = in.readLine();

        if(line.contains("TOF0.dat")){
            line = in.readLine();
            line = in.readLine();
            if(line.contains("Position")){
                QStringList list = line.split(" ", QString::SkipEmptyParts);
                z_TOF0 = list.at(3).toDouble();
                std::cout << "TOF0 is at " << z_TOF0 << "\n";
            }
        }

        if(line.contains("TOF1.dat")){
            line = in.readLine();
            line = in.readLine();
            if(line.contains("Position")){
                QStringList list = line.split(" ", QString::SkipEmptyParts);
                z_TOF1 = list.at(3).toDouble();
                std::cout << "TOF1 is at " << z_TOF1 << "\n";
            }
        }

        if(line.contains("Module Q7")){
            line = in.readLine();
            line = in.readLine();
            line = in.readLine();
            if(line.contains("Position")){
                QStringList list = line.split(" ", QString::SkipEmptyParts);
                z_q7 = list.at(3).toDouble() + z_correction;
                std::cout << "Q7 is at " << z_q7 << "\n";
            }
        }

        if(line.contains("Module Q8")){
            line = in.readLine();
            line = in.readLine();
            line = in.readLine();
            if(line.contains("Position")){
                QStringList list = line.split(" ", QString::SkipEmptyParts);
                z_q8 = list.at(3).toDouble() + z_correction;
                std::cout << "Q8 is at " << z_q8 << "\n";
            }
        }

        if(line.contains("Module Q9")){
            line = in.readLine();
            line = in.readLine();
            line = in.readLine();
            if(line.contains("Position")){
                QStringList list = line.split(" ", QString::SkipEmptyParts);
                z_q9 = list.at(3).toDouble() + z_correction;
                std::cout << "Q9 is at " << z_q9 << "\n";
            }
        }
    }

    QVector<double> magnet_currents;
    magnet_currents << z_q7 << z_q8 << z_q9 << z_TOF0 << z_TOF1;

    file.flush();
    file.close();
    return magnet_currents;
}
Example #20
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QString openFilename = NULL;
    if (a.arguments().count() > 1) {
        QFile *oFile = new QFile(a.arguments()[1]);
        if (oFile->exists()) {
            openFilename = oFile->fileName();
        }
    }
    QSplashScreen *splash = new QSplashScreen;
    splash -> setPixmap(QPixmap(":/images/splash.png"));
    splash->show();
    QTimer::singleShot(2000,splash,SLOT(close())); //Start splash screen and keep it 2 seconds
#ifdef Q_OS_LINUX
    systExp = "linuxAutre"; //Operating system of the user
    QFile fileOs ("/etc/os-release");
    if (fileOs.exists())
    {
        fileOs.open(QFile::ReadOnly);
        QTextStream stream (&fileOs);
        QString osTxt = stream.readAll();
        if (osTxt.contains("ID=slackware")) {
            systExp = "linuxSlackware";
        }
        else if (osTxt.contains("ID=ubuntu") || osTxt.contains("ID=debian")) {
            systExp = "linuxDebian";
        }
        else if (osTxt.contains("ID=arch") || osTxt.contains("ID=manjaro")) {
            systExp = "linuxArch";
        }
        fileOs.close();
    }
#else
    systExp = "windows";
#endif

    //Define confFile:
    confFile  = confDir +".config";

    //Set locale:
    QString locale = QLocale::system().name();
    appI18n = locale.split("_")[0] == "fr" ? "fr" : "en";

    //Load config:
    QFile configFile(confFile);
    if (configFile.exists()) {
        Functions::loadConfig();
    }
    QTranslator translator;
    translator.load(QString("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    QString trFile = ":/i18n/qrecipewriter_"+ appI18n +".qm";
    if (QFile(trFile).exists()) {
        translator.load(trFile);
    }
    a.installTranslator(&translator);

    //Define other variables:
    QString tmp = confDir + ".cats";
    confCatFile = new QFile(tmp);
    #ifdef Q_OS_LINUX
    QFile fileDictTest1 ("/usr/share/myspell/dicts/fr_FR.dic");
    QFile fileDictTest2 ("/usr/share/myspell/dicts/fr_FR.aff");
    if (fileDictTest1.exists() && fileDictTest2.exists())
    {
        corrOrtho = "/usr/share/myspell/dicts/fr_FR";
    }
    #else
        #if _WIN64
            QFile fileDictTest1 ("C:/hunspellX64/dicts/fr.dic");
            QFile fileDictTest2 ("C:/hunspellX64/dicts/fr.aff");
            if (fileDictTest1.exists() && fileDictTest2.exists())
            {
                corrOrtho = "C:/hunspellX64/dicts/fr";
            }
        #else
            QFile fileDictTest1 ("C:/hunspellI686/dicts/fr.dic");
            QFile fileDictTest2 ("C:/hunspellI686/dicts/fr.aff");
            if (fileDictTest1.exists() && fileDictTest2.exists())
            {
                corrOrtho = "C:/hunspellI686/dicts/fr";
            }
        #endif
    #endif

    QRecipeWriter w;
    w.openStartupFile = openFilename;

    //Define Dialogs:
    Apropos *apropos = new Apropos(&w);
    ptr2apropos = apropos;
    QDir tmpD (dirTmp);
    if (configFile.exists())
    {
        w.init();
        if (!tmpD.exists())
        {
            tmpD.mkpath(".");
        }
        QTimer::singleShot(2000,&w,SLOT(launch())); //Start the application
    }
    else
    {
        QTimer::singleShot(2000,&w,SLOT(config())); //Start initial config
    }
    return a.exec();
}
Example #21
0
void KviHttpRequest::slotSocketConnected()
{
	if(m_p->pConnectTimeoutTimer)
	{
		delete m_p->pConnectTimeoutTimer;
		m_p->pConnectTimeoutTimer = NULL;
	}

	emit connectionEstabilished();
	emit status(
			__tr2qs("Connected to %1:%2: sending request")
					.arg(m_p->pSocket->peerAddress().toString())
					.arg(m_p->pSocket->peerPort())
		);

	KviCString szMethod;

	bool bIsPost = false;

	if(m_eProcessingType == HeadersOnly)
		szMethod = "HEAD";
	else if(m_szPostData.isEmpty())
		szMethod = "GET";
	else {
		szMethod = "POST";
		bIsPost = true;
	}

	KviCString szRequest(
			KviCString::Format,
			"%s %s HTTP/1.1\r\n" \
			"Host: %s\r\n" \
			"Connection: Close\r\n" \
			"User-Agent: KVIrc-http-slave/1.0.0\r\n" \
			"Accept: */*\r\n",
			szMethod.ptr(),
			m_url.path().toUtf8().data(),
			m_url.host().toUtf8().data()
		);

	if(m_uContentOffset > 0)
		szRequest.append(KviCString::Format,"Range: bytes=%u-\r\n",m_uContentOffset);

	if(bIsPost)
	{
		szRequest.append(KviCString::Format,"Content-Type: application/x-www-form-urlencoded\r\n" \
				"Content-Length: %u\r\n" \
				"Cache-control: no-cache\r\n" \
				"Pragma: no-cache\r\n",m_szPostData.length());
	}

	szRequest += "\r\n";

	if(bIsPost)
	{
		if(!m_szPostData.isEmpty())
			szRequest.append(m_szPostData);
		szRequest += "\r\n";
	}

	// FIXME: Handle this better!
	int written = m_p->pSocket->write(szRequest.ptr(),szRequest.len());
	if(written < szRequest.len())
	{
		m_szLastError = __tr2qs("Socket write error");
		resetInternalStatus();
		emit terminated(false);
	}

	// FIXME: Handle this better
	QString req = QString::fromLatin1(szRequest.ptr());
	QStringList sl = req.split("\r\n");
	emit requestSent(sl);

	// now wait for the response

	// FIXME: Handle read timeouts!
}
bool WeatherDataModel::readDataPeriods(QString line)
{
    QStringList list = line.split(',');
    if(list.size()-3 <= 0 || (list.size()-3) % 4 != 0) {
        LOG(error) << "WeatherDataModel: Expected a multiple of 4 plus 3 entries, got " << list.size();
        return false;
    }
    if(list[0].toLower() != "data periods") {
        LOG(error) << "WeatherDataModel: Unexpected section name '" << list[0].toStdString() <<"'";
        return false;
    }
    bool ok;
    int nDataPeriods = list[1].toInt(&ok);
    if((list.size()-3)/4 != nDataPeriods) {
        LOG(error) << "WeatherDataModel: Expected data for " << nDataPeriods << " data periods, found data for "
                   << (list.size()-3)/4;
        return false;
    }
    m_recordsPerHour = list[2].toInt(&ok);
    if(!ok) {
        LOG(error) << "WeatherDataModel: Cannot convert records per hour value '" << list[2].toStdString()
                   << "' into an integer";
        return false;
    } else if(1 > m_recordsPerHour || 60 < m_recordsPerHour)
    {
        LOG(error) << "WeatherDataModel: Records per hour value " << m_recordsPerHour << " out of range";
        return false;
    }
    if(60 % m_recordsPerHour != 0) {
        LOG(error) << "WeatherDataModel: " << m_recordsPerHour << " records per hour does not evenly divide an hour";
        return false;
    }
    m_minutesBetweenRecords = 60/m_recordsPerHour;
    int i=2;
    QString names[7] = {QString("sunday"), QString("monday"), QString("tuesday"), QString("wednesday"),
                        QString("thursday"), QString("friday"), QString("saturday")};
    for(int n=0;n<nDataPeriods;n++){
        std::string name = list[++i].toStdString();
        QString startDay = list[++i].toLower();
        int intDay=0;
        while(startDay != names[intDay]) {
            intDay++;
            if(intDay==7) {
                LOG(error) << "WeatherDataModel: Invalid starting day '" << startDay.toStdString() << "'";
                return false;
            }
        }
        intDay++;
        QString dateString = list[++i].simplified();
        QDate startDate = QDate::fromString(dateString.replace(" ",""),"M/d");
        if(!startDate.isValid()) {
            LOG(error) << "WeatherDataModel: Invalid starting date string '" << list[i].toStdString() << "'";
            return false;
        }
        dateString = list[++i].simplified();
        QDate endDate = QDate::fromString(dateString.replace(" ",""),"M/d");
        if(!endDate.isValid()) {
            LOG(error) << "WeatherDataModel: Invalid ending date string '" << list[i].toStdString() << "'";
            return false;
        }
        // If we got to this point, everything checks out
        m_dataPeriods << WeatherDataPeriod(name,intDay,startDate.month(),startDate.day(),endDate.month(),endDate.day());
    }

    return true;
}
RideFile *ManualFileReader::openRideFile(QFile &file, QStringList &errors, QList<RideFile*>*) const
{
    QRegExp metricUnits("(km|kph|km/h)", Qt::CaseInsensitive);
    QRegExp englishUnits("(miles|mph|mp/h)", Qt::CaseInsensitive);
    bool metric = false;

    int unitsHeader = 2;

    /*
     *  File format:
     * 	"manual"
     * 	"minutes,mph,watts,miles,hr,bikescore"  # header (metric or imperial)
     *	minutes,mph,watts,miles,hr,bikeScore    # data
     */
    QRegExp manualCSV("manual", Qt::CaseInsensitive);

    double rideSec = 0;

    if (!file.open(QFile::ReadOnly)) {
	errors << (tr("Could not open ride file: \"")
		+ file.fileName() + "\"");
	return NULL;
    }
    int lineno = 1;
    QStringList columnNames;
    QTextStream is(&file);
    RideFile *rideFile = new RideFile();
    while (!is.atEnd()) {
	// the readLine() method doesn't handle old Macintosh CR line endings
	// this workaround will load the the entire file if it has CR endings
	// then split and loop through each line
	// otherwise, there will be nothing to split and it will read each line as expected.
	QString linesIn = is.readLine();
	QStringList lines = linesIn.split('\r');
	// workaround for empty lines
	if(lines.isEmpty()) {
	    lineno++;
	    continue;
	}
	for (int li = 0; li < lines.size(); ++li) {
	    QString line = lines[li];

	    if (lineno == 1) {
		if (manualCSV.indexIn(line) != -1) {
            rideFile->setDeviceType("Manual");
            rideFile->setFileFormat("Manual CSV (csv)");
		    ++lineno;
		    continue;
		}
	    }
	    else if (lineno == unitsHeader) {
		if (metricUnits.indexIn(line) != -1)
		    metric = true;
		else if (englishUnits.indexIn(line) != -1)
		    metric = false;
		else {
		    errors << (tr("Can't find units in first line: \"") + line + "\"");
		    delete rideFile;
		    file.close();
		    return NULL;
		}
                columnNames = line.split(",");
		++lineno;
		continue;
	    }
	    // minutes,kph,watts,km,hr,bikeScore
	    else if (lineno > unitsHeader) {
		double minutes=0,kph=0,watts=0,km=0,hr=0,alt=0,bs=0;
		double cad=0, nm=0;
		int interval=0;
                QStringList fields = line.split(",");
                minutes = fields[0].toDouble();
                kph = fields[1].toDouble();
                watts = fields[2].toDouble();
                km = fields[3].toDouble();
                hr = fields[4].toDouble();
                bs = fields[5].toDouble();
		if (!metric) {
		    km *= KM_PER_MILE;
		    kph *= KM_PER_MILE;
		}
                const RideMetricFactory &factory = RideMetricFactory::instance();
                for (int i = 6; i < fields.size(); ++i) {
                    if (factory.haveMetric(columnNames[i])) {
                        QMap<QString,QString> map;
                        map.insert("value", QString("%1").arg(fields[i]));
                        rideFile->metricOverrides.insert(columnNames[i], map);
                    }
                    else {
                        errors << tr("Unknown ride metric \"%1\".").arg(columnNames[i]);
                    }
                }
		cad = nm = 0.0;
		interval = 0;

		rideFile->appendPoint(minutes * 60.0, cad, hr, km,
                                      kph, nm, watts, alt,
                                      0.0, 0.0, 0.0, 0.0,
                                      RideFile::noTemp, 0.0, interval);
                QMap<QString,QString> bsm;
                bsm.insert("value", QString("%1").arg(bs));
                rideFile->metricOverrides.insert("skiba_bike_score", bsm);
                QMap<QString,QString> trm;
                trm.insert("value", QString("%1").arg(minutes * 60.0));
                rideFile->metricOverrides.insert("time_riding", trm);

		rideSec = minutes * 60.0;
	    }
	    ++lineno;
	}
    }
    // fix recording interval at ride length:
    rideFile->setRecIntSecs(rideSec);

    QRegExp rideTime("^.*/(\\d\\d\\d\\d)_(\\d\\d)_(\\d\\d)_"
	    "(\\d\\d)_(\\d\\d)_(\\d\\d)\\.man$");
    if (rideTime.indexIn(file.fileName()) >= 0) {
	QDateTime datetime(QDate(rideTime.cap(1).toInt(),
		    rideTime.cap(2).toInt(),
		    rideTime.cap(3).toInt()),
		QTime(rideTime.cap(4).toInt(),
		    rideTime.cap(5).toInt(),
		    rideTime.cap(6).toInt()));
	rideFile->setStartTime(datetime);
    }
    file.close();
    return rideFile;
}
Example #24
0
///////
/// \brief QQPalmiFilePoster::parseUpload3TerOrg
/// \param data
///
void QQPalmiFilePoster::parseUpload3TerOrg(const QString &data)
{
	QStringList strL = data.split(QChar('\n'));
	if(strL.size() > 0)
		emit finished(QString("http://%1/f.php?h=%2&p=1").arg(FILE_SHARING_SERVICE_JIRAFEAU_3TER_ORG).arg(strL.first()));
}
Example #25
0
/**
* @brief Creates a new file with selected data
* @param asset The asset created
* @param file The file where are located the values.
* @throw ImportException The data is not valid
*/
void ImportNewData::import(const Asset &asset, const QString& file) const {
	QString data;
	QFile importedCSV(file);
	QStringList rowOfData;
	QStringList rowData;
	data.clear();
	rowOfData.clear();
	rowData.clear();
	QRegExp date_regex("^(20|19)[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$");
	QRegExp value_regex("^([0-9]+)([.])([0-9][0-9])$");
	QDate previousDate = QDate::fromString("2999-01-01", "yyyy-MM-dd");
	int data_index;
	if (asset.getOrigin() == "ProjectVaR") {
		data_index = 1;
	} else {
		data_index = 6;
	}

	if (importedCSV.open(QFile::ReadOnly)) {
		data = importedCSV.readAll();
		rowOfData = data.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
		importedCSV.close();
	}

	//FILE CREATION OF IMPORTED DATA
	// Do unique names
	QFile fileCreated(asset.getFile());
	// The file is open in write-only mode and we check the opening
	if (!fileCreated.open(QIODevice::WriteOnly | QIODevice::Text)) {
		return;
	}
	QTextStream flux(&fileCreated);
	flux.setCodec("UTF-8");
	QDate endDate = asset.getEndDate();
	QDate startDate = asset.getStartDate();
	rowData = rowOfData.at(0).split(",");
	if (!(rowData.count() < data_index)) {
		if (!((QString) rowData[0]).isEmpty() && !((QString)rowData[data_index]).isEmpty()) {
			flux << rowData[0] << "," << rowData[data_index] << "\n";
			// x = 1 to avoid the first line with labels
			for (int x =1; x < rowOfData.size()-1; x++) {
				rowData = rowOfData.at(x).split(",");
				//Check dates and values are correct
				if(date_regex.exactMatch(rowData[0]) && value_regex.exactMatch(rowData[data_index])) {
					QDate currentDate = QDate::fromString(rowData[0], "yyyy-MM-dd");
					//checks the order of dates
					if(previousDate > currentDate) {
						previousDate = currentDate;
						//checks if we are on still in the range of dates
						if ((endDate >= currentDate)) {
							if(startDate > currentDate) {
								break;
							}
							flux << rowData[0] << "," << rowData[data_index] << "\n";
						}
					} else {
						throw CreateAssetException("Dates are not sorted");
						return;
					}

				} else {
					throw CreateAssetException("The data is invalid");
					return;
				}
			}
		} else {
			throw CreateAssetException("Header is missing");
			return;
		}
	} else {
		throw CreateAssetException("Wrong file type");
		return;
	}
	fileCreated.close();
}
Example #26
0
// TODO: this will be replaced.
QString reprocessMarkdown(QString markdown)
{
	QString htmlData;
	QTextStream html(&htmlData);
	auto lines = markdown.split(QRegExp("[\r]?[\n]"),QString::KeepEmptyParts);
	enum
	{
		BASE,
		LIST1,
		LIST2
	}state = BASE;
	html << "<html>";
	int i = 0;
	auto procLine = [&](QString line) -> QString
	{
		// [GitHub issues](https://github.com/MultiMC/MultiMC5/issues)
		line.replace(QRegExp("\\[([^\\]]+)\\]\\(([^\\)]+)\\)"), "<a href=\"\\2\">\\1</a>");
		return line;
	};
	for(auto line: lines)
	{
		if(line.isEmpty())
		{
			// html << "<br />\n";
		}
		else switch (state)
		{
			case BASE:
				if(line.startsWith("##"))
				{
					html << "<h2>" << procLine(line.mid(2)) << "</h2>\n";
				}
				else if(line.startsWith("#"))
				{
					html << "<h1>" << procLine(line.mid(1)) << "</h1>\n";
				}
				else if(line.startsWith("- "))
				{
					state = LIST1;
					html << "<ul>\n";
					html << "<li>" << procLine(line.mid(2)) << "</li>\n";
				}
				else QLOG_ERROR() << "Invalid input on line " << i << ": " << line;
				break;
			case LIST1:
				if(line.startsWith("##"))
				{
					state = BASE;
					html << "</ul>\n";
					html << "<h2>" << procLine(line.mid(2)) << "</h2>\n";
				}
				else if(line.startsWith("#"))
				{
					state = BASE;
					html << "</ul>\n";
					html << "<h1>" << procLine(line.mid(1)) << "</h1>\n";
				}
				else if(line.startsWith("- "))
				{
					html << "<li>" << procLine(line.mid(2)) << "</li>\n";
				}
				else if(line.startsWith("  - "))
				{
					state = LIST2;
					html << "<ul>\n";
					html << "<li>" << procLine(line.mid(4)) << "</li>\n";
				}
				else QLOG_ERROR() << "Invalid input on line " << i << ": " << line;
				break;
			case LIST2:
				if(line.startsWith("##"))
				{
					state = BASE;
					html << "</ul>\n";
					html << "</ul>\n";
					html << "<h2>" << procLine(line.mid(2)) << "</h2>\n";
				}
				else if(line.startsWith("#"))
				{
					state = BASE;
					html << "</ul>\n";
					html << "</ul>\n";
					html << "<h1>" << procLine(line.mid(1)) << "</h1>\n";
				}
				else if(line.startsWith("- "))
				{
					state = LIST1;
					html << "</ul>\n";
					html << "<li>" << procLine(line.mid(2)) << "</li>\n";
				}
				else if(line.startsWith("  - "))
				{
					html << "<li>" << procLine(line.mid(4)) << "</li>\n";
				}
				else QLOG_ERROR() << "Invalid input on line " << i << ": " << line;
				break;
		}
		i++;
	}
	if(state == LIST2)
	{
		html << "</ul>\n";
		state = LIST1;
	}
	if(state == LIST1)
	{
		html << "</ul>\n";
		state = BASE;
	}
	if (state != BASE)
	{
		QLOG_ERROR() << "Reprocessing markdown didn't end in a final state!";
	}
	html << "</html>\n";
	QLOG_DEBUG() << htmlData;
	return htmlData;
}
Example #27
0
void createHeatImage2(int argc, char *argv[])
{
    if (argc < 7)
    {
        printf("Usage: images.exe -w 100 -i filename.txt -o filename.png\n");
        return;
    }

    unsigned int width = QString(argv[2]).toInt();
    QString inFile = QString(argv[4]);
    QString outFile = QString(argv[6]);

    QPixmap pixmap(QSize(width, 10));
    pixmap.fill(Qt::white);
    QPainter painter(&pixmap);

    QFile file(inFile);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream in(&file);

    double maximum = 6.6724519545;
    double minimum = 0.0;

    QDoubleVector m;
    m.resize(width);

    QString line = in.readLine();
    QStringList list = line.split(" ");
    unsigned int i=0;
    for (int j=0; j<list.size(); j++)
    {
        QString str = list[j];
        if (!str.isNull() && !str.isEmpty())
        {
            double u = str.toDouble();
            m[i] = u;
            if (u<=minimum) minimum = u;
            if (u>=maximum) maximum = u;
            i++;
        }
    }
    file.close();

    printf("Minimum: %.10f Maximum: %.10f width: %d output: %s\n", minimum, maximum, width, outFile.toLatin1().data());
    //minimum = 1.0;

    for (int i=0; i<m.size(); i++)
    {
        double u = m[i];

        //unsigned int c = (u-minimum)*(maximum-minimum)*0xffffff;
        double ratio = 0.0;
        if (minimum!=maximum)
            ratio = 2.0 * (u-minimum) / (maximum - minimum);
        int b = int(MAX(0, 255*(1 - ratio)));
        int r = int(MAX(0, 255*(ratio - 1)));
        int g = 255 - b - r;
        QColor c(r, g, b);
        painter.setPen(c);
        painter.drawLine(i,0,i,10);
    }

    pixmap.save(outFile, "PNG");
}
Example #28
0
/*!
  \a fileName is the path of the file to find.

  \a files and \a dirs are the lists where we must find the
  components of \a fileName.
  
  \a location is used for obtaining the file and line numbers
  for report qdoc errors.
 */
QString Config::findFile(const Location& location,
                         const QStringList& files,
                         const QStringList& dirs,
                         const QString& fileName,
                         QString& userFriendlyFilePath)
{
    if (fileName.isEmpty() || fileName.startsWith(QLatin1Char('/'))) {
        userFriendlyFilePath = fileName;
        return fileName;
    }

    QFileInfo fileInfo;
    QStringList components = fileName.split(QLatin1Char('?'));
    QString firstComponent = components.first();

    QStringList::ConstIterator f = files.begin();
    while (f != files.end()) {
	if (*f == firstComponent ||
            (*f).endsWith(QLatin1Char('/') + firstComponent)) {
	    fileInfo.setFile(*f);
	    if (!fileInfo.exists())
		location.fatal(tr("File '%1' does not exist").arg(*f));
	    break;
	}
	++f;
    }

    if (fileInfo.fileName().isEmpty()) {
	QStringList::ConstIterator d = dirs.begin();
	while (d != dirs.end()) {
	    fileInfo.setFile(QDir(*d), firstComponent);
	    if (fileInfo.exists()) {
		break;
            }
	    ++d;
	}
    }

    userFriendlyFilePath = QString();
    if (!fileInfo.exists())
	    return QString();

    QStringList::ConstIterator c = components.begin();
    for (;;) {
	bool isArchive = (c != components.end() - 1);
	QString userFriendly = *c;

	userFriendlyFilePath += userFriendly;

	if (isArchive) {
	    QString extracted = extractedDirs[fileInfo.filePath()];
	    ++c;
	    fileInfo.setFile(QDir(extracted), *c);
	}
        else
	    break;

	userFriendlyFilePath += "?";
    }
    return fileInfo.filePath();
}
Example #29
0
void MainWindow::on_actionOpen_triggered()
{
    QString speckFileOpenStr = QFileDialog::getOpenFileName(this, tr("Open File"), QString(),
                tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if (!speckFileOpenStr.isEmpty()) {
        QFile fileO(speckFileOpenStr);
        if (!fileO.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
        QTextStream in(&fileO);
        //int i;
        QString line;
        QStringList splittedLine, splittedLastLine;
        //i=0;
        speckCount=0;randomsL.clear();randomsW.clear();
        while(!in.atEnd()){
            line=in.readLine();
            splittedLine=line.split(",");
            splittedLastLine=line.split(" ");
            if(splittedLastLine[3]=="total"){
                qDebug()<<"Last line last word: "<<splittedLastLine[3];
                break;
            }
            randomsL.append(splittedLine[0].toDouble());
            randomsW.append(splittedLine[1].toDouble());
            qDebug()<<"Length random="<<randomsL[speckCount]<<"Width random="<<randomsW[speckCount];
            speckCount=speckCount+1;
        }
        fileO.close();
    }
    //Speckle the plate
    if (thereIsPlate==false){
        QMessageBox::information(this, "There is no plate to speckle", "Please draw the plate first");
        return;
    }
    on_cleanButton_clicked();
    readRadii();
    float X, Y;
    //Adding circular speckles to the plate
    if(specksElliptic==false){
        for (int i=0; i<speckCount;i++){
            //Keeping the ellipses within the plate
            if(randomsL[i]*pLength-speckDiam < 0){
                X=randomsL[i]*pLength;
            }
            else{
                X=randomsL[i]*pLength-speckDiam;
            }
            if(randomsW[i]*pWidth-speckDiam < 0){
                Y=randomsW[i]*pWidth;
            }
            else{
                Y=randomsW[i]*pWidth-speckDiam;
            }
            speckList.append(scene->addEllipse(/*randomsL[i]*pLength-speckDiam*/X, /*randomsW[i]*pWidth-speckDiam*/Y, speckDiam, speckDiam,
                        QPen(), redBrush));
        }
    }
    //Adding elliptic speckles to the plate
    if(specksElliptic==true){
        for (int i=0; i<speckCount;i++){
            //Keeping the ellipses within the plate
            //Major axis in horizontal direction case
            if(dia->directionCount>1){
                QMessageBox::information(this, "You checked more than one speckle direction options", "Please select only one speckle direction option");
                return;
            }
            qDebug()<<"majorAxisHorizontal is "<<dia->majorAxisHorizontal;
            if(dia->majorAxisHorizontal==true){
                if(randomsL[i]*pLength-2*majorRadius < 0){
                    X=randomsL[i]*pLength;
                }
                else{
                    X=randomsL[i]*pLength-2*majorRadius;//most of the time this is used
                }
                if(randomsW[i]*pWidth-2*minorRadius < 0){
                    Y=randomsW[i]*pWidth;
                }
                else{
                    Y=randomsW[i]*pWidth-2*minorRadius;
                }
                speckList.append(scene->addEllipse(/*randomsL[i]*pLength-speckDiam*/X, /*randomsW[i]*pWidth-speckDiam*/Y, 2*majorRadius, 2*minorRadius,
                            QPen(), redBrush));
            }
            else if(dia->majorAxisVertical==true){
                if(randomsL[i]*pLength-2*minorRadius < 0){
                    X=randomsL[i]*pLength;
                }
                else{
                    X=randomsL[i]*pLength-2*minorRadius;//most of the time this is used
                }
                if(randomsW[i]*pWidth-2*majorRadius < 0){
                    Y=randomsW[i]*pWidth;
                }
                else{
                    Y=randomsW[i]*pWidth-2*majorRadius;
                }
                speckList.append(scene->addEllipse(/*randomsL[i]*pLength-speckDiam*/X, /*randomsW[i]*pWidth-speckDiam*/Y, 2*minorRadius, 2*majorRadius,
                            QPen(), redBrush));
            }
            //Major axis in vertical direction case
        }
    }
    speckList.clear();
    qDebug()<<"The number of speckles: "<<speckCount;
    speckCountStr=QString::number(speckCount);
    ui->sCountEdit->setText(speckCountStr);
}
Example #30
0
bool QVFbScreen::connect(const QString &displaySpec)
{
    QStringList displayArgs = displaySpec.split(QLatin1Char(':'));
    if (displayArgs.contains(QLatin1String("Gray")))
        grayscale = true;

    key_t key = ftok(QByteArray(QT_VFB_MOUSE_PIPE).replace("%1", QByteArray::number(displayId)), 'b');

    if (key == -1)
        return false;

#if Q_BYTE_ORDER == Q_BIG_ENDIAN
#ifndef QT_QWS_FRAMEBUFFER_LITTLE_ENDIAN
    if (displayArgs.contains(QLatin1String("littleendian")))
#endif
        QScreen::setFrameBufferLittleEndian(true);
#endif

    int shmId = shmget(key, 0, 0);
    if (shmId != -1)
        d_ptr->shmrgn = (unsigned char *)shmat(shmId, 0, 0);
    else
        return false;

    if ((long)d_ptr->shmrgn == -1 || d_ptr->shmrgn == 0) {
        qDebug("No shmrgn %ld", (long)d_ptr->shmrgn);
        return false;
    }

    d_ptr->hdr = (QVFbHeader *)d_ptr->shmrgn;
    data = d_ptr->shmrgn + d_ptr->hdr->dataoffset;

    dw = w = d_ptr->hdr->width;
    dh = h = d_ptr->hdr->height;
    d = d_ptr->hdr->depth;

    switch (d) {
    case 1:
        setPixelFormat(QImage::Format_Mono);
        break;
    case 8:
        setPixelFormat(QImage::Format_Indexed8);
        break;
    case 12:
        setPixelFormat(QImage::Format_RGB444);
        break;
    case 15:
        setPixelFormat(QImage::Format_RGB555);
        break;
    case 16:
        setPixelFormat(QImage::Format_RGB16);
        break;
    case 18:
        setPixelFormat(QImage::Format_RGB666);
        break;
    case 24:
        setPixelFormat(QImage::Format_RGB888);
        break;
    case 32:
        setPixelFormat(QImage::Format_ARGB32_Premultiplied);
        break;
    }

    lstep = d_ptr->hdr->linestep;

    // Handle display physical size spec.
    int dimIdxW = -1;
    int dimIdxH = -1;
    for (int i = 0; i < displayArgs.size(); ++i) {
        if (displayArgs.at(i).startsWith(QLatin1String("mmWidth"))) {
            dimIdxW = i;
            break;
        }
    }
    for (int i = 0; i < displayArgs.size(); ++i) {
        if (displayArgs.at(i).startsWith(QLatin1String("mmHeight"))) {
            dimIdxH = i;
            break;
        }
    }
    if (dimIdxW >= 0) {
        bool ok;
        int pos = 7;
        if (displayArgs.at(dimIdxW).at(pos) == QLatin1Char('='))
            ++pos;
        int pw = displayArgs.at(dimIdxW).mid(pos).toInt(&ok);
        if (ok) {
            physWidth = pw;
            if (dimIdxH < 0)
                physHeight = dh*physWidth/dw;
        }
    }
    if (dimIdxH >= 0) {
        bool ok;
        int pos = 8;
        if (displayArgs.at(dimIdxH).at(pos) == QLatin1Char('='))
            ++pos;
        int ph = displayArgs.at(dimIdxH).mid(pos).toInt(&ok);
        if (ok) {
            physHeight = ph;
            if (dimIdxW < 0)
                physWidth = dw*physHeight/dh;
        }
    }
    if (dimIdxW < 0 && dimIdxH < 0) {
        const int dpi = 72;
        physWidth = qRound(dw * 25.4 / dpi);
        physHeight = qRound(dh * 25.4 / dpi);
    }

    qDebug("Connected to VFB server %s: %d x %d x %d %dx%dmm (%dx%ddpi)", displaySpec.toLatin1().data(),
        w, h, d, physWidth, physHeight, qRound(dw*25.4/physWidth), qRound(dh*25.4/physHeight) );

    size = lstep * h;
    mapsize = size;
    screencols = d_ptr->hdr->numcols;
    memcpy(screenclut, d_ptr->hdr->clut, sizeof(QRgb) * screencols);

    connected = this;

    return true;
}