Beispiel #1
0
QSharedPointer<Filter> XMLizer::readFilter( QDomElement &element, bool audio, bool &readError, bool transition )
{
	QDomNodeList nodes = element.childNodes();
	
	QString name;
	bool okName = false;
	QSharedPointer<Filter> filter;
	
	for ( int i = 0; i < nodes.count(); ++i ) {
		QDomElement e = nodes.at( i ).toElement();
		if ( e.isNull() )
			continue;
		
		if ( e.tagName() == "Name" ) {
			name = e.text();
			okName = true;
			break;
		}
	}
	
	if ( !okName ) {
		readError = true;
		return filter;
	}
	
	FilterCollection *fc = FilterCollection::getGlobalInstance();
	if ( transition ) {
		if ( audio ) {
			for ( int i = 0; i < fc->audioTransitions.count(); ++i ) {
				if ( fc->audioTransitions[ i ].identifier == name ) {
					filter = fc->audioTransitions[ i ].create();
					break;
				}
			}
		}
		else {
			for ( int i = 0; i < fc->videoTransitions.count(); ++i ) {
				if ( fc->videoTransitions[ i ].identifier == name ) {
					filter = fc->videoTransitions[ i ].create();
					break;
				}
			}
		}
	}
	else {
		if ( audio ) {
			for ( int i = 0; i < fc->audioFilters.count(); ++i ) {
				if ( fc->audioFilters[ i ].identifier == name ) {
					filter = fc->audioFilters[ i ].create();
					break;
				}
			}	
		}
		else {
			for ( int i = 0; i < fc->videoFilters.count(); ++i ) {
				if ( fc->videoFilters[ i ].identifier == name ) {
					filter = fc->videoFilters[ i ].create();
					break;
				}
			}
		}
	}
	
	if ( filter.isNull() ) {
		readError = true;
		return filter;
	}

	QString shader = "";
	if ( filter->getIdentifier() == "GLCustom" ) {
		for ( int i = 0; i < nodes.count(); ++i ) {
			QDomElement e = nodes.at( i ).toElement();
			if ( e.isNull() )
				continue;
			if ( e.tagName() == "Parameter" ) {
				readParameter( e, filter );
			}
		}
		
		QString shaderName = "";
		QList<Parameter*> params = filter->getParameters();
		Parameter *editor = NULL;
		for ( int i = 0; i < params.count(); ++i ) {
			if ( params[ i ]->id == "editor" ) {
				editor = params[ i ];
				// retrieve the shader name
				shaderName = editor->value.toString();
				break;
			}
		}
		
		// get the shader
		shader = ShaderCollection::getGlobalInstance()->getLocalShader( shaderName );
		if ( editor && !shader.isEmpty() ) {
			GLCustom *f = (GLCustom*)filter.data();
			// set the shader so that parameters are constructed
			// and will be reparsed in the following loop
			f->setCustomParams( shader );
		}	
	}
	
	for ( int i = 0; i < nodes.count(); ++i ) {
		QDomElement e = nodes.at( i ).toElement();
		if ( e.isNull() )
			continue;
		
		if ( e.tagName() == "PosInTrack" ) {
			filter->setPosition( e.text().toDouble() );
		}
		else if ( e.tagName() == "PosOffset" ) {
			filter->setPositionOffset( e.text().toDouble() );
		}
		else if ( e.tagName() == "Length" ) {
			filter->setLength( e.text().toDouble() );
		}
		else if ( e.tagName() == "SnapMode" ) {
			filter->setSnap( e.text().toInt() );
		}
		else if ( e.tagName() == "Parameter" ) {
			readParameter( e, filter );
		}
	}
	
	if ( filter->getIdentifier() == "GLCustom" ) {
		// restore the shader that has been overwritten
		// by the preceding loop
		QList<Parameter*> params = filter->getParameters();
		for ( int i = 0; i < params.count(); ++i ) {
			if ( params[ i ]->id == "editor" ) {
				if ( !shader.isEmpty() )
					params[ i ]->value = shader;
				else {
					params[ i ]->value = GLCustom::getDefaultShader();
				}
				break;
			}
		}
	}

	return filter;
}
Beispiel #2
0
void multimediaProject::upgrade()
{
	projectVersion version =
		documentElement().attribute( "creatorversion" ).
							replace( "svn", "" );

	if( version < "0.2.1-20070501" )
	{
		QDomNodeList list = elementsByTagName( "arpandchords" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.hasAttribute( "arpdir" ) )
			{
				int arpdir = el.attribute( "arpdir" ).toInt();
				if( arpdir > 0 )
				{
					el.setAttribute( "arpdir", arpdir - 1 );
				}
				else
				{
					el.setAttribute( "arpdisabled", "1" );
				}
			}
		}

		list = elementsByTagName( "sampletrack" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.attribute( "vol" ) != "" )
			{
				el.setAttribute( "vol", el.attribute(
						"vol" ).toFloat() * 100.0f );
			}
			else
			{
				QDomNode node = el.namedItem(
							"automation-pattern" );
				if( !node.isElement() ||
					!node.namedItem( "vol" ).isElement() )
				{
					el.setAttribute( "vol", 100.0f );
				}
			}
		}

		list = elementsByTagName( "ladspacontrols" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			QDomNode anode = el.namedItem( "automation-pattern" );
			QDomNode node = anode.firstChild();
			while( !node.isNull() )
			{
				if( node.isElement() )
				{
					QString name = node.nodeName();
					if( name.endsWith( "link" ) )
					{
						el.setAttribute( name,
							node.namedItem( "time" )
							.toElement()
							.attribute( "value" ) );
						QDomNode oldNode = node;
						node = node.nextSibling();
						anode.removeChild( oldNode );
						continue;
					}
				}
				node = node.nextSibling();
			}
		}

		QDomNode node = m_head.firstChild();
		while( !node.isNull() )
		{
			if( node.isElement() )
			{
				if( node.nodeName() == "bpm" )
				{
					int value = node.toElement().attribute(
							"value" ).toInt();
					if( value > 0 )
					{
						m_head.setAttribute( "bpm",
									value );
						QDomNode oldNode = node;
						node = node.nextSibling();
						m_head.removeChild( oldNode );
						continue;
					}
				}
				else if( node.nodeName() == "mastervol" )
				{
					int value = node.toElement().attribute(
							"value" ).toInt();
					if( value > 0 )
					{
						m_head.setAttribute(
							"mastervol", value );
						QDomNode oldNode = node;
						node = node.nextSibling();
						m_head.removeChild( oldNode );
						continue;
					}
				}
				else if( node.nodeName() == "masterpitch" )
				{
					m_head.setAttribute( "masterpitch",
						-node.toElement().attribute(
							"value" ).toInt() );
					QDomNode oldNode = node;
					node = node.nextSibling();
					m_head.removeChild( oldNode );
					continue;
				}
			}
			node = node.nextSibling();
		}
	}

	if( version < "0.2.1-20070508" )
	{
		QDomNodeList list = elementsByTagName( "arpandchords" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.hasAttribute( "chorddisabled" ) )
			{
				el.setAttribute( "chord-enabled",
					!el.attribute( "chorddisabled" )
								.toInt() );
				el.setAttribute( "arp-enabled",
					!el.attribute( "arpdisabled" )
								.toInt() );
			}
			else if( !el.hasAttribute( "chord-enabled" ) )
			{
				el.setAttribute( "chord-enabled", true );
				el.setAttribute( "arp-enabled",
					el.attribute( "arpdir" ).toInt() != 0 );
			}
		}

		while( !( list = elementsByTagName( "channeltrack" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "instrumenttrack" );
		}

		list = elementsByTagName( "instrumenttrack" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.hasAttribute( "vol" ) )
			{
				float value = el.attribute( "vol" ).toFloat();
				value = roundf( value * 0.585786438f );
				el.setAttribute( "vol", value );
			}
			else
			{
				QDomNodeList vol_list = el.namedItem(
							"automation-pattern" )
						.namedItem( "vol" ).toElement()
						.elementsByTagName( "time" );
				for( int j = 0; !vol_list.item( j ).isNull();
									++j )
				{
					QDomElement timeEl = list.item( j )
								.toElement();
					int value = timeEl.attribute( "value" )
								.toInt();
					value = (int)roundf( value *
								0.585786438f );
					timeEl.setAttribute( "value", value );
				}
			}
		}
	}


	if( version < "0.3.0-rc2" )
	{
		QDomNodeList list = elementsByTagName( "arpandchords" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.attribute( "arpdir" ).toInt() > 0 )
			{
				el.setAttribute( "arpdir",
					el.attribute( "arpdir" ).toInt() - 1 );
			}
		}
	}

	if( version < "0.3.0" )
	{
		QDomNodeList list;
		while( !( list = elementsByTagName(
					"pluckedstringsynth" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "vibedstrings" );
			el.setAttribute( "active0", 1 );
		}

		while( !( list = elementsByTagName( "lb303" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "lb302" );
		}

		while( !( list = elementsByTagName( "channelsettings" ) ).
								isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "instrumenttracksettings" );
		}
	}

	if( version < "0.4.0-20080104" )
	{
		QDomNodeList list = elementsByTagName( "fx" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.hasAttribute( "fxdisabled" ) &&
				el.attribute( "fxdisabled" ).toInt() == 0 )
			{
				el.setAttribute( "enabled", 1 );
			}
		}
	}

	if( version < "0.4.0-20080118" )
	{
		QDomNodeList list;
		while( !( list = elementsByTagName( "fx" ) ).isEmpty() )
		{
			QDomElement fxchain = list.item( 0 ).toElement();
			fxchain.setTagName( "fxchain" );
			QDomNode rack = list.item( 0 ).firstChild();
			QDomNodeList effects = rack.childNodes();
			// move items one level up
			while( effects.count() )
			{
				fxchain.appendChild( effects.at( 0 ) );
			}
			fxchain.setAttribute( "numofeffects",
				rack.toElement().attribute( "numofeffects" ) );
			fxchain.removeChild( rack );
		}
	}

	if( version < "0.4.0-20080129" )
	{
		QDomNodeList list;
		while( !( list =
			elementsByTagName( "arpandchords" ) ).isEmpty() )
		{
			QDomElement aac = list.item( 0 ).toElement();
			aac.setTagName( "arpeggiator" );
			QDomNode cloned = aac.cloneNode();
			cloned.toElement().setTagName( "chordcreator" );
			aac.parentNode().appendChild( cloned );
		}
	}

	if( version < "0.4.0-20080409" )
	{
		QStringList s;
		s << "note" << "pattern" << "bbtco" << "sampletco" << "time";
		for( QStringList::iterator it = s.begin(); it < s.end(); ++it )
		{
			QDomNodeList list = elementsByTagName( *it );
			for( int i = 0; !list.item( i ).isNull(); ++i )
			{
				QDomElement el = list.item( i ).toElement();
				el.setAttribute( "pos",
					el.attribute( "pos" ).toInt()*3 );
				el.setAttribute( "len",
					el.attribute( "len" ).toInt()*3 );
			}
		}
		QDomNodeList list = elementsByTagName( "timeline" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			el.setAttribute( "lp0pos",
				el.attribute( "lp0pos" ).toInt()*3 );
			el.setAttribute( "lp1pos",
				el.attribute( "lp1pos" ).toInt()*3 );
		}
		
	}

	if( version < "0.4.0-20080607" )
	{
		QDomNodeList list;
		while( !( list = elementsByTagName( "midi" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "midiport" );
		}
	}

	if( version < "0.4.0-20080622" )
	{
		QDomNodeList list;
		while( !( list = elementsByTagName(
					"automation-pattern" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "automationpattern" );
		}

		list = elementsByTagName( "bbtrack" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			QString s = el.attribute( "name" );
			s.replace( QRegExp( "^Beat/Baseline " ),
							"Beat/Bassline " );
			el.setAttribute( "name", s );
		}
	}

	if( version < "0.4.0-beta1" )
	{
		// convert binary effect-key-blobs to XML
		QDomNodeList list;
		list = elementsByTagName( "effect" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			QString k = el.attribute( "key" );
			if( !k.isEmpty() )
			{
				const QList<QVariant> l =
					base64::decode( k, QVariant::List ).toList();
				if( !l.isEmpty() )
				{
					QString name = l[0].toString();
					QVariant u = l[1];
					EffectKey::AttributeMap m;
					// VST-effect?
					if( u.type() == QVariant::String )
					{
						m["file"] = u.toString();
					}
					// LADSPA-effect?
					else if( u.type() == QVariant::StringList )
					{
						const QStringList sl = u.toStringList();
						m["plugin"] = sl.value( 0 );
						m["file"] = sl.value( 1 );
					}
					EffectKey key( NULL, name, m );
					el.appendChild( key.saveXML( *this ) );
				}
			}
		}
	}
	if( version < "0.4.0-rc2" )
	{
		QDomNodeList list = elementsByTagName( "audiofileprocessor" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			QString s = el.attribute( "src" );
			s.replace( "drumsynth/misc ", "drumsynth/misc_" );
			s.replace( "drumsynth/r&b", "drumsynth/r_n_b" );
			s.replace( "drumsynth/r_b", "drumsynth/r_n_b" );
			el.setAttribute( "src", s );
		}
		list = elementsByTagName( "lb302" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			int s = el.attribute( "shape" ).toInt();
			if( s >= 1 )
			{
				s--;
			}
			el.setAttribute( "shape", QString("%1").arg(s) );
		}

	}

	// Time-signature
	if ( !m_head.hasAttribute( "timesig_numerator" ) )
	{
		m_head.setAttribute( "timesig_numerator", 4 );
		m_head.setAttribute( "timesig_denominator", 4 );
	}

	if( !m_head.hasAttribute( "mastervol" ) )
	{
		m_head.setAttribute( "mastervol", 100 );
	}
//printf("%s\n", toString( 2 ).toUtf8().constData());
}
Beispiel #3
0
bool parseReportDetailSection(const QDomElement & elemSource, ORDetailSectionData & sectionTarget)
{
  if(elemSource.tagName() != "section")
    return FALSE;

  bool have_name = FALSE;
  bool have_detail = FALSE;
  bool have_key = FALSE;

  ORSectionData * old_head = 0;
  ORSectionData * old_foot = 0;

  QDomNodeList section = elemSource.childNodes();
  for(int nodeCounter = 0; nodeCounter < section.count(); nodeCounter++)
  {
    QDomElement elemThis = section.item(nodeCounter).toElement();
    if(elemThis.tagName() == "name")
    {
      sectionTarget.name = elemThis.text();
      have_name = TRUE;
    }
    else if(elemThis.tagName() == "pagebreak")
    {
      if(elemThis.attribute("when") == "at end")
        sectionTarget.pagebreak = ORDetailSectionData::BreakAtEnd;
    }
    else if(elemThis.tagName() == "grouphead")
    {
      ORSectionData * sd = new ORSectionData();
      if(parseReportSection(elemThis, *sd) == TRUE)
      {
        old_head = sd;
        sectionTarget.trackTotal += sd->trackTotal;
      }
      else
        delete sd;
    }
    else if(elemThis.tagName() == "groupfoot")
    {
      ORSectionData * sd = new ORSectionData();
      if(parseReportSection(elemThis, *sd) == TRUE)
      {
        old_foot = sd;
        sectionTarget.trackTotal += sd->trackTotal;
      }
      else
        delete sd;
    }
    else if(elemThis.tagName() == "group")
    {
      QDomNodeList nl = elemThis.childNodes();
      QDomNode node;
      ORDetailGroupSectionData * dgsd = new ORDetailGroupSectionData();
      for(int i = 0; i < nl.count(); i++)
      {
        node = nl.item(i);
        if(node.nodeName() == "name")
          dgsd->name = node.firstChild().nodeValue();
        else if(node.nodeName() == "column")
          dgsd->column = node.firstChild().nodeValue();
        else if(node.nodeName() == "pagebreak")
        {
          QDomElement elemThis = node.toElement();
          QString n = elemThis.attribute("when");
          if("after foot" == n)
            dgsd->pagebreak = ORDetailGroupSectionData::BreakAfterGroupFoot;
        }
        else if(node.nodeName() == "head")
        {
          ORSectionData * sd = new ORSectionData();
          if(parseReportSection(node.toElement(), *sd) == TRUE)
          {
            dgsd->head = sd;
            sectionTarget.trackTotal += sd->trackTotal;
            for(Q3ValueListIterator<ORDataData> it = sd->trackTotal.begin(); it != sd->trackTotal.end(); ++it)
              dgsd->_subtotCheckPoints[*it] = 0.0;
          }
          else
            delete sd;
        }
        else if(node.nodeName() == "foot")
        {
          ORSectionData * sd = new ORSectionData();
          if(parseReportSection(node.toElement(), *sd) == TRUE)
          {
            dgsd->foot = sd;
            sectionTarget.trackTotal += sd->trackTotal;
            for(Q3ValueListIterator<ORDataData> it = sd->trackTotal.begin(); it != sd->trackTotal.end(); ++it)
              dgsd->_subtotCheckPoints[*it] = 0.0;
          }
          else
            delete sd;
        }
        else
          qDebug("While parsing group section encountered an unknown element: %s", node.nodeName().latin1());
      }
      sectionTarget.groupList.append(dgsd);
    }
    else if(elemThis.tagName() == "detail")
    {
      // find and read in the key data of this element
      have_key = parseReportKey(elemThis.namedItem("key").toElement(), sectionTarget.key);

      ORSectionData * sd = new ORSectionData();
      if(parseReportSection(elemThis, *sd) == TRUE)
      {
        sectionTarget.detail = sd;
        sectionTarget.trackTotal += sd->trackTotal;
        have_detail = TRUE;
      }
      else
        delete sd;
    }
    else
      qDebug("While parsing detail section encountered an unknown element: %s",(const char*)elemThis.tagName());
  }
  if(old_head || old_foot)
  {
    ORDetailGroupSectionData * gsec = new ORDetailGroupSectionData();
    gsec->name = sectionTarget.name;
    gsec->column = sectionTarget.key.column;
    gsec->head = old_head;
    gsec->foot = old_foot;
    sectionTarget.groupList.append(gsec);
  }
  return (have_name && have_detail && have_key);
}
Beispiel #4
0
void QgsSvgCache::replaceElemParams( QDomElement& elem, const QColor& fill, const QColor& outline, double outlineWidth )
{
  if ( elem.isNull() )
  {
    return;
  }

  //go through attributes
  QDomNamedNodeMap attributes = elem.attributes();
  int nAttributes = attributes.count();
  for ( int i = 0; i < nAttributes; ++i )
  {
    QDomAttr attribute = attributes.item( i ).toAttr();
    //e.g. style="fill:param(fill);param(stroke)"
    if ( attribute.name().compare( QLatin1String( "style" ), Qt::CaseInsensitive ) == 0 )
    {
      //entries separated by ';'
      QString newAttributeString;

      QStringList entryList = attribute.value().split( ';' );
      QStringList::const_iterator entryIt = entryList.constBegin();
      for ( ; entryIt != entryList.constEnd(); ++entryIt )
      {
        QStringList keyValueSplit = entryIt->split( ':' );
        if ( keyValueSplit.size() < 2 )
        {
          continue;
        }
        QString key = keyValueSplit.at( 0 );
        QString value = keyValueSplit.at( 1 );
        if ( value.startsWith( QLatin1String( "param(fill)" ) ) )
        {
          value = fill.name();
        }
        else if ( value.startsWith( QLatin1String( "param(fill-opacity)" ) ) )
        {
          value = fill.alphaF();
        }
        else if ( value.startsWith( QLatin1String( "param(outline)" ) ) )
        {
          value = outline.name();
        }
        else if ( value.startsWith( QLatin1String( "param(outline-opacity)" ) ) )
        {
          value = outline.alphaF();
        }
        else if ( value.startsWith( QLatin1String( "param(outline-width)" ) ) )
        {
          value = QString::number( outlineWidth );
        }

        if ( entryIt != entryList.constBegin() )
        {
          newAttributeString.append( ';' );
        }
        newAttributeString.append( key + ':' + value );
      }
      elem.setAttribute( attribute.name(), newAttributeString );
    }
    else
    {
      QString value = attribute.value();
      if ( value.startsWith( QLatin1String( "param(fill)" ) ) )
      {
        elem.setAttribute( attribute.name(), fill.name() );
      }
      else if ( value.startsWith( QLatin1String( "param(fill-opacity)" ) ) )
      {
        elem.setAttribute( attribute.name(), fill.alphaF() );
      }
      else if ( value.startsWith( QLatin1String( "param(outline)" ) ) )
      {
        elem.setAttribute( attribute.name(), outline.name() );
      }
      else if ( value.startsWith( QLatin1String( "param(outline-opacity)" ) ) )
      {
        elem.setAttribute( attribute.name(), outline.alphaF() );
      }
      else if ( value.startsWith( QLatin1String( "param(outline-width)" ) ) )
      {
        elem.setAttribute( attribute.name(), QString::number( outlineWidth ) );
      }
    }
  }

  QDomNodeList childList = elem.childNodes();
  int nChildren = childList.count();
  for ( int i = 0; i < nChildren; ++i )
  {
    QDomElement childElem = childList.at( i ).toElement();
    replaceElemParams( childElem, fill, outline, outlineWidth );
  }
}
Beispiel #5
0
void XMLRead::readFileMeta(QDomNode _file)
{
    Files *f = new Files();
    QDomNodeList childs = _file.childNodes();
    for(int iDx = 0;iDx < childs.count(); iDx++)
    {
        QString nodename = childs.at(iDx).nodeName();
  //      qDebug() << nodename;
        if (nodename == "name")
        {
            //qDebug() << nodename << " = " << childs.at(iDx).toElement().text();
            f->name = childs.at(iDx).toElement().text();
        }
        else if (nodename == "year" )
        {
            //qDebug() << nodename << " = " << childs.at(iDx).toElement().text();
            f->year = childs.at(iDx).toElement().text();
        }
        else if (nodename == "date" )
        {
            //qDebug() << nodename << " = " << childs.at(iDx).toElement().text();
            QDate date = QDate::fromString(childs.at(iDx).toElement().text(),"d.M.yyyy");
            f->date = date;
            f->year = date.toString("yyyy");
            //qDebug() << f->date;
        }
        else if (nodename == "categories" )
        {
            //qDebug() << nodename << " = " << childs.at(iDx).toElement().text();
            QDomNodeList catlist = childs.at(iDx).childNodes();
            for(int r = 0;r < catlist.count(); r++)
            {
                Category temp_category;
                QDomNodeList cat = catlist.at(r).childNodes();
                QString catname = "";
                for(int p = 0;p < cat.count(); p++)
                {
                    if (cat.at(p).nodeName() == "catname")
                    {
                        catname = cat.at(p).toElement().text();
                        temp_category.catname = catname;
                    }
                    else if (cat.at(p).nodeName() == "subcategories")
                    {
                        QDomNodeList subcatnames = cat.at(p).childNodes();
                        for(int t = 0;t < subcatnames.count(); t++)
                        {
                            QString scatname = subcatnames.at(t).toElement().text();
                            temp_category.subcats.append(scatname);
                            //qDebug() << scatname;
                        }
                        //qDebug() << temp_category.subcats;
                    }
                }
                //qDebug() << temp_category.catname << temp_category.subcats;
                f->cat.append(temp_category);
            }

        }
        else if (nodename == "topic" )
        {
            //qDebug() << nodename << " = " << childs.at(iDx).toElement().text();
            f->topic = childs.at(iDx).toElement().text();
        }
        else if (nodename == "description" )
        {
            //qDebug() << nodename << " = " << childs.at(iDx).toElement().text();
            f->description = childs.at(iDx).toElement().text();
        }
        else if (nodename == "writer" )
        {
            //qDebug() << nodename << " = " << childs.at(iDx).toElement().text();
            f->writer = childs.at(iDx).toElement().text();
        }
        else if (nodename == "writedate" )
        {
            //qDebug() << nodename << " = " << childs.at(iDx).toElement().text();
            QDate date = QDate::fromString(childs.at(iDx).toElement().text(),"dd.MM.yyyy");
            f->writedate = date;
        }
        else if (nodename == "searchtags" )
        {
            //qDebug() << nodename << " = " << childs.at(iDx).toElement().text();
            QDomNodeList taglist = childs.at(iDx).childNodes();
            QList <QString> tags;
            for(int r = 0;r < taglist.count(); r++)
            {
                tags.append(taglist.at(r).toElement().text());
            }
            f->tags = tags;
            //qDebug() << f->tags;
        }

    }
    files.append(f);
}
void cNewMagic::load()
{
	// Get all spell definitions
	QStringList sList = DefManager->getSections( WPDT_SPELL );

	for( UINT8 i = 0; i < sList.count(); ++i )
	{
		const QDomElement *elem = DefManager->getSection( WPDT_SPELL, sList[i] );

		UINT8 id = elem->attribute( "id", "0" ).toUShort();

		if( !id || id > 64 )
			continue;

        id--;
		QDomElement node = elem->firstChild().toElement();

		while( !node.isNull() )
		{
			if( node.nodeName() == "name" )
				spells[id].name = node.text();
			else if( node.nodeName() == "mantra" )
				spells[id].mantra = node.text();
			else if( node.nodeName() == "target" )
				spells[id].target = node.text();
			else if( node.nodeName() == "booklow" )
				spells[id].booklow = node.text().toInt();
			else if( node.nodeName() == "bookhigh" )
				spells[id].bookhigh = node.text().toInt();
			else if( node.nodeName() == "scrolllow" )
				spells[id].scrolllow = node.text().toInt();
			else if( node.nodeName() == "scrollhigh" )
				spells[id].scrollhigh = node.text().toInt();
			else if( node.nodeName() == "actiondelay" )
				spells[id].actiondelay = node.text().toInt();
			else if( node.nodeName() == "delay" )
				spells[id].delay = node.text().toInt();
			else if( node.nodeName() == "action" )
				spells[id].action = hex2dec( node.text() ).toInt();
			else if( node.nodeName() == "targets" )
			{
				// process subnodes <char />, <item />, <ground />
				if( node.elementsByTagName( "char" ).count() >= 1 )
					spells[id].targets |= TARGET_CHAR;
				if( node.elementsByTagName( "item" ).count() >= 1 )
					spells[id].targets |= TARGET_ITEM;
				if( node.elementsByTagName( "ground" ).count() >= 1 )
					spells[id].targets |= TARGET_GROUND;
			}				
			else if( node.nodeName() == "flags" )
			{
				QDomNodeList nList = node.childNodes();

				for( INT32 i = 0; i < nList.count(); ++i )
				{
					QDomElement sNode = nList.item( i ).toElement();

					if( !sNode.isNull() )
					{
						if( sNode.nodeName() == "agressive" )
							spells[id].flags |= SPELL_AGRESSIVE;
						else if( sNode.nodeName() == "reflectable" )
							spells[id].flags |= SPELL_REFLECTABLE;
					}
				}
			}
			else if( node.nodeName() == "mana" )
				spells[id].mana = node.text().toInt();
			else if( node.nodeName() == "scroll" )
				spells[id].scroll = hex2dec( node.text() ).toLong();
			else if( node.nodeName() == "script" )
				spells[id].script = ScriptManager->find( node.text() );
			else if( node.nodeName() == "reagents" )
			{
				QDomNodeList nList = node.childNodes();

				for( INT32 i = 0; i < nList.count(); ++i )
				{
					QDomElement sNode = nList.item( i ).toElement();

					if( !sNode.isNull() )
					{
						if( sNode.nodeName() == "blackpearl" )
							spells[id].reagents.blackpearl = hex2dec( sNode.text() ).toInt();
						else if( sNode.nodeName() == "bloodmoss" )
							spells[id].reagents.bloodmoss = hex2dec( sNode.text() ).toInt();
						else if( sNode.nodeName() == "garlic" )
							spells[id].reagents.garlic = hex2dec( sNode.text() ).toInt();
						else if( sNode.nodeName() == "ginseng" )
							spells[id].reagents.ginseng = hex2dec( sNode.text() ).toInt();
						else if( sNode.nodeName() == "mandrake" )
							spells[id].reagents.mandrake = hex2dec( sNode.text() ).toInt();
						else if( sNode.nodeName() == "nightshade" )
							spells[id].reagents.nightshade = hex2dec( sNode.text() ).toInt();
						else if( sNode.nodeName() == "spidersilk" )
							spells[id].reagents.spidersilk = hex2dec( sNode.text() ).toInt();
						else if( sNode.nodeName() == "sulfurash" )
							spells[id].reagents.sulfurash = hex2dec( sNode.text() ).toInt();
					}
				}
			}

			QDomNode tmp = node.nextSibling();
			if( !tmp.isNull() )
				node = tmp.toElement();
			else
				break;
		}
	}
}
Beispiel #7
0
int main(int argc, char *argv[]) {

    QApplication app(argc, argv);
    app.setOrganizationName("QtProject");
    app.setApplicationName("Application Example");

    initDb();
    
    QMainWindow mainWin;
    mainWin.show();
    // QPlainTextEdit* textEdit = new QPlainTextEdit();
//    QToolBar* fileToolBar = mainWin.addToolBar("File");

    QSvgWidget* mySvg = new QSvgWidget();

    vector<string> students(10);
    students = { "eins", "zwei", "drei" };
    StudentList *studentListW = new StudentList(students);


    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(studentListW);
    mainLayout->addWidget(mySvg);

    QWidget *centralWidget = new QWidget;
    centralWidget->setLayout(mainLayout);

    mainWin.setCentralWidget(centralWidget);


    mySvg->load(QString(RESOURCES_PATH "zeugnis.svg"));
    QFile file(QString(RESOURCES_PATH "zeugnis.svg"));
    QDomDocument document;
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    document.setContent(&file);

    QDomElement root = document.firstChildElement();
    QDomNodeList nodes = root.elementsByTagName("tspan");
    
    for(int i = 0; i < nodes.count(); i++) {
        QDomNode elm = nodes.at(i);
        if(elm.isElement()) {
            QDomElement element = elm.toElement();
            QString attribute = element.attribute("id");
            if(attribute == "tspan4167") {
                QString elementText = element.text();    
                std::cout << elementText.toStdString() << std::endl;

                QDomText newTextNode = document.createTextNode("Hello, World");
                QDomNodeList oldTextNodes = element.childNodes();
                qDebug() << "# nodes = " << oldTextNodes.count();
                for (int i=0; i < oldTextNodes.count(); i++) {
                    // element.removeChild(oldTextNodes.at(i));
                    qDebug() << oldTextNodes.at(i).toElement().text();
                }

                element.appendChild(newTextNode);
            }
        }
    }

    mySvg->load(document.toByteArray());

    file.close();
    return app.exec();
}
Beispiel #8
0
void KreImporter::parseFile( const QString &filename )
{
	QFile * file = 0;
	bool unlink = false;
	kDebug() << "loading file:" << filename ;

	if ( filename.right( 4 ) == ".kre" ) {
		file = new QFile( filename );
		kDebug() << "file is an archive" ;
		KTar* kre = new KTar( filename, "application/x-gzip" );
		kre->open( QIODevice::ReadOnly );
		const KArchiveDirectory* dir = kre->directory();
		QString name;
		QStringList fileList = dir->entries();
		for ( QStringList::Iterator it = fileList.begin(); it != fileList.end(); ++it ) {
			if ( ( *it ).right( 6 ) == ".kreml" ) {
				name = *it;
			}
		}
		if ( name.isEmpty() ) {
			kDebug() << "error: Archive doesn't contain a valid Krecipes file" ;
			setErrorMsg( i18n( "Archive does not contain a valid Krecipes file" ) );
			return ;
		}
		QString tmp_dir = KStandardDirs::locateLocal( "tmp", "" );
		dir->copyTo( tmp_dir );
		file = new QFile( tmp_dir + name );
		kre->close();
		unlink = true; //remove file after import
	}
	else {
		file = new QFile( filename );
	}

	if ( file->open( QIODevice::ReadOnly ) ) {
		kDebug() << "file opened" ;
		QDomDocument doc;
		QString error;
		int line;
		int column;
		if ( !doc.setContent( file, &error, &line, &column ) ) {
			kDebug() << QString( "error: \"%1\" at line %2, column %3" ).arg( error ).arg( line ).arg( column ) ;
			setErrorMsg( i18n( "\"%1\" at line %2, column %3" , error , line, column ) );
			return ;
		}

		QDomElement kreml = doc.documentElement();

		if ( kreml.tagName() != "krecipes" ) {
			setErrorMsg( i18n( "This file does not appear to be a *.kreml file" ) );
			return ;
		}

		// TODO Check if there are changes between versions
		QString kreVersion = kreml.attribute( "version" );
		kDebug() << "KreML version" << kreVersion ;

		QDomNodeList r = kreml.childNodes();
		QDomElement krecipe;

		for ( int z = 0; z < r.count(); z++ ) {
			krecipe = r.item( z ).toElement();
			QDomNodeList l = krecipe.childNodes();
			if ( krecipe.tagName() == "krecipes-recipe" ) {
				Recipe recipe;
				for ( int i = 0; i < l.count(); i++ ) {
					QDomElement el = l.item( i ).toElement();
					if ( el.tagName() == "krecipes-description" ) {
						readDescription( el.childNodes(), &recipe );
					}
					if ( el.tagName() == "krecipes-ingredients" ) {
						readIngredients( el.childNodes(), &recipe );
					}
					if ( el.tagName() == "krecipes-instructions" ) {
						recipe.instructions = el.text().trimmed();
					}
					if ( el.tagName() == "krecipes-ratings" ) {
						readRatings( el.childNodes(), &recipe );
					}
				}
				add
					( recipe );
			}
			else if ( krecipe.tagName() == "krecipes-category-structure" ) {
				CategoryTree * tree = new CategoryTree;
				readCategoryStructure( l, tree );
				setCategoryStructure( tree );
			}
		}
	}
	if ( unlink ) {
		file->remove
		();
	}
}
void loadFromXml( mlt_producer producer, QGraphicsScene *scene, const char *templateXml, const char *templateText )
{
	scene->clear();
	mlt_properties producer_props = MLT_PRODUCER_PROPERTIES( producer );
	QDomDocument doc;
	QString data = QString::fromUtf8(templateXml);
	QString replacementText = QString::fromUtf8(templateText);
	doc.setContent(data);
	QDomElement title = doc.documentElement();

	// Check for invalid title
	if ( title.isNull() || title.tagName() != "kdenlivetitle" ) return;
	
	// Check title locale
	if ( title.hasAttribute( "LC_NUMERIC" ) ) {
	    QString locale = title.attribute( "LC_NUMERIC" );
	    QLocale::setDefault( locale );
	}
	
        int originalWidth;
        int originalHeight;
	if ( title.hasAttribute("width") ) {
            originalWidth = title.attribute("width").toInt();
            originalHeight = title.attribute("height").toInt();
            scene->setSceneRect(0, 0, originalWidth, originalHeight);
        }
        else {
            originalWidth = scene->sceneRect().width();
            originalHeight = scene->sceneRect().height();
        }
        if ( title.hasAttribute( "out" ) ) {
            mlt_properties_set_position( producer_props, "_animation_out", title.attribute( "out" ).toDouble() );
        }
        else {
            mlt_properties_set_position( producer_props, "_animation_out", mlt_producer_get_out( producer ) );
        }
        
	mlt_properties_set_int( producer_props, "_original_width", originalWidth );
	mlt_properties_set_int( producer_props, "_original_height", originalHeight );

	QDomNode node;
	QDomNodeList items = title.elementsByTagName("item");
        for ( int i = 0; i < items.count(); i++ )
	{
		QGraphicsItem *gitem = NULL;
		node = items.item( i );
		QDomNamedNodeMap nodeAttributes = node.attributes();
		int zValue = nodeAttributes.namedItem( "z-index" ).nodeValue().toInt();
		if ( zValue > -1000 )
		{
			if ( nodeAttributes.namedItem( "type" ).nodeValue() == "QGraphicsTextItem" )
			{
				QDomNamedNodeMap txtProperties = node.namedItem( "content" ).attributes();
				QFont font( txtProperties.namedItem( "font" ).nodeValue() );
				QDomNode propsNode = txtProperties.namedItem( "font-bold" );
				if ( !propsNode.isNull() )
				{
					// Old: Bold/Not bold.
					font.setBold( propsNode.nodeValue().toInt() );
				}
				else
				{
					// New: Font weight (QFont::)
					font.setWeight( txtProperties.namedItem( "font-weight" ).nodeValue().toInt() );
				}
				font.setItalic( txtProperties.namedItem( "font-italic" ).nodeValue().toInt() );
				font.setUnderline( txtProperties.namedItem( "font-underline" ).nodeValue().toInt() );
				// Older Kdenlive version did not store pixel size but point size
				if ( txtProperties.namedItem( "font-pixel-size" ).isNull() )
				{
					QFont f2;
					f2.setPointSize( txtProperties.namedItem( "font-size" ).nodeValue().toInt() );
					font.setPixelSize( QFontInfo( f2 ).pixelSize() );
				}
				else
					font.setPixelSize( txtProperties.namedItem( "font-pixel-size" ).nodeValue().toInt() );
				QColor col( stringToColor( txtProperties.namedItem( "font-color" ).nodeValue() ) );
				QString text = node.namedItem( "content" ).firstChild().nodeValue();
				if ( !replacementText.isEmpty() )
				{
					text = text.replace( "%s", replacementText );
				}
				QGraphicsTextItem *txt = scene->addText(text, font);
				if (txtProperties.namedItem("font-outline").nodeValue().toDouble()>0.0){
					QTextDocument *doc = txt->document();
					// Make sure some that the text item does not request refresh by itself
					doc->blockSignals(true);
					QTextCursor cursor(doc);
					cursor.select(QTextCursor::Document);
					QTextCharFormat format;
					format.setTextOutline(
							QPen(QColor( stringToColor( txtProperties.namedItem( "font-outline-color" ).nodeValue() ) ),
							txtProperties.namedItem("font-outline").nodeValue().toDouble(),
							Qt::SolidLine,Qt::RoundCap,Qt::RoundJoin)
					);
					format.setForeground(QBrush(col));

					cursor.mergeCharFormat(format);
				} else {
					txt->setDefaultTextColor( col );
				}
				
				// Effects
				if (!txtProperties.namedItem( "typewriter" ).isNull()) {
					// typewriter effect
					mlt_properties_set_int( producer_props, "_animated", 1 );
					QStringList effetData = QStringList() << "typewriter" << text << txtProperties.namedItem( "typewriter" ).nodeValue();
					txt->setData(0, effetData);
					if ( !txtProperties.namedItem( "textwidth" ).isNull() )
						txt->setData( 1, txtProperties.namedItem( "textwidth" ).nodeValue() );
				}
				
				if ( txtProperties.namedItem( "alignment" ).isNull() == false )
				{
					txt->setTextWidth( txt->boundingRect().width() );
					QTextOption opt = txt->document()->defaultTextOption ();
					opt.setAlignment(( Qt::Alignment ) txtProperties.namedItem( "alignment" ).nodeValue().toInt() );
					txt->document()->setDefaultTextOption (opt);
				}
					if ( !txtProperties.namedItem( "kdenlive-axis-x-inverted" ).isNull() )
				{
					//txt->setData(OriginXLeft, txtProperties.namedItem("kdenlive-axis-x-inverted").nodeValue().toInt());
				}
				if ( !txtProperties.namedItem( "kdenlive-axis-y-inverted" ).isNull() )
				{
					//txt->setData(OriginYTop, txtProperties.namedItem("kdenlive-axis-y-inverted").nodeValue().toInt());
				}
					gitem = txt;
			}
			else if ( nodeAttributes.namedItem( "type" ).nodeValue() == "QGraphicsRectItem" )
			{
				QString rect = node.namedItem( "content" ).attributes().namedItem( "rect" ).nodeValue();
				QString br_str = node.namedItem( "content" ).attributes().namedItem( "brushcolor" ).nodeValue();
				QString pen_str = node.namedItem( "content" ).attributes().namedItem( "pencolor" ).nodeValue();
				double penwidth = node.namedItem( "content" ).attributes().namedItem( "penwidth") .nodeValue().toDouble();
				QGraphicsRectItem *rec = scene->addRect( stringToRect( rect ), QPen( QBrush( stringToColor( pen_str ) ), penwidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin ), QBrush( stringToColor( br_str ) ) );
				gitem = rec;
			}
			else if ( nodeAttributes.namedItem( "type" ).nodeValue() == "QGraphicsPixmapItem" )
			{
				const QString url = node.namedItem( "content" ).attributes().namedItem( "url" ).nodeValue();
				const QString base64 = items.item(i).namedItem("content").attributes().namedItem("base64").nodeValue();
				QImage img;
				if (base64.isEmpty()){
					img.load(url);
				}else{
					img.loadFromData(QByteArray::fromBase64(base64.toAscii()));
				}
				ImageItem *rec = new ImageItem(img);
				scene->addItem( rec );
				gitem = rec;
			}
			else if ( nodeAttributes.namedItem( "type" ).nodeValue() == "QGraphicsSvgItem" )
			{
				QString url = items.item(i).namedItem("content").attributes().namedItem("url").nodeValue();
				QString base64 = items.item(i).namedItem("content").attributes().namedItem("base64").nodeValue();
				QGraphicsSvgItem *rec = NULL;
				if (base64.isEmpty()){
					rec = new QGraphicsSvgItem(url);
				}else{
					rec = new QGraphicsSvgItem();
					QSvgRenderer *renderer= new QSvgRenderer(QByteArray::fromBase64(base64.toAscii()), rec );
					rec->setSharedRenderer(renderer);
				}
				if (rec){
					scene->addItem(rec);
					gitem = rec;
				}
			}
		}
		//pos and transform
		if ( gitem )
		{
			QPointF p( node.namedItem( "position" ).attributes().namedItem( "x" ).nodeValue().toDouble(),
			           node.namedItem( "position" ).attributes().namedItem( "y" ).nodeValue().toDouble() );
			gitem->setPos( p );
			gitem->setTransform( stringToTransform( node.namedItem( "position" ).firstChild().firstChild().nodeValue() ) );
			int zValue = nodeAttributes.namedItem( "z-index" ).nodeValue().toInt();
			gitem->setZValue( zValue );

#if QT_VERSION >= 0x040600
			// effects
			QDomNode eff = items.item(i).namedItem("effect");
			if (!eff.isNull()) {
				QDomElement e = eff.toElement();
				if (e.attribute("type") == "blur") {
					QGraphicsBlurEffect *blur = new QGraphicsBlurEffect();
					blur->setBlurRadius(e.attribute("blurradius").toInt());
					gitem->setGraphicsEffect(blur);
				}
				else if (e.attribute("type") == "shadow") {
					QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
					shadow->setBlurRadius(e.attribute("blurradius").toInt());
					shadow->setOffset(e.attribute("xoffset").toInt(), e.attribute("yoffset").toInt());
					gitem->setGraphicsEffect(shadow);
				}
			}
#endif
		}
	}

	QDomNode n = title.firstChildElement("background");
	if (!n.isNull()) {
		QColor color = QColor( stringToColor( n.attributes().namedItem( "color" ).nodeValue() ) );
                if (color.alpha() > 0) {
                        QGraphicsRectItem *rec = scene->addRect(0, 0, scene->width(), scene->height() , QPen( Qt::NoPen ), QBrush( color ) );
                        rec->setZValue(-1100);
                }
	  
	}

	QString startRect;
	n = title.firstChildElement( "startviewport" );
        // Check if node exists, if it has an x attribute, it is an old version title, don't use viewport
	if (!n.isNull() && !n.toElement().hasAttribute("x"))
	{
		startRect = n.attributes().namedItem( "rect" ).nodeValue();
	}
	n = title.firstChildElement( "endviewport" );
        // Check if node exists, if it has an x attribute, it is an old version title, don't use viewport
	if (!n.isNull() && !n.toElement().hasAttribute("x"))
	{
		QString rect = n.attributes().namedItem( "rect" ).nodeValue();
		if (startRect != rect)
			mlt_properties_set( producer_props, "_endrect", rect.toUtf8().data() );
	}
	if (!startRect.isEmpty()) {
	  	mlt_properties_set( producer_props, "_startrect", startRect.toUtf8().data() );
	}
	return;
}
Beispiel #10
0
void Model::deserialize(const QDomDocument &xml)
{
	const QDomNodeList worldList = xml.elementsByTagName("world");
	const QDomNodeList robotsList = xml.elementsByTagName("robots");
	const QDomElement constraints = xml.documentElement().firstChildElement("constraints");

	if (mChecker) {
		/// @todo: should we handle if it returned false?
		mChecker->parseConstraints(constraints);
	}

	if (worldList.count() != 1) {
		return;
	}

	mWorldModel.deserialize(worldList.at(0).toElement());

	if (robotsList.count() != 1) {
		// need for backward compatibility with old format
		const QDomNodeList robotList = xml.elementsByTagName("robot");

		if (robotList.count() != 1) {
			/// @todo Report error
			return;
		}

		mRobotModels.at(0)->deserialize(robotList.at(0).toElement());
		mRobotModels.at(0)->configuration().deserialize(robotList.at(0).toElement());

		return;
	}

	QMutableListIterator<RobotModel *> iterator(mRobotModels);

	const bool oneRobot = robotsList.at(0).toElement().elementsByTagName("robot").size() == 1
			&& mRobotModels.size() == 1;

	while(iterator.hasNext()) {
		bool exist = false;
		RobotModel *robotModel = iterator.next();

		for (QDomElement element = robotsList.at(0).firstChildElement("robot"); !element.isNull();
				element = element.nextSiblingElement("robot")) {
			if (robotModel->info().robotId() == element.toElement().attribute("id")) {
				robotModel->deserialize(element);
				robotModel->configuration().deserialize(element);
				exist = true;
				robotsList.at(0).removeChild(static_cast<QDomNode>(element));
				break;
			}
		}

		if (!exist && !oneRobot) {
			iterator.remove();
			emit robotRemoved(robotModel);
			delete robotModel;
		}
	}

	if (oneRobot && !robotsList.at(0).firstChildElement("robot").isNull()) {
		QDomElement element = robotsList.at(0).firstChildElement("robot");
		mRobotModels.at(0)->deserialize(element);
	} else {
		for (QDomElement element = robotsList.at(0).firstChildElement("robot"); !element.isNull();
				element = element.nextSiblingElement("robot")) {
			twoDModel::robotModel::NullTwoDRobotModel *robotModel = new twoDModel::robotModel::NullTwoDRobotModel(
					element.attribute("id"));
			addRobotModel(*robotModel);
			mRobotModels.last()->deserialize(element);
		}
	}
}
Beispiel #11
0
void KreImporter::readDescription( const QDomNodeList& l, Recipe *recipe )
{
	for ( int i = 0; i < l.count(); i++ ) {
		QDomElement el = l.item( i ).toElement();
		if ( el.tagName() == "title" ) {
			recipe->title = el.text();
			kDebug() << "Found title: " << recipe->title ;
		}
		else if ( el.tagName() == "author" ) {
			kDebug() << "Found author: " << el.text() ;
			recipe->authorList.append( Element( el.text() ) );
		}
		else if ( el.tagName() == "serving" ) { //### Keep for < 0.9 compatibility
			recipe->yield.setAmount(el.text().toInt());
		}
		else if ( el.tagName() == "yield" ) {
			QDomNodeList yield_children = el.childNodes();
			for ( int j = 0; j < yield_children.count(); j++ ) {
				QDomElement y = yield_children.item( j ).toElement();
				if ( y.tagName() == "amount" ) {
					double amount = 0.0, amountOffset = 0.0;
					readAmount(y, amount, amountOffset);
					recipe->yield.setAmount(amount);
					recipe->yield.setAmountOffset(amountOffset);
				}
				else if ( y.tagName() == "type" )
					recipe->yield.setType(y.text());
			}
		}
		else if ( el.tagName() == "preparation-time" ) {
			kDebug() << "Found preparation time: " << el.text();
			recipe->prepTime = QTime::fromString( el.text(), "hh:mm" );
		}
		else if ( el.tagName() == "category" ) {
			QDomNodeList categories = el.childNodes();
			for ( int j = 0; j < categories.count(); j++ ) {
				QDomElement c = categories.item( j ).toElement();
				if ( c.tagName() == "cat" ) {
					kDebug() << "Found category: " << QString( c.text() ).trimmed() ;
					recipe->categoryList.append( Element( QString( c.text() ).trimmed() ) );
				}
			}
		}
		else if ( el.tagName() == "pictures" ) {
			if ( el.hasChildNodes() ) {
				QDomNodeList pictures = el.childNodes();
				for ( int j = 0; j < pictures.count(); j++ ) {
					QDomElement pic = pictures.item( j ).toElement();
					QByteArray decodedPic;
					if ( pic.tagName() == "pic" )
						kDebug() << "Found photo" ;
					QPixmap pix;
					KCodecs::base64Decode( QByteArray( pic.text().toLatin1() ), decodedPic );
					int len = decodedPic.size();
					QByteArray picData;
					picData.resize( len );
					memcpy( picData.data(), decodedPic.data(), len );
					bool ok = pix.loadFromData( picData, "JPEG" );
					if ( ok ) {
						recipe->photo = pix;
					}
				}
			}
		}
	}
}
Beispiel #12
0
OSResult::OSResult(const QDomElement& element) {
  if (element.isNull()) {
    LOG_AND_THROW("Cannot construct OSResult from null QDomElement.");
  }
  if (element.tagName() != QString::fromStdString("OSResult")) {
    LOG_AND_THROW("Cannot construct OSResult from element named " << toString(element.tagName())
                  << " rather than OSResult.");
  }

  QDomElement valueElement = element.firstChildElement(QString::fromStdString("Value"));
  QDomElement errorsElement = element.firstChildElement(QString::fromStdString("Errors"));
  QDomElement warningsElement = element.firstChildElement(QString::fromStdString("Warnings"));
  QDomElement infoElement = element.firstChildElement(QString::fromStdString("Info"));
  QDomElement initialConditionElement = element.firstChildElement(QString::fromStdString("InitialCondition"));
  QDomElement finalConditionElement = element.firstChildElement(QString::fromStdString("FinalCondition"));
  QDomElement attributesElement = element.firstChildElement(QString::fromStdString("Attributes"));

  if (valueElement.isNull()) {
    LOG_AND_THROW("valueElement is null.");
  }

  m_value = OSResultValue(valueElement.firstChild().nodeValue().toStdString());

  if (!errorsElement.isNull()) {
    QDomNodeList childNodes = errorsElement.childNodes();
    for (int i = 0; i < childNodes.count(); ++i) {
      QDomElement childElement = childNodes.at(i).toElement();
      m_errors.push_back(logMessageFromXML(Error,childElement));
    }
  }

  if (!warningsElement.isNull()) {
    QDomNodeList childNodes = warningsElement.childNodes();
    for (int i = 0; i < childNodes.count(); ++i) {
      QDomElement childElement = childNodes.at(i).toElement();
      m_warnings.push_back(logMessageFromXML(Warn,childElement));
    }
  }

  if (!infoElement.isNull()) {
    QDomNodeList childNodes = infoElement.childNodes();
    for (int i = 0; i < childNodes.count(); ++i) {
      QDomElement childElement = childNodes.at(i).toElement();
      m_info.push_back(logMessageFromXML(Info,childElement));
    }
  }

  if (!initialConditionElement.isNull()) {
    QDomNodeList childNodes = initialConditionElement.childNodes();
    int n = childNodes.count();
    OS_ASSERT(n < 2);
    if (n > 0) {
      QDomElement childElement = childNodes.at(0).toElement();
      m_initialCondition = logMessageFromXML(Info,childElement);
    }
  }

  if (!finalConditionElement.isNull()) {
    QDomNodeList childNodes = finalConditionElement.childNodes();
    int n = childNodes.count();
    OS_ASSERT(n < 2);
    if (n > 0) {
      QDomElement childElement = childNodes.at(0).toElement();
      m_finalCondition = logMessageFromXML(Info,childElement);
    }
  }

  if (!attributesElement.isNull()) {
    QDomNodeList childNodes = attributesElement.childNodes();
    for (int i = 0; i < childNodes.count(); ++i) {
      QDomElement childElement = childNodes.at(i).toElement();
      m_attributes.push_back(Attribute(childElement));
    }
  }
}
Beispiel #13
0
Clip* XMLizer::readClip( QDomElement &element, QList<Source*> *sourcesList, Scene *scene, bool &readError )
{
	QDomNodeList nodes = element.childNodes();
	
	QString name;
	double posInTrack = 0;
	double startTime = 0;
	double length = 0;
	double speed = 1;
	bool okName = false, okPos = false, okStart = false, okLen = false;
	Clip *clip = NULL;
	
	speed = element.attribute( "speed" ).toDouble();
	if ( speed == 0.0 )
		speed = 1.0;
	
	for ( int i = 0; i < nodes.count(); ++i ) {
		QDomElement e = nodes.at( i ).toElement();
		if ( e.isNull() )
			continue;
		
		if ( e.tagName() == "Name" ) {
			name = e.text();
			okName = true;
		}
		else if ( e.tagName() == "PosInTrack" ) {
			posInTrack = e.text().toDouble();
			okPos = true;
		}
		else if ( e.tagName() == "StartTime" ) {
			startTime = e.text().toDouble();
			okStart = true;
		}
		else if ( e.tagName() == "Length" ) {
			length = e.text().toDouble();
			okLen = true;
		}
	}
	
	if ( !( okName && okPos && okStart && okLen ) ) {
		readError = true;
		return clip;
	}
	
	// check if source exists and create clip
	for ( int i = 0; i < sourcesList->count(); ++i ) {
		if ( sourcesList->at(i)->getFileName() == name ) {
			clip = scene->createClip( sourcesList->at(i), posInTrack, startTime, length );
			break;
		}
	}
	
	if ( !clip ) {
		readError = true;
		return clip;
	}
	
	clip->setSpeed( speed );
	
	for ( int i = 0; i < nodes.count(); ++i ) {
		QDomElement e = nodes.at( i ).toElement();
		if ( e.isNull() )
			continue;
		
		if ( e.tagName() == "VideoFilter" ) {
			QSharedPointer<Filter> f = readFilter( e, false, readError );
			if ( !f.isNull() ) {
				if ( f->getIdentifier() == "GLStabilize" ) {
					GLStabilize *stab = (GLStabilize*)f.data();
					stab->setSource( clip->getSource() );
				}
				clip->videoFilters.append( f.staticCast<GLFilter>() );
			}
		}
		else if ( e.tagName() == "AudioFilter" ) {
			QSharedPointer<Filter> f = readFilter( e, true, readError );
			if ( !f.isNull() )
				clip->audioFilters.append( f.staticCast<AudioFilter>() );
		}
		else if ( e.tagName() == "Transition" ) {
			readTransition( e, clip, readError );
		}
	}
	
	return clip;
}
Beispiel #14
0
void XMLizer::readParameter( QDomElement &element, QSharedPointer<Filter> f )
{
	QString type = element.attribute( "type" );
	QString name = element.attribute( "name" );
	QString value = element.attribute( "value" );
	QString hue;
	QString saturation;
	
	if ( type.isEmpty() || name.isEmpty() || value.isEmpty() )
		return;
	
	if ( type == "colorwheel" ) {
		hue = element.attribute( "hue" );
		saturation = element.attribute( "saturation" );
		if ( hue.isEmpty() || saturation.isEmpty() )
			return;
	}
	
	Parameter *p = NULL;
	QList<Parameter*> params = f->getParameters();
	for ( int i = 0; i < params.count(); ++i ) {
		if ( params[ i ]->id == name ) {
			p = params[ i ];
			break;
		}
	}
	
	if ( !p )
		return;
	
	if ( type == "double" ) {
		if ( p->type != Parameter::PDOUBLE )
			return;
		p->value = value.toDouble();
	}
	else if ( type == "inputdouble" ) {
		if ( p->type != Parameter::PINPUTDOUBLE )
			return;
		p->value = value.toDouble();
	}
	else if ( type == "int" ) {
		if ( p->type != Parameter::PINT )
			return;
		p->value = value.toInt();
	}
	else if ( type == "bool" ) {
		if ( p->type != Parameter::PBOOL )
			return;
		p->value = value.toInt();
	}
	else if ( type == "rgb" ) {
		if ( p->type != Parameter::PRGBCOLOR )
			return;
		QColor col;
		col.setNamedColor( value );
		p->value = col;
	}
	else if ( type == "rgba" ) {
		if ( p->type != Parameter::PRGBACOLOR )
			return;
		QStringList sl = value.split( "." );
		if ( sl.count() != 2 )
			return;
		QColor col;
		col.setNamedColor( sl[ 0 ] );
		col.setAlpha( sl[ 1 ].toInt() );
		p->value = col;
	}
	else if ( type == "colorwheel" ) {
		if ( p->type != Parameter::PCOLORWHEEL )
			return;
		QColor col;
		col.setRgbF( hue.toDouble(), saturation.toDouble(), value.toDouble() );
		p->value = col;
	}
	else if ( type == "string" ) {
		if ( p->type != Parameter::PSTRING )
			return;
		p->value = value.replace( QString::fromUtf8("¶"), "\n" );
	}
	else if ( type == "shader" ) {
		if ( p->type != Parameter::PSHADEREDIT )
			return;
		p->value = value;
	}
	
	p->graph.keys.clear();
		
	QDomNodeList nodes = element.childNodes();
	for ( int i = 0; i < nodes.count(); ++i ) {
		QDomElement e = nodes.at( i ).toElement();
		if ( e.isNull() )
			continue;
		
		if ( e.tagName() == "Key" ) {
			QString ktype = e.attribute( "type" );
			QString kposition = e.attribute( "position" );
			QString kvalue = e.attribute( "value" );
			
			if ( ktype.isEmpty() || kposition.isEmpty() || kvalue.isEmpty() )
				continue;
			
			int animType = AnimationKey::LINEAR;
			if ( ktype == "constant" )
				animType = AnimationKey::CONSTANT;
			if ( ktype == "curve" )
				animType = AnimationKey::CURVE;
			
			double x = kposition.toDouble();
			if ( x > 1 || x < 0 )
				continue;
			double y = kvalue.toDouble();
			if ( y > p->max.toDouble() || y < p->min.toDouble() )
				continue;
			
			int j;
			for ( j = 0; j < p->graph.keys.count(); ++j ) {
				if ( x < p->graph.keys[ j ].x )
					break;
			}
			p->graph.keys.insert( j, AnimationKey( animType, x, p->getNormalizedKeyValue( y ) ) );
		}
	}
}
Beispiel #15
0
void KWDWriter::finishTable(int tableno, QRect rect)
{
    int ncols = 0;
    int nrows = 0;
    insidetable = false;

    int x = rect.x();
    int y = rect.y();
    int w = rect.width();
    int h = rect.height();

    QDomNodeList nl = docroot().elementsByTagName("FRAMESET");
    //FIXME calculate nrows and stuff.
    //and add empty cells for missing ones.

    // first, see how big the table is (cols & rows)
    for (int i = 0;i < nl.count();i++) {
        QDomElement k = nl.item(i).toElement();
        if (k.attribute("grpMgr") == QString("Table %1").arg(tableno)) {
            ncols = MAX(ncols, k.attribute("col").toInt() + 1);
            nrows = MAX(nrows, k.attribute("row").toInt() + 1);
        }
    }
    int curcol = 0;
    int currow = 0;
    int currow_inc = 0;
    if (ncols == 0) ncols = 1; // FIXME (floating point division by zero)
    if (nrows == 0) nrows = 1;

    int step_x = (w - x) / ncols;
    int step_y = (h - y) / nrows;


    // then, let's create the missing cells and resize them if needed.
    bool must_resize = false;
    if (x > 0) must_resize = true;
    while (currow < nrows) {
        curcol = 0;
        while (curcol < ncols) {
            QDomElement e = fetchTableCell(tableno, currow, curcol);
            if (e.isNull()) {
                // a missing cell !
                kDebug(30503) << QString("creating %1 %2").arg(currow).arg(curcol).toLatin1();
                createTableCell(tableno, currow, curcol, 1,
                                QRect(x + step_x*curcol, y + step_y*currow, step_x, step_y)
                               );
                // fixme: what to do if we don't have to resize ?
            }

            // resize this one FIXME optimize this routine
            if (must_resize == true) {
                QDomElement ee = e.firstChild().toElement(); // the frame in the frameset
                int cs = e.attribute("cols").toInt();
                int rs = e.attribute("rows").toInt();
                kDebug(30503) << "resizing";
                addRect(ee, QRect(x + step_x*curcol, 0, step_x*cs, step_y*rs));
            }
            if (curcol == 0) currow_inc = e.attribute("rows").toInt();
            curcol += e.attribute("cols").toInt();


        }
        currow += currow_inc;
    }


}
Beispiel #16
0
XDomNodeList::XDomNodeList(const QDomNodeList &from)
{
	for(int n = 0; n < from.count(); ++n)
		list += from.item(n);
}
Beispiel #17
0
void ScheduleXmlParser::parseData(const QByteArray &aData, const QString& url, int conferenceId)
{
    QDomDocument document;
    QString xml_error;
    int xml_error_line;
    int xml_error_column;
    if (!document.setContent (aData, false, &xml_error, &xml_error_line, &xml_error_column)) {
        error_message("Could not parse schedule: " + xml_error + " at line " + QString("%1").arg(xml_error_line) + " column " + QString("%1").arg(xml_error_column));
        return;
    }

    QDomElement scheduleElement = document.firstChildElement("schedule");

    sqlEngine->beginTransaction();

    QString conference_title;
    if (!scheduleElement.isNull())
    {
        QDomElement conferenceElement = scheduleElement.firstChildElement("conference");
        if (!conferenceElement.isNull())
        {
            emit(parsingScheduleBegin());
            QHash<QString,QString> conference;
            conference["id"] = QString::number(conferenceId); // conference ID is assigned automatically if 0
            conference["title"] = conferenceElement.firstChildElement("title").text();
            conference["subtitle"] = conferenceElement.firstChildElement("subtitle").text();
            conference["venue"] = conferenceElement.firstChildElement("venue").text();
            conference["city"] = conferenceElement.firstChildElement("city").text();
            conference["start"] = conferenceElement.firstChildElement("start").text(); // date
            conference["end"] = conferenceElement.firstChildElement("end").text(); // date
            conference["day_change"] = conferenceElement.firstChildElement("day_change").text(); // time
            conference["timeslot_duration"] = conferenceElement.firstChildElement("timeslot_duration").text(); // time
            conference["url"] = url;
            sqlEngine->addConferenceToDB(conference, conferenceId);
            conferenceId = conference["id"].toInt();
            conference_title = conference["title"];
        }

        // we need to get count of all events in order to emit 'progressStatus' signal
        int totalEventsCount = scheduleElement.elementsByTagName("event").count();

        // parsing day elements
        int currentEvent = 0; // hold global idx of processed event
        QDomNodeList dayList = scheduleElement.elementsByTagName("day");
        for (int i=0; i<dayList.count(); i++)
        {
            QDomElement dayElement = dayList.at(i).toElement();
            //QDate dayDate = QDate::fromString(dayElement.attribute("date"),DATE_FORMAT);
            //int dayIndex = dayElement.attribute("index").toInt();

            // parsing room elements
            QDomNodeList roomList = dayElement.elementsByTagName("room");
            for (int i=0; i<roomList.count(); i++)
            {
                QDomElement roomElement = roomList.at(i).toElement();
                // roomElement has to be 'Element' and it has to have 'name' attribute
                // TODO: 'event' has also 'room' node, so it can be unstable if that node has also 'name' attribute
                if(roomElement.hasAttribute("name"))
                {
                    // parsing event elements
                    QDomNodeList eventList = roomElement.elementsByTagName("event");
                    for (int i=0; i<eventList.count(); i++)
                    {
                        currentEvent++;
                        QDomElement eventElement = eventList.at(i).toElement();

                        // now we have all info to create ROOM/EVENT_ROOM record(s)
                        QHash<QString,QString> room;
                        room["name"] = roomElement.attribute("name");
                        room["event_id"] = eventElement.attribute("id");
                        room["conference_id"] = QString::number(conferenceId,10);
                        sqlEngine->addRoomToDB(room);

                        // process event's nodes
                        QHash<QString,QString> event;
                        event["id"] = eventElement.attribute("id");;
                        event["conference_id"] = QString::number(conferenceId, 10);
                        event["start"] = eventElement.firstChildElement("start").text(); // time eg. 10:00
                        event["date"] = dayElement.attribute("date"); // date eg. 2009-02-07
                        event["duration"] = eventElement.firstChildElement("duration").text(); // time eg. 00:30
                        event["room_name"] = eventElement.firstChildElement("room").text(); // string eg. "Janson"
                        event["tag"] = eventElement.firstChildElement("tag").text(); // string eg. "welcome"
                        event["title"] = eventElement.firstChildElement("title").text(); // string eg. "Welcome"
                        event["subtitle"] = eventElement.firstChildElement("subtitle").text(); // string
                        event["track"] = eventElement.firstChildElement("track").text(); // string eg. "Keynotes"
                        event["type"] = eventElement.firstChildElement("type").text(); // string eg. "Podium"
                        event["language"] = eventElement.firstChildElement("language").text(); // language eg. "English"
                        event["abstract"] = eventElement.firstChildElement("abstract").text(); // string
                        event["description"] = eventElement.firstChildElement("description").text(); // string
                        sqlEngine->addEventToDB(event);
                        // process persons' nodes
                        QDomElement personsElement = eventElement.firstChildElement("persons");
                        QDomNodeList personList = personsElement.elementsByTagName("person");
                        for(int i = 0;i < personList.count();i++){
                            QHash<QString,QString> person;
                            person["id"] = personList.at(i).toElement().attribute("id");
                            person["name"] = personList.at(i).toElement().text();
                            person["event_id"] = eventElement.attribute("id");
                            person["conference_id"] = QString::number(conferenceId, 10);
                            sqlEngine->addPersonToDB(person);
                        }
                        // process links' nodes
                        QDomElement linksElement = eventElement.firstChildElement("links");
                        QDomNodeList linkList = linksElement.elementsByTagName("link");
                        for(int i = 0;i < linkList.count();i++){
                            QHash<QString,QString> link;
                            link["name"] = linkList.at(i).toElement().text();
                            link["url"] = linkList.at(i).toElement().attribute("href");
                            link["event_id"] = eventElement.attribute("id");
                            link["conference_id"] = QString::number(conferenceId, 10);
                            sqlEngine->addLinkToDB(link);
                        }
                        // emit signal to inform the user about the current status (how many events are parsed so far - expressed in %)
                        int status = currentEvent * 100 / totalEventsCount;
                        progressStatus(status);
                    } // parsing event elements
                }
            } // parsing room elements
        } // parsing day elements
    } // schedule element
    sqlEngine->commitTransaction();
    if (!conference_title.isNull()) {
        emit parsingScheduleEnd(conferenceId);
    } else {
        error_message("Could not parse schedule");
    }
}
Beispiel #18
0
QString Generic::EvaluateWikiPageContents(ApiQuery *query, bool *failed, QString *ts, QString *comment, QString *user,
                                          long *revid, int *reason, QString *title)
{
    if (!failed)
    {
        throw new Huggle::Exception("failed was NULL", "QString Generic::EvaluateWikiPageContents(ApiQuery *query, "\
                                    "bool *failed, QDateTime *base, QString *comment, QString *user, int *revid)");
    }
    if (query == nullptr)
    {
        if (reason) { *reason = EvaluatePageErrorReason_NULL; }
        *failed = true;
        return "Query was NULL";
    }
    if (!query->IsProcessed())
    {
        if (reason) { *reason = EvaluatePageErrorReason_Running; }
        *failed = true;
        return "Query didn't finish";
    }
    if (query->IsFailed())
    {
        if (reason) { *reason = EvaluatePageErrorReason_Unknown; }
        *failed = true;
        return query->Result->ErrorMessage;
    }
    QDomDocument d;
    d.setContent(query->Result->Data);
    QDomNodeList page = d.elementsByTagName("rev");
    QDomNodeList code = d.elementsByTagName("page");
    if (code.count() > 0)
    {
        QDomElement e = code.at(0).toElement();
        if (title && e.attributes().contains("title"))
        {
            *title = e.attribute("title");
        }
        if (e.attributes().contains("missing"))
        {
            if (reason) { *reason = EvaluatePageErrorReason_Missing; }
            *failed = true;
            return "Page is missing";
        }
    }
    if (page.count() == 0)
    {
        if (reason) { *reason = EvaluatePageErrorReason_NoRevs; }
        *failed = true;
        return "No revisions were provided for this page";
    }
    QDomElement e = page.at(0).toElement();
    if (user && e.attributes().contains("user"))
        *user = e.attribute("user");

    if (comment && e.attributes().contains("comment"))
        *comment = e.attribute("comment");

    if (ts && e.attributes().contains("timestamp"))
        *ts = e.attribute("timestamp");

    if (revid)
    {
        if (e.attributes().contains("revid"))
            *revid = e.attribute("revid").toInt();
        else
            *revid = WIKI_UNKNOWN_REVID;
    }
    *failed = false;
    return e.text();
}
Beispiel #19
0
bool MainWindow::readXML()
{
    QFile *file = new QFile("db.xml");
    if (!file->open(QIODevice::ReadOnly)) {
        return false;
    }

    QDomDocument dom;
    if (!dom.setContent(file))  { //load xml to dom
        file->close();
        return false;
    }
    file->close();

    int flag = 0;

    // return root node
    QDomElement docElem = dom.documentElement();
    // return first child node of root node
    QDomNode node = docElem.firstChild();
    while (!node.isNull()) {
        if (node.isElement()) { // if node is element
            // change node to element
            QDomElement element = node.toElement();
            // draw this node's all child nodes && save to list
            QDomNodeList list = element.childNodes();

            for (int i = 0; i < list.count(); i++) {
                QDomNode domNode = list.at(i);
                if (domNode.isElement()) {
                    // get the data
                    switch(i) {
                    case 0:
                        ip = domNode.toElement().text();
                        qDebug() << ip;
                        break;
                    case 1:
                        port = domNode.toElement().text();
                        qDebug() << port;
                        break;
                    case 2:
                        dataBaseVersion = domNode.toElement().text();
                        qDebug() << dataBaseVersion;
                        break;
                    case 3:
                        dataBaseName = domNode.toElement().text();
                        qDebug() << dataBaseName;
                        break;
                    case 4:
                        userName = domNode.toElement().text();
                        qDebug() << userName;
                        break;
                    case 5:
                        passWord = domNode.toElement().text();
                        qDebug() << passWord;
                        break;
                    }
                }
            }
        }

        flag = 1;
        // next sibling
        node=node.nextSibling();
    }

    if (flag) {
        return true;
    }

    return false;
}
void mafViewCompoundConfigurator::parseDocument(QDomNode current, QObject *parent) {
    QDomNodeList dnl = current.childNodes();
    for (int n=0; n < dnl.count(); ++n) {
        QDomNode node = dnl.item(n);
        if (node.nodeType() == QDomNode::ElementNode) {
            QDomElement ce = node.toElement();
            QDomNamedNodeMap attributes = ce.attributes();
            QString elem_name = ce.tagName();
            if (elem_name == "splitter") {
                mafSplitter *splitter = new mafSplitter(Qt::Horizontal, (QWidget *)parent);
                if (parent == NULL) {
                    // parent is the root object, this is the first splitter created
                    m_RootObject = splitter;
                }
                QString sepThikness = attributes.namedItem("separatorThikness").nodeValue();
                QString sepEnabled = attributes.namedItem("enableSeparator").nodeValue();
                splitter->setHandleWidth(sepThikness.toInt());
                QString orientation = attributes.namedItem("orientation").nodeValue();
                if (orientation == "vertical") {
                    // Check only for vertical, horizontal is the default.
                    splitter->setOrientation(Qt::Vertical);
                }
                QStringList sizesString = attributes.namedItem("sizes").nodeValue().split(",", QString::SkipEmptyParts);
                QList<int> sizes;
                for (int s = 0; s < sizesString.count(); ++s) {
                    sizes.append(sizesString[s].toInt());
                }
                splitter->setSizes(sizes);
                // Check if there are children and parse them...
                QDomNodeList splitter_dnl = node.childNodes();
                if (splitter_dnl.count() > 0) {
                    parseDocument(node, splitter);
                }
                QSplitterHandle *handler = splitter->handle(1);
                handler->setEnabled(sepEnabled.toInt() != 0);
            } else if (elem_name == "view") {
                // view objects are added at the parent splitter.
                QString viewClassType = attributes.namedItem("classtype").nodeValue();
                // Instantiate the class type
                mafCore::mafObjectBase *obj = mafNEWFromString(viewClassType);
                // Then extract all the attributes representing the object's properties.
                int s = attributes.size();
                int i = 0;
                for (; i < s; ++i) {
                    QDomNode n(attributes.item(i));
                    if (n.nodeName() != "classtype") {
                        QByteArray ba(n.nodeName().toAscii());
                        bool isOk(obj->setProperty(ba.constData(), n.nodeValue()));
                        if (!isOk) {
                            qWarning() << mafTr("Problem assigning property named: %1 to view of type: %2").arg(n.nodeName(), viewClassType);
                        }
                    }
                }
                mafSplitter *parentSplitter = qobject_cast<mafSplitter *>(parent);
                if (parentSplitter) {
                    // and add it to the splitter.
                    parentSplitter->addView(obj);
                }
                // Check if there are children and parse them...
                QDomNodeList view_dnl = node.childNodes();
                if (view_dnl.count() > 0) {
                    parseDocument(node, obj);
                }
                // The splitter retain the view object, so we can release the instance.
                mafDEL(obj);
            } else if (elem_name == "visualpipe") {
                // Visual pipe to plug into the previous created view...
                QVariant visualPipeClassType(attributes.namedItem("classtype").nodeValue());
                QString dataType(attributes.namedItem("datatype").nodeValue());
                QVariantHash h;
                h.insert(dataType, visualPipeClassType);
                mafCore::mafObjectBase *viewObj = dynamic_cast<mafCore::mafObjectBase *>(parent);
                if (viewObj) {
                    viewObj->setProperty("visualPipeHash", h);

                    int s = attributes.size();
                    int i = 0;
                    QVariantHash propertyHash;
                    for (; i < s; ++i) {
                        QDomNode n(attributes.item(i));
                        if (n.nodeName() != "classtype" && n.nodeName() != "datatype") {
                            propertyHash.insert(n.nodeName(), n.nodeValue());
                        }
                    }
                    if (propertyHash.size() > 0) {
                        // Found some custom properties used to initialize the pipe
                        QString vp(visualPipeClassType.toString());
                        bool isOk(viewObj->metaObject()->invokeMethod(viewObj, "plugPipeParametersHashItem",
                                                    Q_ARG(QString, vp),
                                                    Q_ARG(QVariantHash, propertyHash)));
                        if (!isOk) {
                            qWarning() << mafTr("Problem invoking method used to plug the pipe's parameter for pipe: %1").arg(visualPipeClassType.toString());
                        }
                    }
                }
            } else {
                qWarning() << mafTr("Unrecognized element named: ") << elem_name;
            }
        }
    }
}
Beispiel #21
0
void Core::LoadDB()
{
    Configuration::HuggleConfiguration->ProjectList.clear();
    if (Configuration::HuggleConfiguration->Project != nullptr)
    {
        Configuration::HuggleConfiguration->ProjectList << Configuration::HuggleConfiguration->Project;
    }
    QString text = "";
    if (QFile::exists(Configuration::HuggleConfiguration->WikiDB))
    {
        QFile db(Configuration::HuggleConfiguration->WikiDB);
        if (!db.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            Syslog::HuggleLogs->ErrorLog("Unable to read " + Configuration::HuggleConfiguration->WikiDB);
            return;
        }
        text = QString(db.readAll());
        db.close();
    }

    if (text.isEmpty())
    {
        QFile vf(":/huggle/resources/Resources/Definitions.xml");
        vf.open(QIODevice::ReadOnly);
        text = QString(vf.readAll());
        vf.close();
    }

    QDomDocument d;
    d.setContent(text);
    QDomNodeList list = d.elementsByTagName("wiki");
    int xx=0;
    while (xx < list.count())
    {
        QDomElement e = list.at(xx).toElement();
        if (!e.attributes().contains("name") ||
            !e.attributes().contains("url"))
        {
            continue;
        }
        WikiSite *site = new WikiSite(e.attribute("name"), e.attribute("url"));
        site->IRCChannel = "";
        site->SupportOAuth = false;
        site->SupportHttps = false;
        site->WhiteList = "test";
        if (e.attributes().contains("path"))
            site->LongPath = e.attribute("path");
        if (e.attributes().contains("wl"))
            site->WhiteList = e.attribute("wl");
        if (e.attributes().contains("script"))
            site->ScriptPath = e.attribute("script");
        if (e.attributes().contains("https"))
            site->SupportHttps = Generic::SafeBool(e.attribute("https"));
        if (e.attributes().contains("oauth"))
            site->SupportOAuth = Generic::SafeBool(e.attribute("oauth"));
        if (e.attributes().contains("channel"))
            site->IRCChannel = e.attribute("channel");
        if (e.attributes().contains("rtl"))
            site->IsRightToLeft = Generic::SafeBool(e.attribute("rtl"));
        if (e.attributes().contains("han_irc"))
            site->HANChannel = e.attribute("han_irc");
        if (e.attributes().contains("xmlrcs_name"))
            site->XmlRcsName = e.attribute("xmlrcs_name");
        if (e.attributes().contains("ssl_required"))
            site->ForceSSL = Generic::SafeBool(e.attribute("ssl_required"));
        Configuration::HuggleConfiguration->ProjectList.append(site);
        xx++;
    }
}
Beispiel #22
0
QString odkFormReader::getFieldType(QString itemID)
{
    QDomNodeList list;
    QDomElement item;
    list = doc.elementsByTagName("bind");
    int pos;
    QString res;
    res = "Unknown";
    for (pos = 0; pos <= list.count()-1;pos++)
    {
        item = list.item(pos).toElement();
        if (item.attribute("nodeset","Unknown") == itemID)
        {
            if (item.attribute("readonly","NOP") == "NOP")
            {
                res = item.attribute("type","Unknown");
                break;
            }
            else
            {
                res = "READONLY";
                break;
            }
        }
    }
    if (res == "Unknown")
        return res;

    if (res != "READONLY")
    {
        if (res == "string")
        {
            return "varchar|255";
        }
        if (res == "decimal")
        {
            return "decimal|7,3";
        }
        if (res == "int")
        {
            return "int|9";
        }
        if (res == "select")
        {
            return "int|9"; //This has to change to a different table to store the values
        }
        if (res == "select1")
        {
            return "int|9";
        }
        if (res == "int")
        {
            return "int|9";
        }
        if (res == "date")
        {
            return "date";
        }
        if (res == "time")
        {
            return "time";
        }
        return "varchar|255";
    }
    else
        return res;
}
Beispiel #23
0
void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillParam, bool& hasDefaultFill, QColor& defaultFill,
                                      bool& hasFillOpacityParam, bool& hasDefaultFillOpacity, double& defaultFillOpacity,
                                      bool& hasOutlineParam, bool& hasDefaultOutline, QColor& defaultOutline,
                                      bool& hasOutlineWidthParam, bool& hasDefaultOutlineWidth, double& defaultOutlineWidth,
                                      bool& hasOutlineOpacityParam, bool& hasDefaultOutlineOpacity, double& defaultOutlineOpacity ) const
{
  if ( elem.isNull() )
  {
    return;
  }

  //we already have all the information, no need to go deeper
  if ( hasFillParam && hasOutlineParam && hasOutlineWidthParam && hasFillOpacityParam && hasOutlineOpacityParam )
  {
    return;
  }

  //check this elements attribute
  QDomNamedNodeMap attributes = elem.attributes();
  int nAttributes = attributes.count();

  QStringList valueSplit;
  for ( int i = 0; i < nAttributes; ++i )
  {
    QDomAttr attribute = attributes.item( i ).toAttr();
    if ( attribute.name().compare( QLatin1String( "style" ), Qt::CaseInsensitive ) == 0 )
    {
      //entries separated by ';'
      QStringList entryList = attribute.value().split( ';' );
      QStringList::const_iterator entryIt = entryList.constBegin();
      for ( ; entryIt != entryList.constEnd(); ++entryIt )
      {
        QStringList keyValueSplit = entryIt->split( ':' );
        if ( keyValueSplit.size() < 2 )
        {
          continue;
        }
        QString value = keyValueSplit.at( 1 );
        valueSplit = value.split( ' ' );
        if ( !hasFillParam && value.startsWith( QLatin1String( "param(fill)" ) ) )
        {
          hasFillParam = true;
          if ( valueSplit.size() > 1 )
          {
            defaultFill = QColor( valueSplit.at( 1 ) );
            hasDefaultFill = true;
          }
        }
        else if ( !hasFillOpacityParam && value.startsWith( QLatin1String( "param(fill-opacity)" ) ) )
        {
          hasFillOpacityParam = true;
          if ( valueSplit.size() > 1 )
          {
            bool ok;
            double opacity = valueSplit.at( 1 ).toDouble( &ok );
            if ( ok )
            {
              defaultFillOpacity = opacity;
              hasDefaultFillOpacity = true;
            }
          }
        }
        else if ( !hasOutlineParam && value.startsWith( QLatin1String( "param(outline)" ) ) )
        {
          hasOutlineParam = true;
          if ( valueSplit.size() > 1 )
          {
            defaultOutline = QColor( valueSplit.at( 1 ) );
            hasDefaultOutline = true;
          }
        }
        else if ( !hasOutlineWidthParam && value.startsWith( QLatin1String( "param(outline-width)" ) ) )
        {
          hasOutlineWidthParam = true;
          if ( valueSplit.size() > 1 )
          {
            defaultOutlineWidth = valueSplit.at( 1 ).toDouble();
            hasDefaultOutlineWidth = true;
          }
        }
        else if ( !hasOutlineOpacityParam && value.startsWith( QLatin1String( "param(outline-opacity)" ) ) )
        {
          hasOutlineOpacityParam = true;
          if ( valueSplit.size() > 1 )
          {
            bool ok;
            double opacity = valueSplit.at( 1 ).toDouble( &ok );
            if ( ok )
            {
              defaultOutlineOpacity = opacity;
              hasDefaultOutlineOpacity = true;
            }
          }
        }
      }
    }
    else
    {
      QString value = attribute.value();
      valueSplit = value.split( ' ' );
      if ( !hasFillParam && value.startsWith( QLatin1String( "param(fill)" ) ) )
      {
        hasFillParam = true;
        if ( valueSplit.size() > 1 )
        {
          defaultFill = QColor( valueSplit.at( 1 ) );
          hasDefaultFill = true;
        }
      }
      else if ( !hasFillOpacityParam && value.startsWith( QLatin1String( "param(fill-opacity)" ) ) )
      {
        hasFillOpacityParam = true;
        if ( valueSplit.size() > 1 )
        {
          bool ok;
          double opacity = valueSplit.at( 1 ).toDouble( &ok );
          if ( ok )
          {
            defaultFillOpacity = opacity;
            hasDefaultFillOpacity = true;
          }
        }
      }
      else if ( !hasOutlineParam && value.startsWith( QLatin1String( "param(outline)" ) ) )
      {
        hasOutlineParam = true;
        if ( valueSplit.size() > 1 )
        {
          defaultOutline = QColor( valueSplit.at( 1 ) );
          hasDefaultOutline = true;
        }
      }
      else if ( !hasOutlineWidthParam && value.startsWith( QLatin1String( "param(outline-width)" ) ) )
      {
        hasOutlineWidthParam = true;
        if ( valueSplit.size() > 1 )
        {
          defaultOutlineWidth = valueSplit.at( 1 ).toDouble();
          hasDefaultOutlineWidth = true;
        }
      }
      else if ( !hasOutlineOpacityParam && value.startsWith( QLatin1String( "param(outline-opacity)" ) ) )
      {
        hasOutlineOpacityParam = true;
        if ( valueSplit.size() > 1 )
        {
          bool ok;
          double opacity = valueSplit.at( 1 ).toDouble( &ok );
          if ( ok )
          {
            defaultOutlineOpacity = opacity;
            hasDefaultOutlineOpacity = true;
          }
        }
      }
    }
  }

  //pass it further to child items
  QDomNodeList childList = elem.childNodes();
  int nChildren = childList.count();
  for ( int i = 0; i < nChildren; ++i )
  {
    QDomElement childElem = childList.at( i ).toElement();
    containsElemParams( childElem, hasFillParam, hasDefaultFill, defaultFill,
                        hasFillOpacityParam, hasDefaultFillOpacity, defaultFillOpacity,
                        hasOutlineParam, hasDefaultOutline, defaultOutline,
                        hasOutlineWidthParam, hasDefaultOutlineWidth, defaultOutlineWidth,
                        hasOutlineOpacityParam, hasDefaultOutlineOpacity, defaultOutlineOpacity );
  }
}
void NineMLLayoutData::import_parameters_from_xml(QDomNode &nIn)
{
    type = NineMLLayoutType;

    this->seed = nIn.toElement().attribute("seed","123").toInt();
    this->minimumDistance = nIn.toElement().attribute("minimum_distance","0.0").toDouble();

    QDomNodeList nList = nIn.toElement().elementsByTagName("Property");

    for (int node = 0; node < nList.count(); ++node) {
        QDomNode n = nList.item(node);

        // extract value and dimensions from node
        QString propName = n.toElement().attribute("name","");
        if (propName == "") {
            // error
            QSettings settings;
            int num_errs = settings.beginReadArray("errors");
            settings.endArray();
            settings.beginWriteArray("errors");
                settings.setArrayIndex(num_errs + 1);
                settings.setValue("errorText",  "XML error: attribute 'name' not found in tag 'Property'");
            settings.endArray();
        }

        bool parFound = false;

        for (uint i = 0; i < this->ParameterList.size(); ++i) {
            if (propName == this->ParameterList[i]->name) {
                parFound = true;
                QDomNodeList propVal = n.toElement().elementsByTagName("FixedValue");
                if (propVal.size() == 1) {
                    this->ParameterList[i]->value[0] = propVal.at(0).toElement().attribute("value","").toDouble();
                }
                break;
            }
        }
        if (!parFound) {
            for (uint i = 0; i < this->StateVariableList.size(); ++i) {
                if (propName == this->StateVariableList[i]->name) {
                    parFound = true;
                    QDomNodeList propVal = n.toElement().elementsByTagName("FixedValue");
                    if (propVal.size() == 1) {
                        this->StateVariableList[i]->value[0] = propVal.at(0).toElement().attribute("value","").toDouble();
                    }
                    break;
                }
            }
        }

        if (!parFound) {
            // error
            QSettings settings;
            int num_errs = settings.beginReadArray("errors");
            settings.endArray();
            settings.beginWriteArray("errors");
                settings.setArrayIndex(num_errs + 1);
                settings.setValue("errorText",  "Error: property '" + propName + "' not found in Layout");
            settings.endArray();
        }
    }
}
void ORGraphicsSectionDetail::initFromXML(QDomNode & section)
{
  QDomNodeList nl = section.childNodes();
  QDomNode node;
  QString n;

  // some code to handle old style defs
  QString o_name = "unnamed";
  QString o_column = QString::null;
  bool old_head = false;
  QDomNode o_head;
  bool old_foot = false;
  QDomNode o_foot;

  for(int i = 0; i < nl.count(); i++) {
    node = nl.item(i);
    n = node.nodeName();
    if(n == "name") {
      o_name = node.firstChild().nodeValue();
      setTitle(o_name);
    } else if(n == "pagebreak") {
      QDomElement eThis = node.toElement();
      if(eThis.attribute("when") == "at end")
        setPageBreak(BreakAtEnd);
    } else if(n == "group") {
      ORGraphicsSectionDetailGroup * rsdg = new ORGraphicsSectionDetailGroup("unnamed", this, this);
      QDomNodeList gnl = node.childNodes();
      QDomNode gnode;
      bool show_head = false;
      bool show_foot = false;
      for(int gi = 0; gi < gnl.count(); gi++) {
        gnode = gnl.item(gi);
        if(gnode.nodeName() == "name") {
          rsdg->setTitle(gnode.firstChild().nodeValue());
        } else if(gnode.nodeName() == "column") {
          rsdg->setColumn(gnode.firstChild().nodeValue());
        } else if(gnode.nodeName() == "pagebreak") {
          QDomElement elemThis = gnode.toElement();
          QString n = elemThis.attribute("when");
          if("after foot" == n)
            rsdg->setPageBreak(ORGraphicsSectionDetailGroup::BreakAfterGroupFooter);
        } else if(gnode.nodeName() == "head") {
          rsdg->getGroupHead()->initFromXML(gnode);
          rsdg->showGroupHead(true);
          show_head = true;
        } else if(gnode.nodeName() == "foot") {
          rsdg->getGroupFoot()->initFromXML(gnode);
          rsdg->showGroupFoot(true);
          show_foot = true;
        } else {
          qDebug("encountered unknown element while parsing group element: %s", gnode.nodeName().toLatin1().constData());
        }
      }
      insertSection(groupSectionCount(), rsdg);
      rsdg->showGroupHead(show_head);
      rsdg->showGroupFoot(show_foot);
    } else if(n == "grouphead") {
      o_head = node;
      old_head = true;
    } else if(n == "groupfoot") {
      o_foot = node;
      old_foot = true;
    } else if(n == "detail") {
      // need to pull out the query key values
      QDomNode key = node.namedItem("key");
      if(key.isNull()) {
        qDebug("Did not find a key element while parsing detail section");
      } else {
        QDomNodeList knl = key.childNodes();
        QDomNode knode;
        for(int ki = 0; ki < knl.count(); ki++) {
          knode = knl.item(ki);
          if(knode.nodeName() == "query") {
            setQuery(knode.firstChild().nodeValue());
          } else if(knode.nodeName() == "column") {
            o_column = knode.firstChild().nodeValue();
          } else {
            qDebug("encountered unknown element while parsing key element: %s", knode.nodeName().toLatin1().constData());
          }
        }
      }
      _detail->initFromXML(node);
    } else {
      // unknown element
      qDebug("while parsing section encountered and unknown element: %s", n.toLatin1().constData());
    }
  }

  if(old_head || old_foot) {
    ORGraphicsSectionDetailGroup * rsdg = new ORGraphicsSectionDetailGroup(o_name, this, this);

    rsdg->setColumn(o_column);
    if(old_head)
      rsdg->getGroupHead()->initFromXML(o_head);
    if(old_foot)
      rsdg->getGroupFoot()->initFromXML(o_foot);

    // if we encountered this situation then we shouldn't have
    // any other sections but to be sure we will just tack this one
    // onto the end
    insertSection(groupSectionCount(), rsdg);

    rsdg->showGroupHead(old_head);
    rsdg->showGroupFoot(old_foot);
  }
}
Beispiel #26
0
bool SOAPClient::SendSOAPRequest( const QString    &sMethod, 
                                        QStringMap &list, 
                                        int        &nErrCode, 
                                        QString    &sErrDesc,
                                        bool        bInQtThread )
{
    QUrl url( m_url );

    url.setPath( m_sControlPath );

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------

    QHttpRequestHeader header;

    header.setValue("CONTENT-TYPE", "text/xml; charset=\"utf-8\"" );
    header.setValue("SOAPACTION"  , QString( "\"%1#GetConnectionInfo\"" )
                                       .arg( m_sNamespace ));

    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for ( QStringMap::iterator it  = list.begin(); 
                               it != list.end(); 
                             ++it ) 
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    QBuffer     buff( &aBuffer );

    QString sXml = HttpComms::postHttp( url, 
                                        &header,
                                        (QIODevice *)&buff,
                                        10000, // ms
                                        3,     // retries
                                        0,     // redirects
                                        false, // allow gzip
                                        NULL,  // login
                                        bInQtThread );

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    list.clear();

    QDomDocument doc;

    if ( !doc.setContent( sXml, true, &sErrDesc, &nErrCode ))
    {
        VERBOSE( VB_UPNP, QString( "MythXMLClient::SendSOAPRequest( %1 ) - Invalid response from %2" )
                             .arg( sMethod   )
                             .arg( url.toString() ));
        return false;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     = doc.elementsByTagNameNS( m_sNamespace, sResponseName );

    if (oNodeList.count() > 0)
    {
        QDomNode oMethod = oNodeList.item(0);

        if (!oMethod.isNull())
        {

            for ( QDomNode oNode = oMethod.firstChild(); !oNode.isNull(); 
                           oNode = oNode.nextSibling() )
            {
                QDomElement e = oNode.toElement();

                if (!e.isNull())
                {
                    QString sName  = e.tagName();
                    QString sValue = "";
    
                    QDomText  oText = oNode.firstChild().toText();
    
                    if (!oText.isNull())
                        sValue = oText.nodeValue();

                    list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                                QUrl::fromPercentEncoding(sValue.toUtf8()));
                }
            }
        }

        return true;
    }

    // --------------------------------------------------------------
    // Must be a fault... parse it to return reason
    // --------------------------------------------------------------

    nErrCode = GetNodeValue( doc, "Envelope/Body/Fault/detail/UPnPResult/errorCode"       , 500 );
    sErrDesc = GetNodeValue( doc, "Envelope/Body/Fault/detail/UPnPResult/errorDescription", QString( "Unknown" ));

    return false;
}
Beispiel #27
0
void MythBurn::loadEncoderProfiles()
{
    EncoderProfile *item = new EncoderProfile;
    item->name = "NONE";
    item->description = "";
    item->bitrate = 0.0f;
    m_profileList.append(item);

    // find the encoding profiles
    // first look in the ConfDir (~/.mythtv)
    QString filename = GetConfDir() +
            "/MythArchive/ffmpeg_dvd_" +
            ((gCoreContext->GetSetting("MythArchiveVideoFormat", "pal")
                .toLower() == "ntsc") ? "ntsc" : "pal") + ".xml";

    if (!QFile::exists(filename))
    {
        // not found yet so use the default profiles
        filename = GetShareDir() +
            "mytharchive/encoder_profiles/ffmpeg_dvd_" +
            ((gCoreContext->GetSetting("MythArchiveVideoFormat", "pal")
                .toLower() == "ntsc") ? "ntsc" : "pal") + ".xml";
    }

    LOG(VB_GENERAL, LOG_NOTICE,
        "MythArchive: Loading encoding profiles from " + filename);

    QDomDocument doc("mydocument");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return;

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

    QDomElement docElem = doc.documentElement();
    QDomNodeList profileNodeList = doc.elementsByTagName("profile");
    QString name, desc, bitrate;

    for (int x = 0; x < (int) profileNodeList.count(); x++)
    {
        QDomNode n = profileNodeList.item(x);
        QDomElement e = n.toElement();
        QDomNode n2 = e.firstChild();
        while (!n2.isNull())
        {
            QDomElement e2 = n2.toElement();
            if(!e2.isNull())
            {
                if (e2.tagName() == "name")
                    name = e2.text();
                if (e2.tagName() == "description")
                    desc = e2.text();
                if (e2.tagName() == "bitrate")
                    bitrate = e2.text();

            }
            n2 = n2.nextSibling();

        }

        EncoderProfile *item = new EncoderProfile;
        item->name = name;
        item->description = desc;
        item->bitrate = bitrate.toFloat();
        m_profileList.append(item);
    }
}
Beispiel #28
0
  QDomDocument createTransactionDocument( QgsServerInterface* serverIface, const QString& version,
                                          const QgsServerRequest& request )
  {
    Q_UNUSED( version );

    QDomDocument doc;

    QgsWfsProjectParser* configParser = getConfigParser( serverIface );
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl* accessControl = serverIface->accessControls();
#endif
    const QString requestBody = request.getParameter( QStringLiteral( "REQUEST_BODY" ) );

    QString errorMsg;
    if ( !doc.setContent( requestBody, true, &errorMsg ) )
    {
      throw QgsRequestNotWellFormedException( errorMsg );
    }

    QDomElement docElem = doc.documentElement();
    QDomNodeList docChildNodes = docElem.childNodes();

    // Re-organize the transaction document
    QDomDocument mDoc;
    QDomElement mDocElem = mDoc.createElement( QStringLiteral( "myTransactionDocument" ) );
    mDocElem.setAttribute( QStringLiteral( "xmlns" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:wfs" ), WFS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    mDoc.appendChild( mDocElem );

    QDomElement actionElem;
    QString actionName;
    QDomElement typeNameElem;
    QString typeName;

    for ( int i = docChildNodes.count(); 0 < i; --i )
    {
      actionElem = docChildNodes.at( i - 1 ).toElement();
      actionName = actionElem.localName();

      if ( actionName == QLatin1String( "Insert" ) )
      {
        QDomElement featureElem = actionElem.firstChild().toElement();
        typeName = featureElem.localName();
      }
      else if ( actionName == QLatin1String( "Update" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }
      else if ( actionName == QLatin1String( "Delete" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }

      if ( typeName.contains( QLatin1String( ":" ) ) )
        typeName = typeName.section( QStringLiteral( ":" ), 1, 1 );

      QDomNodeList typeNameList = mDocElem.elementsByTagName( typeName );
      if ( typeNameList.count() == 0 )
      {
        typeNameElem = mDoc.createElement( typeName );
        mDocElem.appendChild( typeNameElem );
      }
      else
        typeNameElem = typeNameList.at( 0 ).toElement();

      typeNameElem.appendChild( actionElem );
    }

    // It's time to make the transaction
    // Create the response document
    QDomDocument resp;
    //wfs:WFS_TransactionRespone element
    QDomElement respElem = resp.createElement( QStringLiteral( "WFS_TransactionResponse" )/*wfs:WFS_TransactionResponse*/ );
    respElem.setAttribute( QStringLiteral( "xmlns" ), WFS_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    respElem.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/wfs.xsd" );
    respElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) );
    resp.appendChild( respElem );

    // Store the created feature id for WFS
    QStringList insertResults;
    // Get the WFS layers id
    QStringList wfsLayersId = configParser->wfsLayers();;

    QList<QgsMapLayer*> layerList;
    QgsMapLayer* currentLayer = nullptr;

    // Loop through the layer transaction elements
    docChildNodes = mDocElem.childNodes();
    for ( int i = 0; i < docChildNodes.count(); ++i )
    {
      // Get the vector layer
      typeNameElem = docChildNodes.at( i ).toElement();
      typeName = typeNameElem.tagName();

      layerList = configParser->mapLayerFromTypeName( typeName );
      // Could be empty!
      if ( layerList.count() > 0 )
      {
        currentLayer = layerList.at( 0 );
      }
      else
      {
        throw QgsRequestNotWellFormedException( QStringLiteral( "Wrong TypeName: %1" ).arg( typeName ) );
      }

      QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( currentLayer );
      // it's a vectorlayer and defined by the administrator as a WFS layer
      if ( layer && wfsLayersId.contains( layer->id() ) )
      {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        if ( actionName == QLatin1String( "Insert" ) )
        {
          if ( !accessControl->layerInsertPermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature insert permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Update" ) )
        {
          if ( !accessControl->layerUpdatePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature update permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Delete" ) )
        {
          if ( !accessControl->layerDeletePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature delete permission denied" ) );
          }
        }
#endif

        // Get the provider and it's capabilities
        QgsVectorDataProvider* provider = layer->dataProvider();
        if ( !provider )
        {
          continue;
        }

        int cap = provider->capabilities();

        // Start the update transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::ChangeAttributeValues ) && ( cap & QgsVectorDataProvider::ChangeGeometries ) )
        {
          // Loop through the update elements for this layer
          QDomNodeList upNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Update" ) );
          for ( int j = 0; j < upNodeList.count(); ++j )
          {
            if ( !configParser->wfstUpdateLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS updates on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Update" ), errorMsg );
              return resp;
            }

            actionElem = upNodeList.at( j ).toElement();

            // Get the Feature Ids for this filter on the layer
            QDomElement filterElem = actionElem.elementsByTagName( QStringLiteral( "Filter" ) ).at( 0 ).toElement();
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

            // Loop through the property elements
            // Store properties and the geometry element
            QDomNodeList propertyNodeList = actionElem.elementsByTagName( QStringLiteral( "Property" ) );
            QMap<QString, QString> propertyMap;
            QDomElement propertyElem;
            QDomElement nameElem;
            QDomElement valueElem;
            QDomElement geometryElem;

            for ( int l = 0; l < propertyNodeList.count(); ++l )
            {
              propertyElem = propertyNodeList.at( l ).toElement();
              nameElem = propertyElem.elementsByTagName( QStringLiteral( "Name" ) ).at( 0 ).toElement();
              valueElem = propertyElem.elementsByTagName( QStringLiteral( "Value" ) ).at( 0 ).toElement();
              if ( nameElem.text() != QLatin1String( "geometry" ) )
              {
                propertyMap.insert( nameElem.text(), valueElem.text() );
              }
              else
              {
                geometryElem = valueElem;
              }
            }

            // Update the features
            QgsFields fields = provider->fields();
            QMap<QString, int> fieldMap = provider->fieldNameMap();
            QMap<QString, int>::const_iterator fieldMapIt;
            QString fieldName;
            bool conversionSuccess;

            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif

              QMap< QString, QString >::const_iterator it = propertyMap.constBegin();
              for ( ; it != propertyMap.constEnd(); ++it )
              {
                fieldName = it.key();
                fieldMapIt = fieldMap.find( fieldName );
                if ( fieldMapIt == fieldMap.constEnd() )
                {
                  continue;
                }
                QgsField field = fields.at( fieldMapIt.value() );
                if ( field.type() == 2 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toInt( &conversionSuccess ) );
                else if ( field.type() == 6 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toDouble( &conversionSuccess ) );
                else
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value() );
              }

              if ( !geometryElem.isNull() )
              {
                QgsGeometry g = QgsOgcUtils::geometryFromGML( geometryElem );
                if ( !layer->changeGeometry( *fidIt, g ) )
                {
                  throw QgsRequestNotWellFormedException( QStringLiteral( "Error in change geometry" ) );
                }
              }

#ifdef HAVE_SERVER_PYTHON_PLUGINS
              fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  layer->rollBack();
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif
            }
          }
        }
        // Commit the changes of the update elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Update" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }
        // Start the delete transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::DeleteFeatures ) )
        {
          // Loop through the delete elements
          QDomNodeList delNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Delete" ) );
          for ( int j = 0; j < delNodeList.count(); ++j )
          {
            if ( !configParser->wfstDeleteLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS deletes on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Delete" ), errorMsg );
              return resp;
            }

            actionElem = delNodeList.at( j ).toElement();
            QDomElement filterElem = actionElem.firstChild().toElement();
            // Get Feature Ids for the Filter element
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

#ifdef HAVE_SERVER_PYTHON_PLUGINS
            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
            }
#endif

            layer->selectByIds( fids );
            layer->deleteSelectedFeatures();
          }
        }
        // Commit the changes of the delete elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Delete" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }

        // Store the inserted features
        QgsFeatureList inFeatList;
        if ( cap & QgsVectorDataProvider::AddFeatures )
        {
          // Get Layer Field Information
          QgsFields fields = provider->fields();
          QMap<QString, int> fieldMap = provider->fieldNameMap();
          QMap<QString, int>::const_iterator fieldMapIt;

          // Loop through the insert elements
          QDomNodeList inNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Insert" ) );
          for ( int j = 0; j < inNodeList.count(); ++j )
          {
            if ( !configParser->wfstInsertLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS inserts on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Insert" ), errorMsg );
              return resp;
            }

            actionElem = inNodeList.at( j ).toElement();
            // Loop through the feature element
            QDomNodeList featNodes = actionElem.childNodes();
            for ( int l = 0; l < featNodes.count(); l++ )
            {
              // Add the feature to the layer
              // and store it to put it's Feature Id in the response
              inFeatList << QgsFeature( fields );

              // Create feature for this layer
              QDomElement featureElem = featNodes.at( l ).toElement();

              QDomNode currentAttributeChild = featureElem.firstChild();

              while ( !currentAttributeChild.isNull() )
              {
                QDomElement currentAttributeElement = currentAttributeChild.toElement();
                QString attrName = currentAttributeElement.localName();

                if ( attrName != QLatin1String( "boundedBy" ) )
                {
                  if ( attrName != QLatin1String( "geometry" ) ) //a normal attribute
                  {
                    fieldMapIt = fieldMap.find( attrName );
                    if ( fieldMapIt == fieldMap.constEnd() )
                    {
                      continue;
                    }
                    QgsField field = fields.at( fieldMapIt.value() );
                    QString attrValue = currentAttributeElement.text();
                    int attrType = field.type();
                    QgsMessageLog::logMessage( QStringLiteral( "attr: name=%1 idx=%2 value=%3" ).arg( attrName ).arg( fieldMapIt.value() ).arg( attrValue ) );
                    if ( attrType == QVariant::Int )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toInt() );
                    else if ( attrType == QVariant::Double )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toDouble() );
                    else
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue );
                  }
                  else //a geometry attribute
                  {
                    QgsGeometry g = QgsOgcUtils::geometryFromGML( currentAttributeElement );
                    inFeatList.last().setGeometry( g );
                  }
                }
                currentAttributeChild = currentAttributeChild.nextSibling();
              }
            }
          }
        }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        QgsFeatureList::iterator featureIt = inFeatList.begin();
        while ( featureIt != inFeatList.end() )
        {
          if ( !accessControl->allowToEdit( layer, *featureIt ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
          }
          featureIt++;
        }
#endif

        // add the features
        if ( !provider->addFeatures( inFeatList ) )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "Partial" ), QStringLiteral( "Insert" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          if ( provider->hasErrors() )
          {
            provider->clearErrors();
          }
          return resp;
        }
        // Get the Feature Ids of the inserted feature
        for ( int j = 0; j < inFeatList.size(); j++ )
        {
          insertResults << typeName + "." + QString::number( inFeatList[j].id() );
        }
      }
    }

    // Put the Feature Ids of the inserted feature
    if ( !insertResults.isEmpty() )
    {
      Q_FOREACH ( const QString &fidStr, insertResults )
      {
        QDomElement irElem = doc.createElement( QStringLiteral( "InsertResult" ) );
        QDomElement fiElem = doc.createElement( QStringLiteral( "ogc:FeatureId" ) );
        fiElem.setAttribute( QStringLiteral( "fid" ), fidStr );
        irElem.appendChild( fiElem );
        respElem.appendChild( irElem );
      }
Beispiel #29
0
bool parseReport(const QDomElement & elemSource, ORReportData & reportTarget)
{
  if(elemSource.tagName() != "report")
  {
    qDebug("QDomElement passed to parseReport() was not <report> tag");
    return FALSE;
  }

  double d = 0.0;
  bool valid = FALSE;

  QDomNodeList section = elemSource.childNodes();
  for(int nodeCounter = 0; nodeCounter < section.count(); nodeCounter++)
  {
    QDomElement elemThis = section.item(nodeCounter).toElement();
    if(elemThis.tagName() == "title")
      reportTarget.title = elemThis.text();
    else if(elemThis.tagName() == "name")
      reportTarget.name = elemThis.text();
    else if(elemThis.tagName() == "description")
      reportTarget.description = elemThis.text();
    else if(elemThis.tagName() == "parameter")
    {
      parseReportParameter(elemThis, reportTarget);
    }
    else if(elemThis.tagName() == "watermark")
      parseReportWatermark(elemThis, reportTarget.wmData);
    else if(elemThis.tagName() == "background")
      parseReportBackground(elemThis, reportTarget.bgData);
    else if(elemThis.tagName() == "size")
    {
      if(elemThis.firstChild().isText())
        reportTarget.page.setPageSize(elemThis.firstChild().nodeValue());
      else
      {
        //bad code! bad code!
        // this code doesn't check the elemts and assums they are what
        // they should be.
        QDomNode n1 = elemThis.firstChild();
        QDomNode n2 = n1.nextSibling();
        if(n1.nodeName() == "width")
        {
          reportTarget.page.setCustomWidth(n1.firstChild().nodeValue().toDouble() / 100.0);
          reportTarget.page.setCustomHeight(n2.firstChild().nodeValue().toDouble() / 100.0);
        }
        else
        {
          reportTarget.page.setCustomWidth(n2.firstChild().nodeValue().toDouble() / 100.0);
          reportTarget.page.setCustomHeight(n1.firstChild().nodeValue().toDouble() / 100.0);
        }
        reportTarget.page.setPageSize("Custom");
      }
    }
    else if(elemThis.tagName() == "labeltype")
      reportTarget.page.setLabelType(elemThis.firstChild().nodeValue());
    else if(elemThis.tagName() == "portrait")
      reportTarget.page.setPortrait(TRUE);
    else if(elemThis.tagName() == "landscape")
      reportTarget.page.setPortrait(FALSE);
    else if(elemThis.tagName() == "topmargin")
    {
      d = elemThis.text().toDouble(&valid);
      if(!valid || d < 0.0)
      {
        qDebug("Error converting topmargin value: %s",(const char*)elemThis.text());
        d = 50.0;
      }
      reportTarget.page.setMarginTop((d / 100.0));
    }
    else if(elemThis.tagName() == "bottommargin")
    {
      d = elemThis.text().toDouble(&valid);
      if(!valid || d < 0.0)
      {
        qDebug("Error converting bottommargin value: %s",(const char*)elemThis.text());
        d = 50.0;
      }
      reportTarget.page.setMarginBottom((d / 100.0));
    }
    else if(elemThis.tagName() == "leftmargin")
    {
      d = elemThis.text().toDouble(&valid);
      if(!valid || d < 0.0)
      {
        qDebug("Error converting leftmargin value: %s",(const char*)elemThis.text());
        d = 50.0;
      }
      reportTarget.page.setMarginLeft(d/100.0);
    }
    else if(elemThis.tagName() == "rightmargin")
    {
      d = elemThis.text().toDouble(&valid);
      if(!valid || d < 0.0)
      {
        qDebug("Error converting rightmargin value: %s",(const char*)elemThis.text());
        d = 50.0;
      }
      reportTarget.page.setMarginRight(d/100.0);
    }
    else if(elemThis.tagName() == "querysource")
    {
      // we need to read in the query sources
      QString qsname = elemThis.namedItem("name").toElement().text();
      QString qsquery = elemThis.namedItem("sql").toElement().text();
      reportTarget.queries.add(new QuerySource(qsname,qsquery));
    }
    else if(elemThis.tagName() == "rpthead")
    {
      ORSectionData * sd = new ORSectionData();
      if(parseReportSection(elemThis, *sd) == TRUE)
      {
        reportTarget.rpthead = sd;
        reportTarget.trackTotal += sd->trackTotal;
      }
      else
        delete sd;
    }
    else if(elemThis.tagName() == "rptfoot")
    {
      ORSectionData * sd = new ORSectionData();
      if(parseReportSection(elemThis, *sd) == TRUE)
      {
        reportTarget.rptfoot = sd;
        reportTarget.trackTotal += sd->trackTotal;
      }
      else
        delete sd;
    }
    else if(elemThis.tagName() == "pghead")
    {
      ORSectionData * sd = new ORSectionData();
      if(parseReportSection(elemThis, *sd) == TRUE)
      {
        if(sd->extra == "firstpage")
          reportTarget.pghead_first = sd;
        else if(sd->extra == "odd")
          reportTarget.pghead_odd = sd;
        else if(sd->extra == "even")
          reportTarget.pghead_even = sd;
        else if(sd->extra == "lastpage")
          reportTarget.pghead_last = sd;
        else if(sd->extra == QString::null)
          reportTarget.pghead_any = sd;
        else
        {
          qDebug("don't know which page this page header is for: %s",(const char*)sd->extra);
          delete sd;
        }
        reportTarget.trackTotal += sd->trackTotal;
      }
      else
        delete sd;
    }
    else if(elemThis.tagName() == "pgfoot")
    {
      ORSectionData * sd = new ORSectionData();
      if(parseReportSection(elemThis, *sd) == TRUE) {
        if(sd->extra == "firstpage")
          reportTarget.pgfoot_first = sd;
        else if(sd->extra == "odd")
          reportTarget.pgfoot_odd = sd;
        else if(sd->extra == "even")
          reportTarget.pgfoot_even = sd;
        else if(sd->extra == "lastpage")
          reportTarget.pgfoot_last = sd;
        else if(sd->extra == QString::null)
          reportTarget.pgfoot_any = sd;
        else
        {
          qDebug("don't know which page this page footer is for: %s",(const char*)sd->extra);
          delete sd;
        }
        reportTarget.trackTotal += sd->trackTotal;
      }
      else
        delete sd;
    }
    else if(elemThis.tagName() == "section")
    {
      ORDetailSectionData * dsd = new ORDetailSectionData();
      if(parseReportDetailSection(elemThis, *dsd) == TRUE)
      {
        reportTarget.sections.append(dsd);
        reportTarget.trackTotal += dsd->trackTotal;
      }
      else
        delete dsd;
    }
    else if(elemThis.tagName() == "colordef")
    {
      ORColorDefData coldef;
      if(parseReportColorDefData(elemThis, coldef) == TRUE)
      {
        QColor col(coldef.red, coldef.green, coldef.blue);
        reportTarget.color_map[coldef.name] = col;
      }
    }
    else if(elemThis.tagName() == "database")
    {
      MemDbLoader mdb;
      bool ok = mdb.load(elemThis);
      if(!ok)
        qDebug(mdb.lastError());
    }
    else
      qDebug("While parsing report encountered an unknown element: %s",(const char*)elemThis.tagName());
  }

  return TRUE;
}
Beispiel #30
0
EList KalziumDataObject::readData(  QDomDocument &dataDocument )
{
	EList list;
	QDomNodeList elementNodes; //the list of all element
	QDomElement  domElement;   //a single element

	//read in all elements
	elementNodes = dataDocument.elementsByTagName( "element" );

	const uint count = elementNodes.count();

	for ( uint i = 0; i < count; ++i )
	{//iterate through all elements
		domElement = ( const QDomElement& ) elementNodes.item( i ).toElement();

		double mass = domElement.namedItem( "mass" ).toElement().text().toDouble();
		double en = domElement.namedItem( "electronegativity" ).toElement().text().toDouble();
		double ea = domElement.namedItem( "electronaffinity" ).toElement().text().toDouble();
		double mp = domElement.namedItem( "meltingpoint" ).toElement().text().toDouble();
		double bp = domElement.namedItem( "boilingpoint" ).toElement().text().toDouble();
		double density = domElement.namedItem( "density" ).toElement().text().toDouble();
		double covalent_radius = domElement.namedItem( "radius" ).namedItem( "covalent" ).toElement().text().toDouble();
		//van der Waals-Radius
		double vdw_radius = domElement.namedItem( "radius" ).namedItem( "vdw" ).toElement().text().toDouble();
		double atomic_radius = domElement.namedItem( "radius" ).namedItem( "atomic" ).toElement().text().toDouble();
		double ionic_radius = domElement.namedItem( "radius" ).namedItem( "ionic" ).toElement().text().toDouble();
		QString ionic_charge = domElement.namedItem( "radius" ).namedItem( "ionic" ).toElement().attributeNode( "charge" ).value();
		
		int bio = domElement.namedItem( "biologicalmeaning" ).toElement().text().toInt();
		int radioactive = domElement.namedItem( "radioactive" ).toElement().text().toInt();
		int period = domElement.namedItem( "period" ).toElement().text().toInt();
		int artificial = domElement.namedItem( "artificial" ).toElement().text().toInt();
		int date = domElement.namedItem( "date" ).toElement().text().toInt();
		int number = domElement.namedItem( "number" ).toElement().text().toInt();
		int abundance = domElement.namedItem( "abundance" ).toElement().text().toInt();
		
		QString scientist = domElement.namedItem( "date" ).toElement().attributeNode( "scientist" ).value();
		QString crystal = domElement.namedItem( "crystalstructure" ).toElement().text();
		
		QDomElement nameE = domElement.namedItem( "name" ).toElement();
		QString name = nameE.text();
		QString origin = i18n( nameE.attributeNode( "origin" ).value().utf8() );
		
		QString block = domElement.namedItem( "block" ).toElement().text();
		QString group = domElement.namedItem( "group" ).toElement().text();
		QString family = domElement.namedItem( "family" ).toElement().text();
		QString orbits = domElement.namedItem( "orbits" ).toElement().text();
		QString symbol = domElement.namedItem( "symbol" ).toElement().text();
		QString oxydation = domElement.namedItem( "oxydation" ).toElement().text();
		QString acidicbehaviour = domElement.namedItem( "acidicbehaviour" ).toElement().text();

		QDomNodeList elist = domElement.elementsByTagName( "energy" );
		QValueList<double> ionlist;
		for( uint i = 0; i < elist.length(); i++ )
		{
			ionlist.append(  elist.item(  i ).toElement().text().toDouble() );
		}
		
		//now read in all the date for the isotopes
		QDomNodeList isotopelist = domElement.elementsByTagName( "isotope" );
		QValueList<Isotope*> isolist;
		for( uint i = 0; i < isotopelist.length(); i++ )
		{
			QDomElement iso = isotopelist.item( i ).toElement();
			double halflife = iso.attributeNode( "halflife" ).value().toDouble();
			double weight = iso.attributeNode( "weight" ).value().toDouble();
			QString format = iso.attributeNode( "halflifeformat" ).value();
			int neutrons  = iso.attributeNode( "neutron" ).value().toInt();
			double percentage = iso.attributeNode( "percentage" ).value().toDouble();
			double alphapercentage = iso.attributeNode( "alphapercentage" ).value().toDouble();
			double betapluspercentage = iso.attributeNode( "betapluspercentage" ).value().toDouble();
			double betaminuspercentage = iso.attributeNode( "betaminuspercentage" ).value().toDouble();
			double ecpercentage = iso.attributeNode( "ecpercentage" ).value().toDouble();
			double alphadecay = iso.attributeNode( "alphadecay" ).value().toDouble();
			double betaplusdecay = iso.attributeNode( "betaplusdecay" ).value().toDouble();
			double betaminusdecay = iso.attributeNode( "betaminusdecay" ).value().toDouble();
			double ecdecay = iso.attributeNode( "ecdecay" ).value().toDouble();
			QString spin = iso.attributeNode( "spin" ).value();
			QString magmoment = iso.attributeNode( "magmoment" ).value();
			
						
			Isotope *isotope = new Isotope( neutrons, 
					number, 
					percentage, 
					weight, 
					halflife, 
					format, 
					alphadecay, 
					betaplusdecay, 
					betaminusdecay, 
					ecdecay, 
					alphapercentage, 
					betapluspercentage, 
					betaminuspercentage, 
					ecpercentage, 
					spin, 
					magmoment );
			isolist.append( isotope );
		}

		QDomNodeList spectrumList = domElement.namedItem( "spectra" ).toElement().elementsByTagName( "spectrum" );

		Element *e = new Element();
		e->setDate(date);
		e->setBiologicalMeaning(bio);
		e->setNumber( number );
		e->setName(i18n(name.utf8()));
		e->setRadius( Element::ATOMIC, atomic_radius );
		e->setRadius( Element::IONIC, ionic_radius, ionic_charge );
		e->setRadius( Element::COVALENT, covalent_radius );
		e->setRadius( Element::VDW, vdw_radius );
		e->setAbundance( abundance );

		if ( artificial == 1 )
			e->setArtificial();
		if ( radioactive == 1 )
			e->setRadioactive();
		
		e->setScientist(scientist);
		e->setPeriod( period );
		e->setCrysatalstructure( crystal );
		e->setOrigin(origin);
		e->setBlock(block);
		e->setGroup(group);
		e->setFamily(family);
		e->setOrbits(orbits);
		e->setSymbol(symbol);
		e->setOxydation(oxydation);
		e->setAcidicbehaviour(acidicbehaviour);
		e->setIonisationList( ionlist );
		e->setIsotopeList( isolist );
		
		e->setMass( mass );	
		e->setEN( en );
		e->setEA( ea );
		e->setMeltingpoint( mp );
		e->setBoilingpoint( bp );
		e->setDensity( density );

		e->setupXY();

		Spectrum *spectrum = new Spectrum();
		bool spectrum_temp = false;
		if ( spectrumList.length() > 0 )
			spectrum_temp = true;
		for( uint i = 0; i < spectrumList.length(); i++ )
		{
			Spectrum::band b;
			QDomElement spec = spectrumList.item( i ).toElement();
			
			b.intensity = spec.attributeNode( "intensity" ).value().toInt();
			b.wavelength = spec.attributeNode( "wavelength" ).value().toDouble()/10.0;
			b.aki = spec.attributeNode( "aki" ).value().toDouble();
			b.energy1 = spec.attributeNode( "energy1" ).value().toDouble();
			b.energy2 = spec.attributeNode( "energy2" ).value().toDouble();
			b.electronconfig1 = spec.attributeNode( "electronconfig1" ).value();
			b.electronconfig2 = spec.attributeNode( "electronconfig1" ).value();
			b.term1 = spec.attributeNode( "term1" ).value();
			b.term2 = spec.attributeNode( "term2" ).value();
			b.J1 = spec.attributeNode( "J1" ).value();
			b.J2 = spec.attributeNode( "J2" ).value();

			spectrum->addBand( b );
		}
		if ( spectrum_temp ) //if no spectrumdata are found don't use this object
			e->setSpectrum( spectrum );
		e->setHasSepctrum( spectrum_temp );

		list.append( e );
		coordinate point; point.x =  e->x; point.y = e->y;
		CoordinateList.append( point );
	}

	return list;
}