Пример #1
0
bool StopSpam::processMuc(int account, const QDomElement& stanza) {
	if(stanza.tagName() == "presence") {
		QStringList jidList = stanza.attribute("from").split("/");
		int i =  mucUsers_.size();
		if(findMuc(jidList.first(),jidList.last(), i)) {
			MucUser &mu = mucUsers_[i];
			QDomNodeList nodeList = stanza.elementsByTagName("x");
			for(int i = nodeList.size(); i> 0;) {
				QDomNode node = nodeList.at(--i).firstChild();
				while(!node.isNull()) {
					QDomElement item = node.toElement();
					if(item.tagName() == "item") {
						mu.affiliation = item.attribute("affiliation");
						mu.role = item.attribute("role");
						mu.jid = item.attribute("jid");
						break;
					}
					node = node.nextSibling();
				}
			}
		}
		else {
			MucUser mu;
			mu.mucJid = jidList.first();
			mu.nick = jidList.last();
			QDomNodeList nodeList = stanza.elementsByTagName("x");
			for(int i = nodeList.size(); i> 0;) {
				QDomNode node = nodeList.at(--i).firstChild();
				while(!node.isNull()) {
					QDomElement item = node.toElement();
					if(item.tagName() == "item") {
						mu.affiliation = item.attribute("affiliation");
						mu.role = item.attribute("role");
						mu.jid = item.attribute("jid");
						break;
					}
					node = node.nextSibling();
				}
			}
			mucUsers_ << mu;
		}
	}
	else if(stanza.tagName() == "message" && stanza.attribute("type") == "chat") {
		QDomElement subj = stanza.firstChildElement("subject");
		if (subj.text() == "StopSpam" || subj.text() == "StopSpam Question") return false;

		QString valF = stanza.attribute("from");
		if (contactInfo->isConference(account, valF)) return false;

		MucUser mu;
		QStringList jidList = valF.split("/");
		int i =  mucUsers_.size();
		if(findMuc(jidList.first(),jidList.last(), i)) {
			mu = mucUsers_[i];
		} else {
			mu.affiliation = "";
			mu.jid = "";
			mu.mucJid = "";
			mu.nick = "";
			mu.role = "";
		}

		bool find = false;

		if(mu.affiliation == "owner" && !Owner)
			find = true;
		else if( mu.affiliation == "admin" && !Admin)
			find = true;
		else if(mu.affiliation == "none" && !None)
			find = true;
		else if(mu.affiliation == "member" && !Member)
			find = true;
		if(find)
			return false;

		if(mu.role == "moderator" && !Moder)
			find = true;
		else if(mu.role == "participant" && !Participant)
			find = true;
		else if(mu.role == "visitor" && !Visitor)
			find = true;
		if(find)
			return false;

		QStringList UnblockedJids = Unblocked.split("\n");
		if(UnblockedJids.contains(valF, Qt::CaseInsensitive))
			return false;

		for(int i = 0; i < Jids.size(); i++) {
			QString jid_ = Jids.at(i);
			if(jid_.isEmpty())
				continue;
			if(mu.jid.contains(jid_, Qt::CaseInsensitive)
				|| mu.nick.contains(jid_, Qt::CaseInsensitive)
				|| mu.mucJid.contains(jid_, Qt::CaseInsensitive)) {
				if(!selected[i].toBool())
					return false;
				break;
			}
		}

		QDomElement Body = stanza.firstChildElement("body");
		if(Body.isNull())
			return false;

		if(BlockAll) {
			updateCounter(stanza, false);

			if(EnableBlockAllMes)
				stanzaHost->sendMessage(account, valF,  BlockAllMes, "StopSpam", "chat");

			return true;
		}

		QString BodyText = Body.text();
		if(BodyText == Answer) {
			Unblocked += valF + "\n";
			QVariant vUnblocked(Unblocked);
			psiOptions->setPluginOption(constUnblocked, vUnblocked);
			psiOptions->setPluginOption(constLastUnblock, QVariant(QDate::currentDate().toString("yyyyMMdd")));
			stanzaHost->sendMessage(account, valF,  Congratulation, "StopSpam", "chat");
			updateCounter(stanza, true);
			return true;
		}
		else {
			int i = BlockedJids.size();
			if(findAcc(account, valF, i)) {
				Blocked &B = BlockedJids[i];
				if(B.count < Times) {
					stanzaHost->sendMessage(account, valF,  Question, "StopSpam Question", "chat");
					updateCounter(stanza, false);
					B.count++;
					B.LastMes = QDateTime::currentDateTime();
					return true;
				}
				else {
					if(QDateTime::currentDateTime().secsTo(B.LastMes) >= -ResetTime*60) {
						updateCounter(stanza, false);
						return true;
					}
					else {
						B.count = 1;
						B.LastMes = QDateTime::currentDateTime();
						stanzaHost->sendMessage(account, valF,  Question, "StopSpam Question", "chat");
						updateCounter(stanza, false);
						return true;
					}
				}
			}
			else {
				Blocked B = { account, valF, 1, QDateTime::currentDateTime() };
				BlockedJids << B;
				stanzaHost->sendMessage(account, valF,  Question, "StopSpam Question", "chat");
				updateCounter(stanza, false);
				return true;
			}
		}
	}

	return false;
}
Пример #2
0
int main(int argc, char *argv[])
{
  QCoreApplication application(argc, argv);
  application.addLibraryPath(".");

  QTextStream out(stdout, QIODevice::WriteOnly);

  if (application.argc() > 1)
  {
    QString databaseURL;
    QString username;
    QString passwd;
    QString arguments;

    QString xml_file = QString::null;
    int     report_grade = 0;

    for (int counter = 1; counter < application.argc(); counter++)
    {
      QString arguments(application.argv()[counter]);

      if (arguments.startsWith("-databaseURL=", Qt::CaseInsensitive))
        databaseURL = arguments.right(arguments.length() - 13);
      else if (arguments.startsWith("-username="******"-passwd=", Qt::CaseInsensitive))
        passwd = arguments.right(arguments.length() - 8);
      else if (arguments.startsWith("-f=", Qt::CaseInsensitive))
        xml_file = arguments.right(arguments.length() - 3);
      else if (arguments.startsWith("-grade=", Qt::CaseInsensitive))
        report_grade = (arguments.right(arguments.length() - 7)).toInt();
      else if(!arguments.startsWith("-"))
        xml_file = arguments;
    }

    QString report_name = QString::null;
    QString report_desc = QString::null;
    QString report_src  = QString::null;

    if(xml_file != "") {
        QFile file(xml_file);
        if(file.open( QIODevice::ReadOnly )) {
            QDomDocument doc;
            QString errMsg;
            int errLine, errCol;
            if(doc.setContent(&file, &errMsg, &errLine, &errCol)) {
                QDomElement root = doc.documentElement();
                if(root.tagName() == "report") {
                    for(QDomNode n = root.firstChild();
                            !n.isNull(); n = n.nextSibling() ) {
                        if(n.nodeName() == "name") {
                            report_name = n.firstChild().nodeValue();
                        } else if(n.nodeName() == "description") {
                            report_desc = n.firstChild().nodeValue();
                        }
                    }
                    report_src  = doc.toString();

                    if(report_name == "") {
                        out << "The document " << xml_file << " does not have a report name defined." << endl;
                    }
                } else {
                    out << "XML Document " << xml_file << " does not have root node of report." << endl;
                }
            } else {
                out << "Error parsing file " << xml_file << ": " << errMsg << " on line " << errLine << " column " << errCol << endl;
            }
        } else {
            out << "Could not open the specified file: " << xml_file << endl;
        }
    } else {
        out << "You must specify an XML file to load by using the -f= parameter." << endl;
    }

    if(report_name == "" || report_src == "") {
        // an error message already should have been displayed to the user
        exit(-1);
    }

    if (  (databaseURL != "") &&
          (username != "")    &&
          (passwd != "")          ) {
      QSqlDatabase db;

// Open the Database Driver
      db = databaseFromURL( databaseURL );
      if (!db.isValid())
      {
        out << "Could not load the specified database driver." << endl;
        exit(-1);
      }

//  Try to connect to the Database
      db.setUserName(username);
      db.setPassword(passwd);
      if (!db.open())
      {
        out << "Host=" << db.hostName() << ", Database=" << db.databaseName() << ", port=" << db.port() << endl;
        out << "Could not log into database.  System Error: "
            << db.lastError().text() << endl;
        exit(-1);
      }

      QSqlQuery().exec(getSqlFromTag("fmt05", db.driverName()));		// MANU

      // first we need to determine if there is already a report in the database of the same
      // name and if so then we will perform an update instead of an insert
      QSqlQuery qry;
      qry.prepare(getSqlFromTag("fmt09", db.driverName()));		// MANU
      qry.bindValue(":report_name", report_name);
      qry.bindValue(":report_grade", report_grade);
      qry.exec();
      QSqlQuery query;
      if(qry.first()) {
          // update
          query.prepare(getSqlFromTag("fmt10", db.driverName()));		// MANU
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_id", qry.value(0));
          query.bindValue(":report_name", report_name);
      } else {
          // insert
          query.prepare(getSqlFromTag("fmt11", db.driverName()));		// MANU
          query.bindValue(":report_name", report_name);
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_grade", report_grade);
      }
      
      if(!query.exec()) {
          QSqlError err = query.lastError();
          out << "Error: " << err.driverText() << endl
              << "\t" << err.databaseText() << endl;
          exit(-1);
      }
      
    }
    else if (databaseURL == "")
      out << "You must specify a Database URL by using the -databaseURL= parameter." << endl;
    else if (username == "")
      out << "You must specify a Database Username by using the -username= parameter." << endl;
    else if (passwd == "")
      out << "You must specify a Database Password by using the -passwd= parameter." << endl;
  }
  else
    out << "Usage: import -databaseURL='$' -username='******' -passwd='$' -grade=# -f='$'" << endl;
  return 0;
}
Пример #3
0
void ShapePlug::parseGroup(QDomNode &DOC)
{
	QString tmp = "";
	QString FillCol = "White";
	QString StrokeCol = "Black";
	QString defFillCol = "White";
	QString defStrokeCol = "Black";
	QColor stroke = Qt::black;
	QColor fill = Qt::white;
	Qt::PenStyle Dash = Qt::SolidLine;
	Qt::PenCapStyle LineEnd = Qt::FlatCap;
	Qt::PenJoinStyle LineJoin = Qt::MiterJoin;
	int fillStyle = 1;
	double strokewidth = 0.1;
	bool poly = false;
	while(!DOC.isNull())
	{
		double x1, y1, x2, y2;
		StrokeCol = defStrokeCol;
		FillCol = defFillCol;
		stroke = Qt::black;
		fill = Qt::white;
		fillStyle = 1;
		strokewidth = 1.0;
		Dash = Qt::SolidLine;
		LineEnd = Qt::FlatCap;
		LineJoin = Qt::MiterJoin;
		FPointArray PoLine;
		PoLine.resize(0);
		QDomElement pg = DOC.toElement();
		QString STag = pg.tagName();
		QString style = pg.attribute( "style", "" ).simplified();
		if (style.isEmpty())
			style = pg.attribute( "svg:style", "" ).simplified();
		QStringList substyles = style.split(';', QString::SkipEmptyParts);
		for( QStringList::Iterator it = substyles.begin(); it != substyles.end(); ++it )
		{
			QStringList substyle = (*it).split(':', QString::SkipEmptyParts);
			QString command(substyle[0].trimmed());
			QString params(substyle[1].trimmed());
			if (command == "fill")
			{
				if (!((params == "foreground") || (params == "background") || (params == "fg") || (params == "bg") || (params == "none") || (params == "default") || (params == "inverse")))
				{
					if (params == "nofill")
						FillCol = CommonStrings::None;
					else
					{
						fill.setNamedColor( params );
						FillCol = "FromDia"+fill.name();
						ScColor tmp;
						tmp.fromQColor(fill);
						tmp.setSpotColor(false);
						tmp.setRegistrationColor(false);
						QString fNam = m_Doc->PageColors.tryAddColor(FillCol, tmp);
						if (fNam == FillCol)
							importedColors.append(FillCol);
						FillCol = fNam;
					}
				}
			}
			else if (command == "stroke")
			{
				if (!((params == "foreground") || (params == "background") || (params == "fg") || (params == "bg") || (params == "none") || (params == "default")) || (params == "inverse"))
				{
					stroke.setNamedColor( params );
					StrokeCol = "FromDia"+stroke.name();
					ScColor tmp;
					tmp.fromQColor(stroke);
					tmp.setSpotColor(false);
					tmp.setRegistrationColor(false);
					QString fNam = m_Doc->PageColors.tryAddColor(StrokeCol, tmp);
					if (fNam == StrokeCol)
						importedColors.append(StrokeCol);
					StrokeCol = fNam;
				}
			}
			else if (command == "stroke-width")
				strokewidth = ScCLocale::toDoubleC(params);
			else if( command == "stroke-linejoin" )
			{
				if( params == "miter" )
					LineJoin = Qt::MiterJoin;
				else if( params == "round" )
					LineJoin = Qt::RoundJoin;
				else if( params == "bevel" )
					LineJoin = Qt::BevelJoin;
			}
			else if( command == "stroke-linecap" )
			{
				if( params == "butt" )
					LineEnd = Qt::FlatCap;
				else if( params == "round" )
					LineEnd = Qt::RoundCap;
				else if( params == "square" )
					LineEnd = Qt::SquareCap;
			}
		}
		if (STag == "svg:line")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("x1")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("y1")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("x2")) * Conversion;
			y2 = ScCLocale::toDoubleC(pg.attribute("y2")) * Conversion;
			PoLine.addPoint(x1, y1);
			PoLine.addPoint(x1, y1);
			PoLine.addPoint(x2, y2);
			PoLine.addPoint(x2, y2);
			int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, CommonStrings::None, StrokeCol, true);
			m_Doc->Items->at(z)->PoLine = PoLine.copy();
			finishItem(m_Doc->Items->at(z));
		}
		else if (STag == "svg:rect")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("x")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("y")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("width")) * Conversion;
			y2 = ScCLocale::toDoubleC(pg.attribute("height")) * Conversion;
			int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, baseX + x1, baseY + y1, x2, y2, strokewidth, FillCol, StrokeCol, true);
			m_Doc->Items->at(z)->setLineJoin(LineJoin);
			m_Doc->Items->at(z)->setLineEnd(LineEnd);
			finishItem(m_Doc->Items->at(z));
		}
		else if ((STag == "svg:polygon") || (STag == "svg:polyline"))
		{
			bool bFirst = true;
			double x = 0.0;
			double y = 0.0;
			QString points = pg.attribute( "points" ).simplified().replace(',', " ");
			QStringList pointList = points.split(' ', QString::SkipEmptyParts);
			FirstM = true;
			for( QStringList::Iterator it = pointList.begin(); it != pointList.end(); it++ )
			{
				if( bFirst )
				{
					x = ScCLocale::toDoubleC(*(it++));
					y = ScCLocale::toDoubleC(*it);
					svgMoveTo(x * Conversion, y * Conversion);
					bFirst = false;
					WasM = true;
				}
				else
				{
					x = ScCLocale::toDoubleC(*(it++));
					y = ScCLocale::toDoubleC(*it);
					svgLineTo(&PoLine, x * Conversion, y * Conversion);
				}
			}
			if (STag == "svg:polygon")
				svgClosePath(&PoLine);
			if (PoLine.size() < 4)
			{
				DOC = DOC.nextSibling();
				continue;
			}
			int z;
			if (STag == "svg:polygon")
				z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, FillCol, StrokeCol, true);
			else
				z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, CommonStrings::None, StrokeCol, true);
			m_Doc->Items->at(z)->PoLine = PoLine.copy();
			finishItem(m_Doc->Items->at(z));
		}
		else if ((STag == "svg:circle") || (STag == "svg:ellipse"))
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("cx")) * Conversion - x1;
			y2 = ScCLocale::toDoubleC(pg.attribute("cy")) * Conversion - y1;
			x1 *= 2.0;
			y1 *= 2.0;
			int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, baseX + x1, baseY + y1, x2, y2, strokewidth, FillCol, StrokeCol, true);
			m_Doc->Items->at(z)->setLineJoin(LineJoin);
			m_Doc->Items->at(z)->setLineEnd(LineEnd);
			finishItem(m_Doc->Items->at(z));
		}
		else if (STag == "svg:path")
		{
			poly = parseSVG( pg.attribute( "d" ), &PoLine );
			if (PoLine.size() < 4)
			{
				DOC = DOC.nextSibling();
				continue;
			}
			int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, FillCol, StrokeCol, true);
			m_Doc->Items->at(z)->PoLine = PoLine.copy();
			finishItem(m_Doc->Items->at(z));
		}
		else if (STag == "svg:g")
		{
			int z = m_Doc->itemAdd(PageItem::Group, PageItem::Rectangle, baseX, baseX, 1, 1, 0, CommonStrings::None, CommonStrings::None, true);
			PageItem *neu = m_Doc->Items->at(z);
			Elements.append(neu);
			if (groupStack.count() > 0)
				groupStack.top().append(neu);
			QList<PageItem*> gElements;
			groupStack.push(gElements);
			QDomNode child = DOC.firstChild();
			parseGroup(child);
			if (gElements.count() == 0)
			{
				groupStack.pop();
				Elements.removeAll(neu);
				groupStack.top().removeAll(neu);
				Selection tmpSelection(m_Doc, false);
				tmpSelection.addItem(neu);
				m_Doc->itemSelection_DeleteItem(&tmpSelection);
				m_Doc->renumberItemsInListOrder();
			}
			else
			{
				QList<PageItem*> gElem = groupStack.pop();
				double minx =  std::numeric_limits<double>::max();
				double miny =  std::numeric_limits<double>::max();
				double maxx = -std::numeric_limits<double>::max();
				double maxy = -std::numeric_limits<double>::max();
				for (int gr = 0; gr < gElements.count(); ++gr)
				{
					PageItem* currItem = gElem.at(gr);
					double x1, x2, y1, y2;
					currItem->getVisualBoundingRect(&x1, &y1, &x2, &y2);
					minx = qMin(minx, x1);
					miny = qMin(miny, y1);
					maxx = qMax(maxx, x2);
					maxy = qMax(maxy, y2);
				}
				double gx = minx;
				double gy = miny;
				double gw = maxx - minx;
				double gh = maxy - miny;
				neu->setXYPos(gx, gy, true);
				neu->setWidthHeight(gw, gh, true);
				neu->SetRectFrame();
				neu->Clip = FlattenPath(neu->PoLine, neu->Segments);
				neu->setItemName( tr("Group%1").arg(m_Doc->GroupCounter));
				neu->AutoName = false;
				neu->gXpos = neu->xPos() - gx;
				neu->gYpos = neu->yPos() - gy;
				neu->groupWidth = gw;
				neu->groupHeight = gh;
				for (int gr = 0; gr < gElem.count(); ++gr)
				{
					PageItem* currItem = gElem.at(gr);
					currItem->gXpos = currItem->xPos() - gx;
					currItem->gYpos = currItem->yPos() - gy;
					currItem->gWidth = gw;
					currItem->gHeight = gh;
					neu->groupItemList.append(currItem);
					m_Doc->Items->removeAll(currItem);
					Elements.removeAll(currItem);
				}
				neu->setRedrawBounding();
				neu->setTextFlowMode(PageItem::TextFlowDisabled);
				m_Doc->GroupCounter++;
				m_Doc->renumberItemsInListOrder();
			}
		}
		DOC = DOC.nextSibling();
	}
}
Пример #4
0
bool VCProperties::loadProperties(const QDomElement* root)
{
	QDomElement tag;
	QDomNode node;
	QString str;

	Q_ASSERT(root != NULL);

	if (root->tagName() != KXMLQLCVCProperties)
	{
		qDebug() << "Virtual console properties node not found!";
		return false;
	}

	node = root->firstChild();
	while (node.isNull() == false)
	{
		tag = node.toElement();
		if (tag.tagName() == KXMLQLCVCPropertiesGrid)
		{
			/* Grid X resolution */
			str = tag.attribute(KXMLQLCVCPropertiesGridXResolution);
			setGridX(str.toInt());

			/* Grid Y resolution */
			str = tag.attribute(KXMLQLCVCPropertiesGridYResolution);
			setGridY(str.toInt());

			/* Grid enabled */
			str = tag.attribute(KXMLQLCVCPropertiesGridEnabled);
			if (str == KXMLQLCTrue)
				setGridEnabled(true);
			else
				setGridEnabled(false);
		}
		else if (tag.tagName() == KXMLQLCVCPropertiesKeyboard)
		{
			/* Keyboard grab */
			str = tag.attribute(KXMLQLCVCPropertiesKeyboardGrab);
			if (str == KXMLQLCTrue)
				setGrabKeyboard(true);
			else
				setGrabKeyboard(false);

			/* Key repeat */
			str = tag.attribute(KXMLQLCVCPropertiesKeyboardRepeatOff);
			if (str == KXMLQLCTrue)
				setKeyRepeatOff(true);
			else
				setKeyRepeatOff(false);
		}
		else if (tag.tagName() == KXMLQLCVCPropertiesDefaultSlider)
		{
			t_bus_value low = 0;
			t_bus_value high = 10;
			t_input_universe universe = KInputUniverseInvalid;
			t_input_channel channel = KInputChannelInvalid;
			QDomElement subtag;

			/* Bus low limit */
			str = tag.attribute(KXMLQLCVCPropertiesLowLimit);
			if (str.isNull() == false)
				low = t_bus_value(str.toInt());

			/* Bus high limit */
			str = tag.attribute(KXMLQLCVCPropertiesHighLimit);
			if (str.isNull() == false)
				high = t_bus_value(str.toInt());

			/* Sliders' visibility (on by default) */
			str = tag.attribute(KXMLQLCVCPropertiesDefaultSliderVisible);
			if (str == KXMLQLCFalse)
				setSlidersVisible(false);
			else
				setSlidersVisible(true);

			/* External input */
			subtag = tag.firstChild().toElement();
			if (subtag.isNull() == false &&
			    subtag.tagName() == KXMLQLCVCPropertiesInput)
			{
				/* Universe */
				str = subtag.attribute(KXMLQLCVCPropertiesInputUniverse);
				if (str.isNull() == false)
					universe = str.toInt();

				/* Channel */
				str = subtag.attribute(KXMLQLCVCPropertiesInputChannel);
				if (str.isNull() == false)
					channel = str.toInt();
			}

			/* Set the gathered properties to the correct slider */
			if (tag.attribute(KXMLQLCBusRole) == KXMLQLCBusFade)
			{
				setFadeLimits(low, high);
				setFadeInputSource(universe, channel);
			}
			else
			{
				setHoldLimits(low, high);
				setHoldInputSource(universe, channel);
			}
		}
		else if (tag.tagName() == KXMLQLCWidgetProperties)
		{
			QLCWidgetProperties::loadXML(&tag);
		}
		else
		{
			qDebug() << "Unknown virtual console property tag:"
				 << tag.tagName();
		}

		/* Next node */
		node = node.nextSibling();
	}

	return true;
}
Пример #5
0
bool VCSpeedDialPreset::loadXML(const QDomElement &root)
{
    QDomNode node;
    QDomElement tag;

    if (root.tagName() != KXMLQLCVCSpeedDialPreset)
    {
        qWarning() << Q_FUNC_INFO << "Speed Dial Preset node not found";
        return false;
    }

    if (root.hasAttribute(KXMLQLCVCSpeedDialPresetID) == false)
    {
        qWarning() << Q_FUNC_INFO << "Speed Dial Preset ID not found";
        return false;
    }

    m_id = root.attribute(KXMLQLCVCSpeedDialPresetID).toUInt();

    /* Children */
    node = root.firstChild();
    while (node.isNull() == false)
    {
        tag = node.toElement();
        if (tag.tagName() == KXMLQLCVCSpeedDialPresetName)
        {
            m_name = tag.text();
        }
        else if (tag.tagName() == KXMLQLCVCSpeedDialPresetShowName)
        {
            m_showName = (tag.text() == KXMLQLCTrue);
        }
        else if (tag.tagName() == KXMLQLCVCSpeedDialPresetValue)
        {
            m_value = tag.text().toInt();
        }
        else if (tag.tagName() == KXMLQLCVCSpeedDialPresetInput)
        {
            if (tag.hasAttribute(KXMLQLCVCSpeedDialPresetInputUniverse) &&
                tag.hasAttribute(KXMLQLCVCSpeedDialPresetInputChannel))
            {
                quint32 uni = tag.attribute(KXMLQLCVCSpeedDialPresetInputUniverse).toUInt();
                quint32 ch = tag.attribute(KXMLQLCVCSpeedDialPresetInputChannel).toUInt();
                m_inputSource = QSharedPointer<QLCInputSource>(new QLCInputSource(uni, ch));

                uchar min = 0, max = UCHAR_MAX;
                if (tag.hasAttribute(KXMLQLCVCWidgetInputLowerValue))
                    min = uchar(tag.attribute(KXMLQLCVCWidgetInputLowerValue).toUInt());
                if (tag.hasAttribute(KXMLQLCVCWidgetInputUpperValue))
                    max = uchar(tag.attribute(KXMLQLCVCWidgetInputUpperValue).toUInt());
                m_inputSource->setRange(min, max);
            }
        }
        else if (tag.tagName() == KXMLQLCVCSpeedDialPresetKey)
        {
            m_keySequence = VCWidget::stripKeySequence(QKeySequence(tag.text()));
        }
        else
        {
            qWarning() << Q_FUNC_INFO << "Unknown VCSpeedDialPreset tag:" << tag.tagName();
        }

        node = node.nextSibling();
    }

    return true;
}
Пример #6
0
static bool loadDetailsFromXML(const QString &filename, FileDetails *details)
{
    QDomDocument doc("mydocument");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return false;

    if (!doc.setContent(&file))
    {
        file.close();
        return false;
    }
    file.close();

    QString docType = doc.doctype().name();

    if (docType == "MYTHARCHIVEITEM")
    {
        QDomNodeList itemNodeList = doc.elementsByTagName("item");
        QString type, dbVersion;

        if (itemNodeList.count() < 1)
        {
            LOG(VB_GENERAL, LOG_ERR,
                "Couldn't find an 'item' element in XML file");
            return false;
        }

        QDomNode n = itemNodeList.item(0);
        QDomElement e = n.toElement();
        type = e.attribute("type");
        dbVersion = e.attribute("databaseversion");
        if (type == "recording")
        {
            QDomNodeList nodeList = e.elementsByTagName("recorded");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'recorded' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                        details->title = e.text();

                    if (e.tagName() == "subtitle")
                        details->subtitle = e.text();

                    if (e.tagName() == "starttime")
                        details->startTime = MythDate::fromString(e.text());

                    if (e.tagName() == "description")
                        details->description = e.text();
                }
                n = n.nextSibling();
            }

            // get channel info
            n = itemNodeList.item(0);
            e = n.toElement();
            nodeList = e.elementsByTagName("channel");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'channel' element in XML file");
                details->chanID = "";
                details->chanNo = "";
                details->chanName = "";
                details->callsign =  "";
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            details->chanID = e.attribute("chanid");
            details->chanNo = e.attribute("channum");
            details->chanName = e.attribute("name");
            details->callsign =  e.attribute("callsign");
            return true;
        }
        else if (type == "video")
        {
            QDomNodeList nodeList = e.elementsByTagName("videometadata");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'videometadata' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                    {
                        details->title = e.text();
                        details->subtitle = "";
                        details->startTime = QDateTime();
                    }

                    if (e.tagName() == "plot")
                    {
                        details->description = e.text();
                    }
                }
                n = n.nextSibling();
            }

            details->chanID = "N/A";
            details->chanNo = "N/A";
            details->chanName = "N/A";
            details->callsign = "N/A";

            return true;
        }
    }

    return false;
}
Пример #7
0
void Fixture_Test::save()
{
    QLCFixtureDef* fixtureDef;
    fixtureDef = m_doc->fixtureDefCache()->fixtureDef("Martin", "MAC250+");
    Q_ASSERT(fixtureDef != NULL);

    QLCFixtureMode* fixtureMode;
    fixtureMode = fixtureDef->modes().at(0);
    Q_ASSERT(fixtureMode != NULL);

    Fixture fxi(this);
    fxi.setID(1337);
    fxi.setName("Test Fixture");
    fxi.setUniverse(2);
    fxi.setAddress(438);
    fxi.setFixtureDefinition(fixtureDef, fixtureMode);

    QDomDocument doc;
    QDomElement root = doc.createElement("TestRoot");
    QVERIFY(fxi.saveXML(&doc, &root) == true);
    QDomNode node = root.firstChild();
    QVERIFY(node.toElement().tagName() == "Fixture");

    bool manufacturer = false, model = false, mode = false, name = false,
                                       channels = false, universe = false, address = false, id = false;

    node = node.firstChild();
    while (node.isNull() == false)
    {
        QDomElement e = node.toElement();

        if (e.tagName() == "Manufacturer")
        {
            QVERIFY(e.text() == "Martin");
            manufacturer = true;
        }
        else if (e.tagName() == "Model")
        {
            QVERIFY(e.text() == "MAC250+");
            model = true;
        }
        else if (e.tagName() == "Mode")
        {
            QVERIFY(e.text() == fixtureMode->name());
            mode = true;
        }
        else if (e.tagName() == "ID")
        {
            QVERIFY(e.text() == "1337");
            id = true;
        }
        else if (e.tagName() == "Name")
        {
            QVERIFY(e.text() == "Test Fixture");
            name = true;
        }
        else if (e.tagName() == "Universe")
        {
            QVERIFY(e.text() == "2");
            universe = true;
        }
        else if (e.tagName() == "Address")
        {
            QVERIFY(e.text() == "438");
            address = true;
        }
        else if (e.tagName() == "Channels")
        {
            QVERIFY(e.text().toInt()
                    == fixtureMode->channels().count());
            channels = true;
        }
        else
        {
            QFAIL(QString("Unexpected tag: %1").arg(e.tagName())
                  .toLatin1());
        }

        node = node.nextSibling();
    }

    QVERIFY(manufacturer == true);
    QVERIFY(model == true);
    QVERIFY(mode == true);
    QVERIFY(id == true);
    QVERIFY(name == true);
    QVERIFY(universe == true);
    QVERIFY(address == true);
    QVERIFY(channels == true);
}
Пример #8
0
void QERecipe::buttonSaveClicked()
{

    QDomElement rootElement;
    QDomElement recipeElement;
    QDomElement processVariableElement;
    QDomNode rootNode;
    _Field *fieldInfo;
    QString currentName;
    QString name;
    int count;
    int i;


    currentName = qComboBoxRecipeList->currentText();

    if (QMessageBox::question(this, "Info", "Do you want to save the values in recipe '" + currentName + "'?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
    {
        count = 0;
        rootElement = document.documentElement();
        if (rootElement.tagName() == "epicsqt")
        {
            rootNode = rootElement.firstChild();
            while (rootNode.isNull() == false)
            {
                recipeElement = rootNode.toElement();
                if (recipeElement.tagName() == "recipe")
                {
                    if (recipeElement.attribute("name").isEmpty())
                    {
                        name= "Recipe #" + QString::number(count);
                        count++;
                    }
                    else
                    {
                        name = recipeElement.attribute("name");
                    }
                    if (currentName.compare(name) == 0)
                    {
                        break;
                    }
                }
                rootNode = rootNode.nextSibling();
            }
        }

        while (recipeElement.hasChildNodes())
        {
            recipeElement.removeChild(recipeElement.lastChild());
        }

        for(i = 0; i < qEConfiguredLayoutRecipeFields->currentFieldList.size(); i++)
        {
            fieldInfo = qEConfiguredLayoutRecipeFields->currentFieldList.at(i);
            processVariableElement = document.createElement("processvariable");
            processVariableElement.setAttribute("name", fieldInfo->getProcessVariable());
            if (fieldInfo->getType() == BUTTON)
            {
            }
            else if (fieldInfo->getType() == LABEL)
            {
            }
            else if (fieldInfo->getType() == SPINBOX)
            {
                processVariableElement.setAttribute("value", ((QESpinBox *) fieldInfo->qeWidget)->text());
            }
            else if (fieldInfo->getType() == COMBOBOX)
            {
                processVariableElement.setAttribute("value", ((QEComboBox *) fieldInfo->qeWidget)->currentText());
            }
            else
            {
                processVariableElement.setAttribute("value", ((QELineEdit *) fieldInfo->qeWidget)->text());
            }
            recipeElement.appendChild(processVariableElement);
        }

        if (saveRecipeList())
        {
            QMessageBox::information(this, "Info", "The recipe '" + currentName + "' was successfully saved!");
        }
        else
        {
            // TODO: restore original document if there is an error
            QMessageBox::critical(this, "Error", "Unable to save recipe '" + currentName + "' in file '" + filename + "'!");
        }
    }

}
Пример #9
0
void QERecipe::refreshRecipeList()
{

    QDomElement rootElement;
    QDomElement recipeElement;
    QDomNode rootNode;
    QString visible;
    QString tmp;
    bool flag;
    int count;
    int i;


    qComboBoxRecipeList->blockSignals(true);
    tmp = qComboBoxRecipeList->currentText();
    qComboBoxRecipeList->clear();
    rootElement = document.documentElement();
    if (rootElement.tagName() == "epicsqt")
    {
        count = 0;
        rootNode = rootElement.firstChild();
        while (rootNode.isNull() == false)
        {
            recipeElement = rootNode.toElement();
            if (recipeElement.tagName() == "recipe")
            {
                visible = recipeElement.attribute("visible").toUpper();
                if (visible.isEmpty())
                {
                    flag = true;
                }
                else
                {
                    if (visible == "USER")
                    {
                        flag = true;
                    }
                    else if (visible == "SCIENTIST")
                    {
                        flag = (currentUserType > 0);
                    }
                    else if (visible == "ENGINEER")
                    {
                        flag = (currentUserType > 1);
                    }
                    else
                    {
                        flag = false;
                    }
                }
                if (flag)
                {
                    if (recipeElement.attribute("name").isEmpty())
                    {
                        qComboBoxRecipeList->addItem("Recipe #" + QString::number(count));
                        count++;
                    }
                    else
                    {
                        qComboBoxRecipeList->addItem(recipeElement.attribute("name"));
                    }
                }
            }
            rootNode = rootNode.nextSibling();
        }
    }
    i = qComboBoxRecipeList->findText(tmp);
    if (i == -1)
    {
        qComboBoxRecipeList->setCurrentIndex(0);
    }
    else
    {
       qComboBoxRecipeList->setCurrentIndex(i);
    }
    refreshButton();
    qComboBoxRecipeList->blockSignals(false);

}
Пример #10
0
void InstrumentTrack::loadTrackSpecificSettings( const QDomElement & thisElement )
{
	silenceAllNotes( true );

	lock();

	m_volumeModel.loadSettings( thisElement, "vol" );
	m_panningModel.loadSettings( thisElement, "pan" );
	m_pitchRangeModel.loadSettings( thisElement, "pitchrange" );
	m_pitchModel.loadSettings( thisElement, "pitch" );
	m_effectChannelModel.setRange( 0, engine::fxMixer()->numChannels()-1 );
	m_effectChannelModel.loadSettings( thisElement, "fxch" );
	m_baseNoteModel.loadSettings( thisElement, "basenote" );

	// clear effect-chain just in case we load an old preset without FX-data
	m_audioPort.effects()->clear();

	QDomNode node = thisElement.firstChild();
	while( !node.isNull() )
	{
		if( node.isElement() )
		{
			if( m_soundShaping.nodeName() == node.nodeName() )
			{
				m_soundShaping.restoreState( node.toElement() );
			}
			else if( m_noteStacking.nodeName() == node.nodeName() )
			{
				m_noteStacking.restoreState( node.toElement() );
			}
			else if( m_arpeggio.nodeName() == node.nodeName() )
			{
				m_arpeggio.restoreState( node.toElement() );
			}
			else if( m_midiPort.nodeName() == node.nodeName() )
			{
				m_midiPort.restoreState( node.toElement() );
			}
			else if( m_audioPort.effects()->nodeName() == node.nodeName() )
			{
				m_audioPort.effects()->restoreState( node.toElement() );
			}
			else if( node.nodeName() == "instrument" )
			{
				delete m_instrument;
				m_instrument = NULL;
				m_instrument = Instrument::instantiate( node.toElement().attribute( "name" ), this );
				m_instrument->restoreState( node.firstChildElement() );

				emit instrumentChanged();
			}
			// compat code - if node-name doesn't match any known
			// one, we assume that it is an instrument-plugin
			// which we'll try to load
			else if( AutomationPattern::classNodeName() != node.nodeName() &&
					ControllerConnection::classNodeName() != node.nodeName() &&
					!node.toElement().hasAttribute( "id" ) )
			{
				delete m_instrument;
				m_instrument = NULL;
				m_instrument = Instrument::instantiate( node.nodeName(), this );
				if( m_instrument->nodeName() == node.nodeName() )
				{
					m_instrument->restoreState( node.toElement() );
				}
				emit instrumentChanged();
			}
		}
		node = node.nextSibling();
	}
	unlock();
}
Пример #11
0
void QERecipe::buttonNewClicked()
{

    QDomElement rootElement;
    QDomElement recipeElement;
    QDomElement processVariableElement;
    QDomNode rootNode;
    _Field *fieldInfo;
    QString currentName;
    QString name;
    QString visible;
    bool flag;
    int count;
    int i;


    do
    {
        name = QInputDialog::getText(this, "New Recipe", "Name:", QLineEdit::Normal , "", &flag);
    }
    while(flag && name.isEmpty());

    if (name.isEmpty() == false)
    {
        flag = true;
        count = 0;
        rootElement = document.documentElement();
        if (rootElement.tagName() == "epicsqt")
        {
            rootNode = rootElement.firstChild();
            while (rootNode.isNull() == false)
            {
                recipeElement = rootNode.toElement();
                if (recipeElement.tagName() == "recipe")
                {
                    if (recipeElement.attribute("name").isEmpty())
                    {
                        currentName = "Recipe #" + QString::number(count);
                        count++;
                    }
                    else
                    {
                        currentName = recipeElement.attribute("name");
                    }
                    if (currentName.compare(name) == 0)
                    {
                        flag = false;
                        break;
                    }
                }
                rootNode = rootNode.nextSibling();
            }
        }
        if (flag == false)
        {
            visible = recipeElement.attribute("visible").toUpper();
            if (visible.isEmpty())
            {
                flag = true;
            }
            else if (visible == "USER")
            {
                flag = true;
            }
            else if (visible == "SCIENTIST")
            {
                flag = (currentUserType > 0);
            }
            else if (visible == "ENGINEER")
            {
                flag = (currentUserType > 1);
            }
            else
            {
                flag = false;
            }
            if (flag)
            {
                flag = (QMessageBox::question(this, "Info", "Do you want to replace existing recipe '" + name + "'?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes);
                if (flag)
                {
                    rootElement.removeChild(rootNode);
                }
            }
            else
            {
                QMessageBox::warning(this, "Warning", "Unable to create recipe '" + name + "' since it already exists and belongs to another user type with more priviledges!");
            }
        }
        else
        {
            switch (currentUserType)
            {
                case userLevelTypes::USERLEVEL_USER:
                    visible = "USER";
                    break;
                case userLevelTypes::USERLEVEL_SCIENTIST:
                    visible = "SCIENTIST";
                    break;
                default:
                    visible = "ENGINEER";
            }
        }
        if (flag)
        {
            recipeElement = document.createElement("recipe");
            recipeElement.setAttribute("name", name);
            recipeElement.setAttribute("visible", visible);
            for(i = 0; i < qEConfiguredLayoutRecipeFields->currentFieldList.size(); i++)
            {
                fieldInfo = qEConfiguredLayoutRecipeFields->currentFieldList.at(i);
                processVariableElement = document.createElement("processvariable");
                processVariableElement.setAttribute("name", fieldInfo->getProcessVariable());
                if (fieldInfo->getType() == BUTTON)
                {
                }
                else if (fieldInfo->getType() == LABEL)
                {
                }
                else if (fieldInfo->getType() == SPINBOX)
                {
                    processVariableElement.setAttribute("value", ((QESpinBox *) fieldInfo->qeWidget)->text());
                }
                else if (fieldInfo->getType() == COMBOBOX)
                {
                    processVariableElement.setAttribute("value", ((QEComboBox *) fieldInfo->qeWidget)->currentText());
                }
                else
                {
                    processVariableElement.setAttribute("value", ((QELineEdit *) fieldInfo->qeWidget)->text());
                }
                recipeElement.appendChild(processVariableElement);
            }
            rootElement.appendChild(recipeElement);
            if (saveRecipeList())
            {
                QMessageBox::information(this, "Info", "The recipe '" + name + "' was successfully created!");
            }
            else
            {
                // TODO: restore original document if there is an error
                //rootElement.removeChild(recipeElement);
                QMessageBox::critical(this, "Error", "Unable to create recipe '" + name + "' in file '" + filename + "'!");
            }
        }
    }

}
Пример #12
0
void RenderWindow::setDocument(const QDomDocument & doc)
{
  QDomElement root = doc.documentElement();
  if(root.tagName() != "report")
  {
    QMessageBox::critical(this, tr("Not a Valid Report"),
      tr("The report definition does not appear to be a valid report."
         "\n\nThe root node is not 'report'."));
    return;
  }

  _doc = doc;
  _reportInfo->setEnabled(true);

  _reportName->setText(QString::null);
  _reportTitle->setText(QString::null);
  _reportDescription->setText(QString::null);
  for(QDomNode n = root.firstChild(); !n.isNull(); n = n.nextSibling())
  {
    if(n.nodeName() == "name")
      _reportName->setText(n.firstChild().nodeValue());
    else if(n.nodeName() == "title")
      _reportTitle->setText(n.firstChild().nodeValue());
    else if(n.nodeName() == "description")
      _reportDescription->setText(n.firstChild().nodeValue());
    else if(n.nodeName() == "parameter")
    {
      QDomElement elemSource = n.toElement();
      ORParameter param;

      param.name = elemSource.attribute("name");
      if(param.name.isEmpty())
        continue;
    
      param.type = elemSource.attribute("type");
      param.defaultValue  = elemSource.attribute("default");
      param.active = (elemSource.attribute("active") == "true");
      param.listtype = elemSource.attribute("listtype");
      
      QList<QPair<QString,QString> > pairs;
      if(param.listtype.isEmpty())
        param.description = elemSource.text();
      else
      {
        QDomNodeList section = elemSource.childNodes();
        for(int nodeCounter = 0; nodeCounter < section.count(); nodeCounter++)
        {
          QDomElement elemThis = section.item(nodeCounter).toElement();
          if(elemThis.tagName() == "description")
            param.description = elemThis.text();
          else if(elemThis.tagName() == "query")
            param.query = elemThis.text();
          else if(elemThis.tagName() == "item")
            param.values.append(qMakePair(elemThis.attribute("value"), elemThis.text()));
          else
            qDebug("While parsing parameter encountered an unknown element: %s",elemThis.tagName().toLatin1().data());
        }
      }
      QVariant defaultVar;
      if(!param.defaultValue.isEmpty())
        defaultVar = QVariant(param.defaultValue);
      if("integer" == param.type)
        defaultVar = defaultVar.toInt();
      else if("double" == param.type)
        defaultVar = defaultVar.toDouble();
      else if("bool" == param.type)
        defaultVar = QVariant(defaultVar.toBool());
      else
        defaultVar = defaultVar.toString();
      updateParam(param.name, defaultVar, param.active);
      QList<QPair<QString, QString> > list;
      if("static" == param.listtype)
        list = param.values;
      else if("dynamic" == param.listtype && !param.query.isEmpty())
      {
		//qDebug() << "RenderWindow::setDocument :" << param.query;			// MANU
        QSqlQuery qry(param.query);
        while(qry.next())
          list.append(qMakePair(qry.value(0).toString(), qry.value(1).toString()));
      }
      if(!list.isEmpty())
        _lists.insert(param.name, list);
    }
  }
}
Пример #13
0
SVNHandler::FileStatus SVNHandler::fstatus( const QString& filename ) const
{
  // no valid repository
  if ( !_isPORepository )
    return NO_REPOSITORY;

  QString fn( filename );
  fn = fn.remove( QRegExp( "/$" ) );

  QFileInfo info( fn );

  // check if '.svn/entries' exists.
  QFile entries( info.dir( true ).path( ) + "/.svn/entries" );

  if ( !entries.exists() )
    return NOT_IN_SVN;

  KProcess proc;
  SVNOutputCollector out( &proc );

  proc << "svn" << "status" << "-v" << "--xml" << info.absFilePath();

  if( !proc.start( KProcess::Block, KProcess::Stdout ) )
    return ERROR_IN_WC;

  QDomDocument doc;
  QString errorMsg;
  int errorLine, errorCol;
  QDomNodeList nodelist;
  QDomNode node;
  QDomElement entry, wcStatus;

  // Parse the output.
  if ( !doc.setContent( out.getOutput(), &errorMsg, &errorLine, &errorCol ) ) {
    kdDebug(8109) << "Cannot parse \"svn status -v --xml\" output for"
        << filename << endl << "Line: " << errorLine << " Column: "
        << errorCol << " Error: " << errorMsg << endl;
    goto no_status_xml;
  }

  // There should be only one "entry" element. If it doesn't exist, path
  // isn't repo path at all.
  nodelist = doc.elementsByTagName("entry");
  if (nodelist.count() < 1)
    return NOT_IN_SVN;

  entry = nodelist.item(0).toElement();

  // Shouldn't fail, but just in case there is some weird error.
  if ( entry.attributeNode("path").value() != info.absFilePath() )
    return ERROR_IN_WC;

  for ( node = entry.firstChild(); !node.isNull(); node = node.nextSibling() ) {
    if ( !node.isElement() )
      continue;
    if (node.toElement().tagName() == "wc-status")
      break;
  }

  if ( node.isNull() )
    return ERROR_IN_WC;

  wcStatus = node.toElement();

  if ( wcStatus.attributeNode("item").value() == "normal" )
    return UP_TO_DATE;
  if ( wcStatus.attributeNode("item").value() == "modified" )
    return LOCALLY_MODIFIED;
  if ( wcStatus.attributeNode("item").value() == "conflicted" )
    return CONFLICT;
  if ( wcStatus.attributeNode("item").value() == "unversioned" )
    return NOT_IN_SVN;
  // TODO Ignored entry should have separate return value probably.
  if ( wcStatus.attributeNode("item").value() == "ignored" )
    return NOT_IN_SVN;
  if ( wcStatus.attributeNode("item").value() == "added" )
    return LOCALLY_ADDED;
  if ( wcStatus.attributeNode("item").value() == "deleted" )
    return LOCALLY_REMOVED;
  // TODO What to do with "missing", "incomplete", "replaced", "merged",
  // "obstructed", "external"? Can these appear at all in our case?

  return ERROR_IN_WC;

no_status_xml:
  if ( !entries.open( IO_ReadOnly ) )
    return ERROR_IN_WC;  // we already know that it is a repository

  // Parse the entries file
  if ( !doc.setContent( &entries, &errorMsg, &errorLine, &errorCol ) ) {
    kdDebug() << "Cannot parse .svn/entries file for " << filename << endl
        << "Line: " << errorLine << " Column: " << errorCol << " Error: " << errorMsg << endl;
    return ERROR_IN_WC;
  }
  entries.close();

  QDomElement element;
  // File name that we are searching
  const QString findName = info.fileName();
  // The entries are <entry> elements, so we have to check them
  QDomNode child = doc.documentElement().firstChild();
  for ( ; !child.isNull() ; child = child.nextSibling() )
  {
    if ( !child.isElement() )
      continue;
    element = child.toElement();
    if ( element.tagName() != "entry" ) {
      // We have another kind of element, so skip it
      // Should not happend with svn 1.1.x
      continue;
    }
    const QString name = element.attribute("name");
    if ( name == findName )
      break;
  }

  if ( child.isNull() ) {
    // We have not found an entry for the file
    return NOT_IN_SVN;
  }

  // ### TODO: should we check the attribute kind to be file and not dir?

  // ### TODO: what do copy and move add here?
  const QString onSchedule = element.attribute( "schedule" );
  if ( onSchedule == "delete" )
    return LOCALLY_REMOVED;
  else if ( onSchedule == "added" )
    return LOCALLY_ADDED;

  if ( element.hasAttribute( "conflict-new" ) || element.hasAttribute( "conflict-old" ) || element.hasAttribute( "conflict-wrk" ) ) {
    return CONFLICT;
  }

  // Note: we do not check the property time stamp
  const QString textTimeStamp( element.attribute( "text-time" ) );

  // calculate the UTC time from the file's last modified date
  struct stat st;
  lstat( QFile::encodeName(fn), &st );
  struct tm * tm_p = gmtime( &st.st_mtime );
  const int year = tm_p->tm_year + 1900;
  const int month = tm_p->tm_mon + 1;
  QString fileTime;
  fileTime.sprintf( "%04i-%02i-%02iT%02i:%02i:%02i.000000Z",
                    year, month, tm_p->tm_mday, tm_p->tm_hour, tm_p->tm_min, tm_p->tm_sec );
  //kdDebug() << "File: " << filename << " SVN time: " << textTimeStamp << " File time: " << fileTime << endl;
  if ( fileTime > textTimeStamp ) // ISO 8601 dates/times can be compared as strings if they have the exact same format.
    return LOCALLY_MODIFIED;

  return UP_TO_DATE;

}
Пример #14
0
bool VCMatrix::loadXML(const QDomElement *root)
{
    QDomNode node;
    QDomElement tag;
    QString str;

    Q_ASSERT(root != NULL);

    if (root->tagName() != KXMLQLCVCMatrix)
    {
        qWarning() << Q_FUNC_INFO << "Matrix node not found";
        return false;
    }

    /* Widget commons */
    loadXMLCommon(root);

    /* Children */
    node = root->firstChild();
    while (node.isNull() == false)
    {
        tag = node.toElement();
        if (tag.tagName() == KXMLQLCWindowState)
        {
            bool visible = false;
            int x = 0;
            int y = 0;
            int w = 0;
            int h = 0;
            loadXMLWindowState(&tag, &x, &y, &w, &h, &visible);
            setGeometry(x, y, w, h);
        }
        else if (tag.tagName() == KXMLQLCVCWidgetAppearance)
        {
            loadXMLAppearance(&tag);
        }
        else if (tag.tagName() == KXMLQLCVCMatrixFunction)
        {
            str = tag.attribute(KXMLQLCVCMatrixFunctionID);
            setFunction(str.toUInt());
            if (tag.hasAttribute(KXMLQLCVCMatrixInstantApply))
                setInstantChanges(true);
        }
        else if (tag.tagName() == KXMLQLCVCWidgetInput)
        {
            loadXMLInput(&tag);
        }
        else if(tag.tagName() == KXMLQLCVCMatrixControl)
        {
            VCMatrixControl *control = new VCMatrixControl(0xFF);
            if (control->loadXML(tag) == false)
                delete control;
            else
                addCustomControl(control);
        }
        else
        {
            qWarning() << Q_FUNC_INFO << "Unknown VCMatrix tag:" << tag.tagName();
        }

        node = node.nextSibling();
    }

    return true;
}
Пример #15
0
void TupProject::fromXml(const QString &xml)
{
    QDomDocument document;

    if (!document.setContent(xml))
        return;

    QDomElement root = document.documentElement();
    QDomNode n = root.firstChild();

    int i = 0;
    while (!n.isNull()) {
           QDomElement e = n.toElement();

           if (!e.isNull()) {
               if (e.tagName() == "project") {
                   setProjectName(e.attribute("name", projectName()));
                   QDomNode n1 = e.firstChild();
                   e = n1.toElement();

                   if (e.tagName() == "meta") {
                       QDomNode n1 = e.firstChild();

                       while (!n1.isNull()) {
                              QDomElement e1 = n1.toElement();

                              if (e1.tagName() == "author") {
                                  if (e1.firstChild().isText()) 
                                      setAuthor(e1.text());

                              } else if (e1.tagName() == "bgcolor") {
                                         if (e1.text().isEmpty())
                                             setBgColor(QColor("#ffffff"));
                                         else
                                             setBgColor(QColor(e1.text()));

                              } else if (e1.tagName() == "description") {
                                         if (e1.firstChild().isText())
                                             setDescription(e1.text());

                                } else if (e1.tagName() == "dimension") {
                                           if (e1.firstChild().isText()) {
                                               QStringList list = e1.text().split(",");
                                               int x = list.at(0).toInt();
                                               int y = list.at(1).toInt();
                                               QSize size(x,y);
                                               setDimension(size);
                                           }

                                } else if (e1.tagName() == "fps") {
                                           if (e1.firstChild().isText())
                                               setFPS(e1.text().toInt());
                                }

                                n1 = n1.nextSibling();
                          }
                   }
               }
           } 
           n = n.nextSibling();
           i++;
    }
}
Пример #16
0
void QERecipe::refreshButton()
{

    QDomElement rootElement;
    QDomElement recipeElement;
    QDomElement processVariableElement;
    QDomNode rootNode;
    _Field *fieldInfo;
    QString currentName;
    QString name;
    int count;
    int i;

    currentName = qComboBoxRecipeList->currentText();


//    qDebug() << "recipe: " + currentName;


    count = 0;
    rootElement = document.documentElement();
    if (rootElement.tagName() == "epicsqt")
    {
        rootNode = rootElement.firstChild();
        while (rootNode.isNull() == false)
        {
            recipeElement = rootNode.toElement();
            if (recipeElement.tagName() == "recipe")
            {
                if (recipeElement.attribute("name").isEmpty())
                {
                    name = "Recipe #" + QString::number(count);
                    count++;
                }
                else
                {
                    name = recipeElement.attribute("name");
                }

                if (currentName.compare(name) == 0)
                {
                    for(i = 0; i < qEConfiguredLayoutRecipeFields->currentFieldList.size(); i++)
                    {
                        fieldInfo = qEConfiguredLayoutRecipeFields->currentFieldList.at(i);

                        if (fieldInfo->getVisibility())
                        {
                            rootNode = recipeElement.firstChild();
                            while (rootNode.isNull() == false)
                            {
                                processVariableElement = rootNode.toElement();
                                if (processVariableElement.tagName() == "processvariable")
                                {
                                    if (fieldInfo->getProcessVariable() == processVariableElement.attribute("name"))
                                    {

                                        if (fieldInfo->getType() == BUTTON)
                                        {
                                        }
                                        else if (fieldInfo->getType() == LABEL)
                                        {
                                        }
                                        else if (fieldInfo->getType() == SPINBOX)
                                        {
                                            //((QESpinBox *) fieldInfo->qeWidget)->setValue((float) processVariableElement.attribute("value"));
                                        }
                                        else if (fieldInfo->getType() == COMBOBOX)
                                        {
                                            ((QEComboBox *) fieldInfo->qeWidget)->setEditText(processVariableElement.attribute("value"));
                                        }
                                        else
                                        {
                                            ((QELineEdit *) fieldInfo->qeWidget)->setText(processVariableElement.attribute("value"));
                                        }
                                        break;
                                    }
                                }
                                rootNode = rootNode.nextSibling();
                            }
                        }

                    }

                    break;
                }
            }
            rootNode = rootNode.nextSibling();
        }
    }


    qPushButtonSave->setEnabled(qComboBoxRecipeList->currentText().isEmpty() == false);
    qPushButtonDelete->setEnabled(qComboBoxRecipeList->currentText().isEmpty() == false);
    qPushButtonApply->setEnabled(qComboBoxRecipeList->currentText().isEmpty() == false);

}
RenderSettingsDialog::RenderSettingsDialog(QWidget *parent) :
		QDialog(parent, Qt::Sheet),
	ui(new Ui::RenderSettingsDialog), m_icNode(NULL), m_aiNode(NULL) {
	ui->setupUi(this);

	connect(ui->integratorBox, SIGNAL(highlighted(int)), SLOT(cbHighlighted(int)));
	connect(ui->integratorBox, SIGNAL(activated(int)), SLOT(update()));
	connect(ui->samplerBox, SIGNAL(highlighted(int)), SLOT(cbHighlighted(int)));
	connect(ui->samplerBox, SIGNAL(activated(int)), SLOT(update()));
	connect(ui->rFilterBox, SIGNAL(highlighted(int)), SLOT(cbHighlighted(int)));
	connect(ui->rFilterBox, SIGNAL(activated(int)), SLOT(update()));
	connect(ui->icBox, SIGNAL(pressed()), SLOT(chkBoxPressed()));
	connect(ui->aiBox, SIGNAL(pressed()), SLOT(chkBoxPressed()));
	connect(ui->icBox, SIGNAL(toggled(bool)), SLOT(update()));
	connect(ui->aiBox, SIGNAL(toggled(bool)), SLOT(update()));
	connect(ui->resolutionBox, SIGNAL(activated(int)), SLOT(refresh()));
	connect(ui->resolutionBox, SIGNAL(editTextChanged(const QString &)), SLOT(refresh()));

	QFile file(":/resources/docs.xml");
	if (!file.open(QIODevice::ReadOnly) || !m_document.setContent(&file))
		SLog(EError, "Unable to read the documentation file!");
	file.close();

	/* Populate the integrator, rec. filter & sampler combo box widgets */
	QDomElement docRoot = m_document.documentElement();
	for (QDomElement e = docRoot.firstChildElement("plugin"); !e.isNull();
		 e = e.nextSiblingElement("plugin")) {
		QString docString, name = e.attribute("name");
		if (!e.firstChildElement("descr").isNull()) {
			/* Create a HTML-based documentation string */
			QDomDocument helpDoc;
			QDomElement root = helpDoc.createElement("p");
			helpDoc.appendChild(root);

			for (QDomNode child = e.firstChildElement("descr").firstChild();
			   !child.isNull(); child = child.nextSibling())
			root.appendChild(helpDoc.importNode(child, true));
			docString = helpDoc.toString();
		}

		if (e.hasAttribute("show") && e.attribute("show") == "true") {
			QString type = e.attribute("type"),
					className = e.attribute("className"),
					readableName = e.attribute("readableName"),
					name = e.attribute("name");

			QList<QVariant> list;
			list.append(className);
			list.append(docString);
			list.append(name);

			if (type == "integrator")
				ui->integratorBox->addItem(readableName, list);
			else if (type == "sampler")
				ui->samplerBox->addItem(readableName, list);
			else if (type == "rfilter")
				ui->rFilterBox->addItem(readableName, list);
		}
		if (name == "irrcache")
			ui->icBox->setProperty("help", docString);
		else if (name == "adaptive")
			ui->aiBox->setProperty("help", docString);
	}

	m_model = new XMLTreeModel(docRoot, palette(), this);
	ui->treeView->setModel(m_model);
	ui->treeView->setAlternatingRowColors(true);
	ui->treeView->setUniformRowHeights(true);
	ui->treeView->setColumnWidth(0, 270);
	ui->treeView->setStyleSheet("QTreeView::item { padding-right: 8px; }");
	ui->treeView->setItemDelegate(new PropertyDelegate(this));
	connect(ui->treeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection)),
		SLOT(onTreeSelectionChange(const QItemSelection &, const QItemSelection &)));
	connect(m_model, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(dataChanged()));
	m_integratorNode = m_model->registerClass("MIPathTracer", "Path tracer");
	m_samplerNode = m_model->registerClass("IndependentSampler", "Independent sampler");
	m_rFilterNode = m_model->registerClass("BoxFilter", "Box filter");
	QRegExp resRegExp("^[1-9]\\d{0,4}x[1-9]\\d{0,4}$");
	ui->resolutionBox->setValidator(new QRegExpValidator(resRegExp, this));
	QPalette pal = ui->helpViewer->palette();
	pal.setColor(QPalette::Text, pal.color(QPalette::Foreground));
	pal.setColor(QPalette::Base, pal.color(QPalette::Window));
	ui->helpViewer->setPalette(pal);
	ui->helpViewer->setHtml("Click on any setting for documentation");
}
Пример #18
0
void addDir(const QString &dir, bool system)
{
    QDomDocument doc("fontconfig");
    QString      fileName=getConfigFile(system);
    QFile        f(fileName);
    bool         hasDir(false);

    KFI_DBUG << "Using fontconfig file:" << fileName;

    // Load existing file - and check to see whether it has the dir...
    if(f.open(QIODevice::ReadOnly))
    {
        doc.clear();

        if(doc.setContent(&f))
        {
            QDomNode n = doc.documentElement().firstChild();

            while(!n.isNull() && !hasDir)
            {
                QDomElement e = n.toElement();

                if(!e.isNull() && "dir"==e.tagName())
                    if(0==Misc::expandHome(Misc::dirSyntax(e.text())).indexOf(dir))
                        hasDir=true;
                n=n.nextSibling();
            }
        }
        f.close();
    }

    // Add dir, and save, if config does not already have this dir.
    if(!hasDir)
    {
        if(doc.documentElement().isNull())
            doc.appendChild(doc.createElement("fontconfig"));

        QDomElement newNode = doc.createElement("dir");
        QDomText    text    = doc.createTextNode(Misc::contractHome(xDirSyntax(dir)));

        newNode.appendChild(text);
        doc.documentElement().appendChild(newNode);

        FcAtomic *atomic=FcAtomicCreate((const unsigned char *)(QFile::encodeName(fileName).data()));

        if(atomic)
        {
            if(FcAtomicLock(atomic))
            {
                FILE *f=fopen((char *)FcAtomicNewFile(atomic), "w");

                if(f)
                {
                    //
                    // Check document syntax...
                    static const char qtXmlHeader[]   = "<?xml version = '1.0'?>";
                    static const char xmlHeader[]     = "<?xml version=\"1.0\"?>";
                    static const char qtDocTypeLine[] = "<!DOCTYPE fontconfig>";
                    static const char docTypeLine[]   = "<!DOCTYPE fontconfig SYSTEM "
                                                        "\"fonts.dtd\">";

                    QString str(doc.toString());
                    int     idx;

                    if(0!=str.indexOf("<?xml"))
                        str.insert(0, xmlHeader);
                    else if(0==str.indexOf(qtXmlHeader))
                        str.replace(0, strlen(qtXmlHeader), xmlHeader);

                    if(-1!=(idx=str.indexOf(qtDocTypeLine)))
                        str.replace(idx, strlen(qtDocTypeLine), docTypeLine);

                    //
                    // Write to file...
                    fputs(str.toUtf8(), f);
                    fclose(f);

                    if(!FcAtomicReplaceOrig(atomic))
                        FcAtomicDeleteNew(atomic);
                }
                FcAtomicUnlock(atomic);
            }
            FcAtomicDestroy(atomic);
        }
    }
}
Пример #19
0
MythFontProperties *MythFontProperties::ParseFromXml(
    const QString &filename,
    const QDomElement &element,
    MythUIType *parent,
    bool addToGlobal,
    bool showWarnings)
{
    // Crappy, but cached.  Move to GlobalFontMap?

    bool fromBase = false;
    MythFontProperties *newFont = new MythFontProperties();
    newFont->Freeze();

    if (element.tagName() == "font")
        LOG(VB_GENERAL, LOG_WARNING, LOC +
            QString("File %1: Use of 'font' is deprecated in favour of "
                    "'fontdef'") .arg(filename));

    QString name = element.attribute("name", "");
    if (name.isEmpty())
    {
        VERBOSE_XML(VB_GENERAL, LOG_ERR,
                    filename, element, "Font requires a name");
        delete newFont;
        return NULL;
    }

    QString base = element.attribute("from", "");

    if (!base.isEmpty())
    {
        MythFontProperties *tmp = NULL;

        if (parent)
            tmp = parent->GetFont(base);

        if (!tmp)
            tmp = GetGlobalFontMap()->GetFont(base);

        if (!tmp)
        {
            VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                QString("Specified base font '%1' does not exist.").arg(base));

            delete newFont;
            return NULL;
        }

        *newFont = *tmp;
        fromBase = true;
    }

    int size, pixelsize;
    size = pixelsize = -1;

    QString face = element.attribute("face", "");
    if (face.isEmpty())
    {
        if (!fromBase)
        {
            VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                        "Font needs a face");
            delete newFont;
            return NULL;
        }
    }
    else
    {
        newFont->m_face.setFamily(face);
    }

    if (addToGlobal && GetGlobalFontMap()->Contains(name))
    {
        MythFontProperties *tmp = GetGlobalFontMap()->GetFont(name);
        if (showWarnings)
        {
            VERBOSE_XML(VB_GENERAL, LOG_WARNING, filename, element,
                QString("Attempting to define '%1'\n\t\t\t"
                        "with face '%2', but it already "
                        "exists with face '%3'")
                .arg(name).arg(QFontInfo(newFont->m_face).family())
                .arg((tmp) ? QFontInfo(tmp->m_face).family() : "ERROR"));
        }
        delete newFont;
        return NULL;
    }

    QString hint = element.attribute("stylehint", "");
    if (!hint.isEmpty())
    {
        newFont->m_face.setStyleHint((QFont::StyleHint)hint.toInt());
    }

    for (QDomNode child = element.firstChild(); !child.isNull();
         child = child.nextSibling())
    {
        QDomElement info = child.toElement();
        if (!info.isNull())
        {
            if (info.tagName() == "size")
            {
                size = getFirstText(info).toInt();
            }
            else if (info.tagName() == "pixelsize")
            {
                pixelsize = getFirstText(info).toInt();
            }
            else if (info.tagName() == "color")
            {
                newFont->m_brush = QBrush(QColor(getFirstText(info)));
            }
            else if (info.tagName() == "gradient")
            {
                newFont->m_brush = parseGradient(info);
            }
            else if (info.tagName() == "shadowcolor")
            {
                newFont->m_shadowColor = QColor(getFirstText(info));
            }
            else if (info.tagName() == "shadowoffset")
            {
                newFont->m_hasShadow = true;
                newFont->m_shadowOffset = parsePoint(info);
            }
            else if (info.tagName() == "shadowalpha")
            {
                newFont->m_shadowAlpha = getFirstText(info).toInt();
            }
            else if (info.tagName() == "outlinecolor")
            {
                newFont->m_outlineColor = QColor(getFirstText(info));
            }
            else if (info.tagName() == "outlinesize")
            {
                newFont->m_hasOutline = true;
                newFont->m_outlineSize = getFirstText(info).toInt();
            }
            else if (info.tagName() == "outlinealpha")
            {
                newFont->m_outlineAlpha = getFirstText(info).toInt();
            }
            else if (info.tagName() == "italics")
            {
                newFont->m_face.setItalic(parseBool(info));
            }
            else if (info.tagName() == "letterspacing")
            {
                newFont->m_face.setLetterSpacing(QFont::AbsoluteSpacing,
                                              getFirstText(info).toInt());
            }
            else if (info.tagName() == "wordspacing")
            {
                newFont->m_face.setWordSpacing(getFirstText(info).toInt());
            }
            else if (info.tagName() == "decoration")
            {
                QString dec = getFirstText(info).toLower();
                QStringList values = dec.split(',');

                QStringList::Iterator it;
                for ( it = values.begin(); it != values.end(); ++it )
                {
                    if (*it == "underline")
                        newFont->m_face.setUnderline(true);
                    else if (*it == "overline")
                        newFont->m_face.setOverline(true);
                    else if (*it == "strikeout")
                        newFont->m_face.setStrikeOut(true);
                }
            }
            else if (info.tagName() == "weight")
            {
                QString weight = getFirstText(info).toLower();

                if (weight == "ultralight" ||
                    weight == "1")
                    newFont->m_face.setWeight(1);
                else if (weight == "light" ||
                         weight == "2")
                    newFont->m_face.setWeight(QFont::Light);
                else if (weight == "normal" ||
                         weight == "3")
                    newFont->m_face.setWeight(QFont::Normal);
                else if (weight == "demibold" ||
                         weight == "4")
                    newFont->m_face.setWeight(QFont::DemiBold);
                else if (weight == "bold" ||
                         weight == "5")
                    newFont->m_face.setWeight(QFont::Bold);
                else if (weight == "black" ||
                         weight == "6")
                    newFont->m_face.setWeight(QFont::Black);
                else if (weight == "ultrablack" ||
                         weight == "7")
                    newFont->m_face.setWeight(99);
                else
                    newFont->m_face.setWeight(QFont::Normal);
            }
            else if (info.tagName() == "stretch")
            {
                QString stretch = getFirstText(info).toLower();

                if (stretch == "ultracondensed" ||
                    stretch == "1")
                    newFont->m_stretch = QFont::UltraCondensed;
                else if (stretch == "extracondensed" ||
                         stretch == "2")
                    newFont->m_stretch = QFont::ExtraCondensed;
                else if (stretch == "condensed" ||
                         stretch == "3")
                    newFont->m_stretch = QFont::Condensed;
                else if (stretch == "semicondensed" ||
                         stretch == "4")
                    newFont->m_stretch = QFont::SemiCondensed;
                else if (stretch == "unstretched" ||
                         stretch == "5")
                    newFont->m_stretch = QFont::Unstretched;
                else if (stretch == "semiexpanded" ||
                         stretch == "6")
                    newFont->m_stretch = QFont::SemiExpanded;
                else if (stretch == "expanded" ||
                         stretch == "7")
                    newFont->m_stretch = QFont::Expanded;
                else if (stretch == "extraexpanded" ||
                         stretch == "8")
                    newFont->m_stretch = QFont::ExtraExpanded;
                else if (stretch == "ultraexpanded" ||
                         stretch == "9")
                    newFont->m_stretch = QFont::UltraExpanded;
                else
                    newFont->m_stretch = QFont::Unstretched;

                newFont->m_face.setStretch(newFont->m_stretch);
            }
            else
            {
                VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, info,
                            QString("Unknown tag in font '%1'").arg(name));
                delete newFont;
                return NULL;
            }
        }
    }

    if (size <= 0 && pixelsize <= 0 && !fromBase)
    {
        VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                    "Font size must be greater than 0.");
        delete newFont;
        return NULL;
    }
    else if (pixelsize > 0)
    {
        newFont->SetPixelSize(pixelsize);
    }
    else if (size > 0)
    {
        newFont->SetPointSize(size);
    }

    newFont->Unfreeze();

    QFontInfo fi(newFont->m_face);
    if (newFont->m_face.family() != fi.family())
    {
        VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                    QString("Failed to load '%1', got '%2' instead")
            .arg(newFont->m_face.family()).arg(fi.family()));
    }
    else
    {
        VERBOSE_XML(VB_GUI, LOG_DEBUG, filename, element,
                    QString("loaded '%1'").arg(fi.family()));
    }

    if (addToGlobal)
        GetGlobalFontMap()->AddFont(name, newFont);

    return newFont;
}
Пример #20
0
void Data::load(void)
{
  std::cout << qPrintable(tr("Loading data")) << std::endl;

  QFile file( OC_CFG_FILE );
  QDir::setCurrent( OC_CFG_DIR );

  if( !file.open( QIODevice::ReadOnly ) )
    {
      QString strErr = QObject::tr("Error: Can't open config file !\n"
                                   "This is probably the first time\n"
                                   "you run this application.\n"
                                   "So just click ok.\n"
                                   "Next time, this message shouldn't appear.\n"
                                  );
      std::cerr << " " << qPrintable(strErr) << std::endl;
      QMessageBox::warning(0,
                           QObject::tr("Loading config file"),
                           strErr
                          );
      file.close();
      return;
    }

  std::cout << " " << qPrintable(tr("Loading...")) << std::endl;
  //std::cout << " ToDo" << std::endl;

  /* validating document using dtd : not possible easily using Qt4 */

  /* En test */
  QDomDocument doc;
  QString errorStr;
  int errorLine;
  int errorColumn;

  /* looking for malformed xml file */
  if( !doc.setContent( &file, true, &errorStr, &errorLine, &errorColumn ) )
    {
      QString strErr = QObject::tr("Parse error at line %1, "
                                   "column %2:\n%3")
                       .arg(errorLine)
                       .arg(errorColumn)
                       .arg(errorStr);
      std::cerr << " " << qPrintable(strErr) << std::endl;
      QMessageBox::warning(0,
                           QObject::tr("DOM Parser"),
                           strErr
                          );
      file.close();
      return;
    }

  QDomElement root = doc.documentElement();

  /* looking for the root name 'ocdata' */
  //std::cout << "root = " << qPrintable(root.tagName()) << std::endl;
  if (root.tagName() != QLatin1String("ocdata"))
    {
      QString strErr = QObject::tr("Document should begin with <ocdata> and stop with </ocdata>");
      std::cerr << " " << qPrintable(strErr) << std::endl;
      QMessageBox::warning(0,
                           QObject::tr("DOM Parser"),
                           strErr
                          );

      file.close();
      return;
    }

  /* parsing file */

  QDomNode node = root.firstChild();
  while ( !node.isNull() )
    {
      QDomElement element = node.toElement();

      if (element.tagName() == QLatin1String("track"))
        {
          //Track::parse(node.toElement(), this->track);
          std::cout  << qPrintable(tr(" ")) << qPrintable(tr("Parsing"))  << qPrintable(tr(" ")) << qPrintable(element.tagName()) << std::endl;

          //std::cout << "laps=" << qPrintable(element.attribute("laps")) << std::endl;
          this->track.setLaps(element.attribute(QLatin1String("laps")).toInt());
          this->track.setEtaps(element.attribute(QLatin1String("etaps")).toInt());
          this->track.setName(element.attribute(QLatin1String("etaps")));
        }
      else if (element.tagName() == QLatin1String("position"))
        {
          std::cout << qPrintable(tr(" ")) << qPrintable(tr("Parsing")) << qPrintable(tr(" ")) << qPrintable(element.tagName()) << std::endl;
          this->position.setLap(element.attribute(QLatin1String("lap")).toInt());
          this->position.setEtap(element.attribute(QLatin1String("etap")).toInt());
        }
      else if (element.tagName() == QLatin1String("vehicule"))
        {
          std::cout << qPrintable(tr(" ")) << qPrintable(tr("Parsing")) << qPrintable(tr(" ")) << qPrintable(element.tagName()) << std::endl;
          // ToDo
        }
      else if (element.tagName() == QLatin1String("chrono"))
        {
          std::cout << qPrintable(tr(" ")) << qPrintable(tr("Parsing")) << qPrintable(tr(" ")) << qPrintable(element.tagName()) << std::endl;
          // ToDo
        }
      else
        {
          QString strErr = QObject::tr("Error: Undefined element tagName");
          std::cerr << qPrintable(tr(" ")) << qPrintable(strErr) << std::endl;
          QMessageBox::warning(0,
                               QObject::tr("DOM Parser"),
                               strErr
                              );
        }

      node = node.nextSibling();
    }

  file.close();

  std::cout << qPrintable(tr(" ")) << qPrintable(tr("Data loaded")) << std::endl;
}
Пример #21
0
void ColorSetManager::initialiseDefaultPrefs(struct ApplicationPrefs& appPrefs)
{
	QString defaultSwatch = ScPaths::instance().shareDir() + "swatches/" + "Scribus_Basic.xml";
	QFile fiC(defaultSwatch);
	if (!fiC.exists())
	{
		appPrefs.colorPrefs.DColors.insert("White", ScColor(0, 0, 0, 0));
		appPrefs.colorPrefs.DColors.insert("Black", ScColor(0, 0, 0, 255));
		ScColor cc = ScColor(255, 255, 255, 255);
		cc.setRegistrationColor(true);
		appPrefs.colorPrefs.DColors.insert("Registration", cc);
		appPrefs.colorPrefs.DColors.insert("Blue", ScColor(255, 255, 0, 0));
		appPrefs.colorPrefs.DColors.insert("Cyan", ScColor(255, 0, 0, 0));
		appPrefs.colorPrefs.DColors.insert("Green", ScColor(255, 0, 255, 0));
		appPrefs.colorPrefs.DColors.insert("Red", ScColor(0, 255, 255, 0));
		appPrefs.colorPrefs.DColors.insert("Yellow", ScColor(0, 0, 255, 0));
		appPrefs.colorPrefs.DColors.insert("Magenta", ScColor(0, 255, 0, 0));
		appPrefs.colorPrefs.DColorSet = "Scribus_Small";
	}
	else
	{
		if (fiC.open(QIODevice::ReadOnly))
		{
			QString ColorEn, Cname;
			int Rval, Gval, Bval;
			QTextStream tsC(&fiC);
			ColorEn = tsC.readLine();
			if (ColorEn.startsWith("<?xml version="))
			{
				QByteArray docBytes("");
				loadRawText(defaultSwatch, docBytes);
				QString docText("");
				docText = QString::fromUtf8(docBytes);
				QDomDocument docu("scridoc");
				docu.setContent(docText);
				ScColor lf = ScColor();
				QDomElement elem = docu.documentElement();
				QDomNode PAGE = elem.firstChild();
				while(!PAGE.isNull())
				{
					QDomElement pg = PAGE.toElement();
					if(pg.tagName()=="COLOR" && pg.attribute("NAME")!=CommonStrings::None)
					{
						if (pg.hasAttribute("CMYK"))
							lf.setNamedColor(pg.attribute("CMYK"));
						else if (pg.hasAttribute("RGB"))
							lf.fromQColor(QColor(pg.attribute("RGB")));
						else
						{
							double L = pg.attribute("L", 0).toDouble();
							double a = pg.attribute("A", 0).toDouble();
							double b = pg.attribute("B", 0).toDouble();
							lf.setColor(L, a, b);
						}
						if (pg.hasAttribute("Spot"))
							lf.setSpotColor(static_cast<bool>(pg.attribute("Spot").toInt()));
						else
							lf.setSpotColor(false);
						if (pg.hasAttribute("Register"))
							lf.setRegistrationColor(static_cast<bool>(pg.attribute("Register").toInt()));
						else
							lf.setRegistrationColor(false);
						appPrefs.colorPrefs.DColors.insert(pg.attribute("NAME"), lf);
					}
					PAGE=PAGE.nextSibling();
				}
			}
			else
			{
				while (!tsC.atEnd())
				{
					ColorEn = tsC.readLine();
					QTextStream CoE(&ColorEn, QIODevice::ReadOnly);
					CoE >> Rval;
					CoE >> Gval;
					CoE >> Bval;
					CoE >> Cname;
					ScColor tmp;
					tmp.setColorRGB(Rval, Gval, Bval);
					appPrefs.colorPrefs.DColors.insert(Cname, tmp);
				}
			}
			fiC.close();
		}
		appPrefs.colorPrefs.DColorSet = ScPaths::instance().shareDir() + "swatches/" + "Scribus Basic";
	}
Пример #22
0
KstEquation::KstEquation(const QDomElement &e)
: KstDataObject(e) {
  QString in_tag, equation;

  int ns = -1;
  double x0 = 0.0, x1 = 1.0;
  QString xvtag;
  bool haveVector = false;

  _doInterp = false;

  /* parse the DOM tree */
  QDomNode n = e.firstChild();
  while (!n.isNull()) {
    QDomElement e = n.toElement(); // try to convert the node to an element.
    if (!e.isNull()) { // the node was really an element.
      if (e.tagName() == "tag") {
        in_tag = e.text();
      } else if (e.tagName() == "equation") {
        equation = e.text();
      } else if (e.tagName() == "x0") {
        x0 = e.text().toDouble();
      } else if (e.tagName() == "x1") {
        x1 = e.text().toDouble();
      } else if (e.tagName() == "ns") {
        ns = e.text().toInt();
      } else if (e.tagName() == "xvtag") {
        xvtag = e.text();
      } else if (e.tagName() == "xvector") {
        _inputVectorLoadQueue.append(qMakePair(XVECTOR, e.text()));
        haveVector = true;
      } else if (e.tagName() == "interpolate") {
        _doInterp = true;
      }
    }
    n = n.nextSibling();
  }

  if (!haveVector) {
    if (ns < 0) {
      ns = 2;
    }
    if (x0 == x1) {
      x1 = x0 + 2;
    }

    QString vtag;
    if (xvtag.isEmpty()) {
      vtag = KST::suggestVectorName(QString("(%1..%2)").arg(x0).arg(x1));
    } else {
      vtag = xvtag;
    }

    KstVectorPtr xvector = new KstSVector(x0, x1, ns, vtag);
    KST::addVectorToList(xvector);

    _doInterp = false;
    _xVector = _inputVectors.insert(XVECTOR, xvector);
  } else {
    _xVector = _inputVectors.end();
  }
  commonConstructor(in_tag, equation);
}
Пример #23
0
void PMInsertRuleSystem::loadRules( const QString& fileName )
{
   PMRuleClass::s_pPrototypeManager = m_pPart->prototypeManager( );
   if( m_loadedFiles.find( fileName ) != m_loadedFiles.end( ) )
      return;
   m_loadedFiles.push_back( fileName );


   QString ruleFile = locate( "data", QString( "kpovmodeler/" + fileName ) );
   if( ruleFile.isEmpty( ) )
   {
      kdError( PMArea ) << "Rule file 'kpovmodeler/" << fileName
                        << "' not found." << endl;
      return;
   }

   QFile file( ruleFile );
   if( !file.open( IO_ReadOnly ) )
   {
      kdError( PMArea ) << "Could not open rule file 'kpovmodeler/" << fileName
                        << "'" << endl;
      return;
   }

   QDomDocument doc( "insertrules" );
   doc.setContent( &file );

   QDomElement e = doc.documentElement( );
   if( e.attribute( "format" ) != "1.0" )
      kdError( PMArea ) << "Rule format " << e.attribute( "format" )
                        << " not supported." << endl;
   else
   {
      QDomNode c = e.firstChild( );
      QPtrList<PMRuleDefineGroup> dummyLocalGroups;

      while( !c.isNull( ) )
      {
         if( c.isElement( ) )
         {
            QDomElement ce = c.toElement( );
            if( ce.tagName( ) == "definegroup" )
               m_groups.append( new PMRuleDefineGroup( ce, m_groups,
                                                       dummyLocalGroups ) );
            else if( ce.tagName( ) == "targetclass" )
            {
               QString className = ce.attribute( "name" );
               // find a target class with the same name
               PMRuleTargetClass* target = 0;

               if( !m_rulesDict.isEmpty( ) )
                  target = m_rulesDict.find( className );

               if( target )
                  target->appendRules( ce, m_groups );
               else
               {
                  target = new PMRuleTargetClass( ce, m_groups );
                  m_rulesDict.insert( className, target );
                  m_classRules.append( target );
               }
            }
         }
         c = c.nextSibling( );
      }
   }
   file.close( );

   PMRuleClass::s_pPrototypeManager = 0;
}
Пример #24
0
bool ProjectBarrier::XMLLoadSystem(const QDomElement &project) {
	System *s;
	unsigned int eigenfunctions = 0;
	QString str;

	QDomElement name = XMLUtils::childWithTag(project, "name");
	setName(name.text());

	QDomElement system = XMLUtils::childWithTag(project, "system");
	QDomElement barrierpotential = XMLUtils::childWithTag(system, "barrierpotential");
	
	// fill the dialog
	{
		QDomNode node;
		QDomElement elem;
		QLineEdit *edit = NULL;
		QString tag;
		bool status = true;
	
		for (node = system.firstChild(); !node.isNull(); node = node.nextSibling()) {
			elem = node.toElement();
			if (elem.isNull()) continue;
			tag = elem.tagName();
	
			if (tag == "points") m_dialog->m_numPoints_edit->setText(elem.attribute("value"));
			else if (tag == "lowervalue") m_dialog->m_lowIntegration_edit->setText(elem.attribute("value"));
			else if (tag == "highervalue") m_dialog->m_highIntegration_edit->setText(elem.attribute("value"));
			else if (tag == "particlemass") m_dialog->m_particleMass_edit->setText(elem.attribute("value"));
			else if (tag == "eigenfunction") eigenfunctions++; 
			else {}
		}

		str.setNum(eigenfunctions);
		m_dialog->m_eigenNumber_edit->setText(str);
	
		for (node = barrierpotential.firstChild(); !node.isNull(); node = node.nextSibling()) {
			elem = node.toElement();
			if (elem.isNull()) continue;
			tag = elem.tagName();
			if (tag == "lowedge") m_dialog->m_potentialLowEdge_edit->setText(elem.attribute("value")); 
			else if (tag == "highedge") m_dialog->m_potentialHighEdge_edit->setText(elem.attribute("value")); 
			else if (tag == "highpotential") m_dialog->m_extPotential_edit->setText(elem.attribute("value")); 
			else if (tag == "barrierlowedge") m_dialog->m_barrierLowEdge_edit->setText(elem.attribute("value"));
			else if (tag == "barrierhighedge") m_dialog->m_barrierHighEdge_edit->setText(elem.attribute("value"));
			else if (tag == "barrierheight") m_dialog->m_barrierHeight_edit->setText(elem.attribute("value"));
			else {}
		
		}

	}
		
	// check it

	if (checkValues(false)) {
		// fill system and potential
		s = createSystem();
	} else
		return false;
	
	// pass to model

	return m_model->XMLLoad(s, system);

}
Пример #25
0
bool MythLocale::LoadDefaultsFromXML(void)
{
    m_defaultsLoaded = true;
    m_globalSettings.clear();
    QDomDocument doc;

    QString path = QString("/locales/%1.xml").arg(m_localeCode.toLower());

    QFile file(path.prepend(GetShareDir()));
    if (!file.exists())
    {
        file.setFileName(path.prepend(GetConfDir()));

        if (!file.exists())
        {
            LOG(VB_GENERAL, LOG_ERR, 
                QString("No locale defaults file for %1, skipping")
                    .arg(m_localeCode));
            return false;
        }
    }

    if (!file.open(QIODevice::ReadOnly))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Unable to open %1")
                                                        .arg(file.fileName()));
        return false;
    }

    LOG(VB_GENERAL, LOG_NOTICE, QString("Reading locale defaults from %1")
                                                        .arg(file.fileName()));

    if (!doc.setContent(&file))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Unable to parse %1")
                                                        .arg(file.fileName()));

        file.close();
        return false;
    }
    file.close();

    QDomElement docElem = doc.documentElement();

    for (QDomNode n = docElem.firstChild(); !n.isNull();
            n = n.nextSibling())
    {
        QDomElement e = n.toElement();
        if (!e.isNull())
        {
            if (e.tagName() == "setting")
            {
                QString name = e.attribute("name", "");
                bool global = (e.attribute("global", "false") == "true");
                QString value = e.firstChild().toText().data();

                // TODO Assumes no setting accepts an empty value, which may not
                // be the case
                if (!name.isEmpty() && !value.isEmpty())
                {
                    if (global)
                        m_globalSettings[name] = value;
                    else
                        m_hostSettings[name] = value;
                }
            }
        }
    }

    if (m_globalSettings.isEmpty() && m_hostSettings.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("No locale defaults specified in %1, skipping")
                .arg(file.fileName()));
        return false;
    }

    return true;
}
Пример #26
0
bool VCWidget::loadXMLAppearance(QDomDocument*, QDomElement* root)
{
	QDomNode node;
	QDomElement tag;
	QString str;

	Q_ASSERT(root != NULL);

	if (root->tagName() != KXMLQLCVCAppearance)
	{
		cout << "Appearance node not found!" << endl;
		return false;
	}

	/* Children */
	node = root->firstChild();
	while (node.isNull() == false)
	{
		tag = node.toElement();
		if (tag.tagName() == KXMLQLCVCWidgetFrameStyle)
		{
			int style = 0;
			style = stringToFrameStyle(tag.text());
			setFrameStyle(style);
		}
		else if (tag.tagName() == KXMLQLCVCWidgetForegroundColor)
		{
			if (tag.text() != KXMLQLCVCWidgetColorDefault)
			{
				QColor color(tag.text().toInt());
				setForegroundColor(color);
			}
		}
		else if (tag.tagName() == KXMLQLCVCWidgetBackgroundColor)
		{
			if (tag.text() != KXMLQLCVCWidgetColorDefault)
				setBackgroundColor(QColor(tag.text().toInt()));
		}
		else if (tag.tagName() == KXMLQLCVCWidgetBackgroundImage)
		{
			if (tag.text() != KXMLQLCVCWidgetBackgroundImageNone)
				setBackgroundImage(tag.text());
		}
		else if (tag.tagName() == KXMLQLCVCWidgetFont)
		{
			if (tag.text() != KXMLQLCVCWidgetFontDefault)
			{
				QFont font;
				font.fromString(tag.text());
				setFont(font);
			}
		}
		else
		{
			cout << "Unknown appearance tag: "
			     << tag.tagName().toStdString()
			     << endl;
		}
		
		node = node.nextSibling();
	}

	return true;
}
Пример #27
0
void Aussackler::slotLoadFile(const QString fileName)
{
    QDomDocument doc("aussackler");
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly))
        return;
    if (!doc.setContent(&file)) {
        file.close();
        return;
    }
    file.close();

    for (int i = m_transactions.size() - 1; i >= 0; --i)
    {
        delete m_transactions.at(i);
    }
    m_transactions.clear();

    QDomElement docElem = doc.documentElement();

    QDomNode n = docElem.firstChild();
    while(!n.isNull())
    {
        QDomElement e = n.toElement();
        if(!e.isNull() && e.tagName() == "transaction")
        {
            if (!e.hasAttribute("type"))
                continue;
            ASTransaction::TransactionType type =
                (ASTransaction::TransactionType)
                ASTransaction::TransactionTypeStrings.
                indexOf(e.attribute("type"));
            ASTransaction * a = NULL;
            switch(type)
            {
            case ASTransaction::TRANSACTION_TYPE_BASE:
                a = new ASTransaction(&m_transactions);
                break;
            case ASTransaction::TRANSACTION_TYPE_CATEGORY:
                a = new ASCategory(&m_transactions);
                break;
            case ASTransaction::TRANSACTION_TYPE_ACCOUNT:
                a = new ASAccount(&m_transactions);
                break;
            case ASTransaction::TRANSACTION_TYPE_ACCOUNTENTRY:
                a = new ASAccountEntry(&m_transactions);
                break;
            case ASTransaction::TRANSACTION_TYPE_INVESTMENT:
                a = new ASInvestEntry(&m_transactions);
                break;
            case ASTransaction::TRANSACTION_TYPE_DOCUMENT:
                a = new ASDocument(&m_transactions);
                break;
            case ASTransaction::TRANSACTION_TYPE_VATCATEGORY:
                a = new ASVatCategory(&m_transactions);
                break;
            }
            if (a)
            {
                a->readFromXml(&e);
                a->commit();
            }
        }
        n = n.nextSibling();
    }
}
Пример #28
0
bool RGBMatrix::loadXML(const QDomElement& root)
{
    if (root.tagName() != KXMLQLCFunction)
    {
        qWarning() << Q_FUNC_INFO << "Function node not found";
        return false;
    }

    if (root.attribute(KXMLQLCFunctionType) != typeToString(Function::RGBMatrix))
    {
        qWarning() << Q_FUNC_INFO << "Function is not an RGB matrix";
        return false;
    }

    /* Load matrix contents */
    QDomNode node = root.firstChild();
    while (node.isNull() == false)
    {
        QDomElement tag = node.toElement();

        if (tag.tagName() == KXMLQLCFunctionSpeed)
        {
            loadXMLSpeed(tag);
        }
        else if (tag.tagName() == KXMLQLCRGBAlgorithm)
        {
            setAlgorithm(RGBAlgorithm::loader(doc(), tag));
        }
        else if (tag.tagName() == KXMLQLCRGBMatrixFixtureGroup)
        {
            setFixtureGroup(tag.text().toUInt());
        }
        else if (tag.tagName() == KXMLQLCFunctionDirection)
        {
            loadXMLDirection(tag);
        }
        else if (tag.tagName() == KXMLQLCFunctionRunOrder)
        {
            loadXMLRunOrder(tag);
        }
        else if (tag.tagName() == KXMLQLCRGBMatrixStartColor)
        {
            setStartColor(QColor::fromRgb(QRgb(tag.text().toUInt())));
        }
        else if (tag.tagName() == KXMLQLCRGBMatrixEndColor)
        {
            setEndColor(QColor::fromRgb(QRgb(tag.text().toUInt())));
        }
        else if (tag.tagName() == KXMLQLCRGBMatrixProperty)
        {
            QString name = tag.attribute(KXMLQLCRGBMatrixPropertyName);
            QString value = tag.attribute(KXMLQLCRGBMatrixPropertyValue);
            setProperty(name, value);
        }
        else if (tag.tagName() == KXMLQLCRGBMatrixDimmerControl)
        {
            setDimmerControl(tag.text().toInt());
        }
        else
        {
            qWarning() << Q_FUNC_INFO << "Unknown RGB matrix tag:" << tag.tagName();
        }

        node = node.nextSibling();
    }

    return true;
}
Пример #29
0
void ShapePlug::parseGroupProperties(QDomNode &DOC, double &minXCoor, double &minYCoor, double &maxXCoor, double &maxYCoor, bool &firstCheck)
{
	QString FillCol = "White";
	QString StrokeCol = "Black";
	QColor stroke = Qt::black;
	QColor fill = Qt::white;
	while(!DOC.isNull())
	{
		double x1, y1, x2, y2;
		FPointArray PoLine;
		PoLine.resize(0);
		QDomElement pg = DOC.toElement();
		QString STag = pg.tagName();
		if (STag == "svg:line")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("x1")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("y1")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("x2")) * Conversion;
			y2 = ScCLocale::toDoubleC(pg.attribute("y2")) * Conversion;
			PoLine.addPoint(x1, y1);
			PoLine.addPoint(x1, y1);
			PoLine.addPoint(x2, y2);
			PoLine.addPoint(x2, y2);
		}
		else if (STag == "svg:rect")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("x")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("y")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("width")) * Conversion;
			y2 = ScCLocale::toDoubleC(pg.attribute("height")) * Conversion;
			static double rect[] = {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0,
									1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
									0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0};
			for (int a = 0; a < 29; a += 4)
			{
				double xa = x2 * rect[a];
				double ya = y2 * rect[a+1];
				double xb = x2 * rect[a+2];
				double yb = y2 * rect[a+3];
				PoLine.addPoint(x1+xa, y1+ya);
				PoLine.addPoint(x1+xb, y1+yb);
			}
		}
		else if ((STag == "svg:polygon") || (STag == "svg:polyline"))
		{
			bool bFirst = true;
			double x = 0.0;
			double y = 0.0;
			QString points = pg.attribute( "points" ).simplified().replace(',', " ");
			QStringList pointList = points.split(' ', QString::SkipEmptyParts);
			FirstM = true;
			for( QStringList::Iterator it1 = pointList.begin(); it1 != pointList.end(); it1++ )
			{
				if( bFirst )
				{
					x = ScCLocale::toDoubleC(*(it1++));
					y = ScCLocale::toDoubleC(*it1);
					svgMoveTo(x * Conversion, y * Conversion);
					bFirst = false;
					WasM = true;
				}
				else
				{
					x = ScCLocale::toDoubleC(*(it1++));
					y = ScCLocale::toDoubleC(*it1);
					svgLineTo(&PoLine, x * Conversion, y * Conversion);
				}
			}
			if (STag == "svg:polygon")
				svgClosePath(&PoLine);
			if (PoLine.size() < 4)
			{
				DOC = DOC.nextSibling();
				continue;
			}
		}
		else if (STag == "svg:circle")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("cx")) * Conversion - x1;
			y2 = ScCLocale::toDoubleC(pg.attribute("cy")) * Conversion - y1;
			x1 *= 2.0;
			y1 *= 2.0;
			static double rect[] = {1.0, 0.5, 1.0, 0.77615235,0.5, 1.0, 0.77615235, 1.0,
									0.5, 1.0, 0.22385765, 1.0, 0.0, 0.5, 0.0, 0.77615235,
									0.0, 0.5, 0.0, 0.22385765, 0.5, 0.0, 0.22385765, 0.0,
									0.5, 0.0, 0.77615235, 0.0, 1.0, 0.5, 1.0, 0.22385765};
			for (int a = 0; a < 29; a += 4)
			{
				double xa = x1 * rect[a];
				double ya = y1 * rect[a+1];
				double xb = x1 * rect[a+2];
				double yb = y1 * rect[a+3];
				PoLine.addPoint(x2+xa, y2+ya);
				PoLine.addPoint(x2+xb, y2+yb);
			}
		}
		else if (STag == "svg:ellipse")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("rx")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("ry")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("cx")) * Conversion - x1;
			y2 = ScCLocale::toDoubleC(pg.attribute("cy")) * Conversion - y1;
			x1 *= 2.0;
			y1 *= 2.0;
			static double rect[] = {1.0, 0.5, 1.0, 0.77615235,0.5, 1.0, 0.77615235, 1.0,
									0.5, 1.0, 0.22385765, 1.0, 0.0, 0.5, 0.0, 0.77615235,
									0.0, 0.5, 0.0, 0.22385765, 0.5, 0.0, 0.22385765, 0.0,
									0.5, 0.0, 0.77615235, 0.0, 1.0, 0.5, 1.0, 0.22385765};
			for (int a = 0; a < 29; a += 4)
			{
				double xa = x1 * rect[a];
				double ya = y1 * rect[a+1];
				double xb = x1 * rect[a+2];
				double yb = y1 * rect[a+3];
				PoLine.addPoint(x2+xa, y2+ya);
				PoLine.addPoint(x2+xb, y2+yb);
			}
		}
		else if (STag == "svg:path")
		{
			parseSVG( pg.attribute( "d" ), &PoLine );
			if (PoLine.size() < 4)
			{
				DOC = DOC.nextSibling();
				continue;
			}
		}
		else if (STag == "svg:g")
		{
			QDomNode child = DOC.firstChild();
			parseGroupProperties(child, minXCoor, minYCoor, maxXCoor, maxYCoor, firstCheck);
		}
		if (PoLine.size() < 4)
		{
			DOC = DOC.nextSibling();
			continue;
		}
		FPoint tp2(getMinClipF(&PoLine));
		PoLine.translate(-tp2.x(), -tp2.y());
		FPoint wh(getMaxClipF(&PoLine));
		if (firstCheck)
		{
			minXCoor = tp2.x();
			minYCoor = tp2.y();
			maxXCoor = tp2.x() + wh.x();
			maxYCoor = tp2.y() + wh.y();
			firstCheck = false;
		}
		else
		{
			minXCoor = qMin(minXCoor, tp2.x());
			minYCoor = qMin(minYCoor, tp2.y());
			maxXCoor = qMax(maxXCoor, tp2.x() + wh.x());
			maxYCoor = qMax(maxYCoor, tp2.y() + wh.y());
		}
		DOC = DOC.nextSibling();
	}
}
Пример #30
0
void QLCPhysical_Test::save()
{
	QDomDocument doc;
	QDomElement root = doc.createElement("Test Root");
	bool bulb = false, dim = false, lens = false, focus = false, technical = false;

	QVERIFY(p.saveXML(&doc, &root) == true);
	QVERIFY(root.firstChild().toElement().tagName() == "Physical");

	QDomNode node = root.firstChild().firstChild();
	while (node.isNull() == false)
	{
		QDomElement e = node.toElement();
		if (e.tagName() == "Bulb")
		{
			bulb = true;
			QVERIFY(e.attribute("Type") == "LED");
			QVERIFY(e.attribute("Lumens") == "18000");
			QVERIFY(e.attribute("ColourTemperature") == "6500");
		}
		else if (e.tagName() == "Dimensions")
		{
			dim = true;
			QVERIFY(e.attribute("Width") == "530");
			QVERIFY(e.attribute("Depth") == "260");
			QVERIFY(e.attribute("Height") == "320");
			QVERIFY(e.attribute("Weight") == "39");
		}
		else if (e.tagName() == "Lens")
		{
			lens = true;
			QVERIFY(e.attribute("Name") == "Fresnel");
			QVERIFY(e.attribute("DegreesMin") == "8");
			QVERIFY(e.attribute("DegreesMax") == "38");
		}
		else if (e.tagName() == "Focus")
		{
			focus = true;
			QVERIFY(e.attribute("Type") == "Head");
			QVERIFY(e.attribute("PanMax") == "520");
			QVERIFY(e.attribute("TiltMax") == "270");
		}
		else if (e.tagName() == "Technical")
		{
			technical = true;
			QVERIFY(e.attribute("PowerConsumption") == "250");
			QVERIFY(e.attribute("DmxConnector") == "5-pin");
		}
		else
		{
			QFAIL(QString("Unexpected tag: %1").arg(e.tagName())
				.toAscii());
		}

		node = node.nextSibling();
	}

	QVERIFY(bulb == true);
	QVERIFY(dim == true);
	QVERIFY(lens == true);
	QVERIFY(focus == true);
	QVERIFY(technical == true);
}