Esempio n. 1
0
bool QgsSymbol::writeXML( QDomNode & item, QDomDocument & document, const QgsVectorLayer *vl ) const
{
  bool returnval = false;
  returnval = true; // no error checking yet
  QDomElement symbol = document.createElement( "symbol" );
  item.appendChild( symbol );

  appendText( symbol, document, "lowervalue", mLowerValue );
  appendText( symbol, document, "uppervalue", mUpperValue );
  appendText( symbol, document, "label", mLabel );

  QString name = pointSymbolName();
  if ( name.startsWith( "svg:" ) )
  {
    name = name.mid( 4 );

    QFileInfo fi( name );
    if ( fi.exists() )
    {
      name = fi.canonicalFilePath();

      QStringList svgPaths = QgsApplication::svgPaths();

      for ( int i = 0; i < svgPaths.size(); i++ )
      {
        QString dir = QFileInfo( svgPaths[i] ).canonicalFilePath();

        if ( !dir.isEmpty() && name.startsWith( dir ) )
        {
          name = name.mid( dir.size() );
          break;
        }
      }
    }

    name = "svg:" + name;
  }

  appendText( symbol, document, "pointsymbol", name );
  appendText( symbol, document, "pointsize", QString::number( pointSize() ) );
  appendText( symbol, document, "pointsizeunits", pointSizeUnits() ? "mapunits" : "pixels" );

  if ( vl )
  {
    appendField( symbol, document, *vl, "rotationclassificationfieldname", mRotationClassificationField );
    appendField( symbol, document, *vl, "scaleclassificationfieldname", mScaleClassificationField );
    appendField( symbol, document, *vl, "symbolfieldname", mSymbolField );
  }

  QDomElement outlinecolor = document.createElement( "outlinecolor" );
  outlinecolor.setAttribute( "red", QString::number( mPen.color().red() ) );
  outlinecolor.setAttribute( "green", QString::number( mPen.color().green() ) );
  outlinecolor.setAttribute( "blue", QString::number( mPen.color().blue() ) );
  symbol.appendChild( outlinecolor );

  appendText( symbol, document, "outlinestyle", QgsSymbologyUtils::penStyle2QString( mPen.style() ) );
  appendText( symbol, document, "outlinewidth", QString::number( mPen.widthF() ) );

  QDomElement fillcolor = document.createElement( "fillcolor" );
  fillcolor.setAttribute( "red", QString::number( mBrush.color().red() ) );
  fillcolor.setAttribute( "green", QString::number( mBrush.color().green() ) );
  fillcolor.setAttribute( "blue", QString::number( mBrush.color().blue() ) );
  symbol.appendChild( fillcolor );

  appendText( symbol, document, "fillpattern", QgsSymbologyUtils::brushStyle2QString( mBrush.style() ) );
  appendText( symbol, document, "texturepath", QgsProject::instance()->writePath( mTextureFilePath ) );

  return returnval;
}
Esempio n. 2
0
void ORGraphicsSectionDetail::buildXML(QDomDocument & doc, QDomElement & section)
{
  // name/title
  QDomElement name = doc.createElement("name");
  name.appendChild(doc.createTextNode(getTitle()));
  section.appendChild(name);

  if(pageBreak() != ORGraphicsSectionDetail::BreakNone)
  {
    QDomElement spagebreak = doc.createElement("pagebreak");
    if(pageBreak() == ORGraphicsSectionDetail::BreakAtEnd)
      spagebreak.setAttribute("when", "at end");
    section.appendChild(spagebreak);
  }

  for(int i = 0; i < groupList.count(); i++)
  {
    ORGraphicsSectionDetailGroup * rsdg = groupList.at(i);
    QDomNode grp = doc.createElement("group");

    QDomNode gname = doc.createElement("name");
    gname.appendChild(doc.createTextNode(rsdg->getTitle()));
    grp.appendChild(gname);

    QDomNode gcol = doc.createElement("column");
    gcol.appendChild(doc.createTextNode(rsdg->column()));
    grp.appendChild(gcol);

    if(rsdg->pageBreak() != ORGraphicsSectionDetailGroup::BreakNone)
    {
      QDomElement pagebreak = doc.createElement("pagebreak");
      if(rsdg->pageBreak() == ORGraphicsSectionDetailGroup::BreakAfterGroupFooter)
        pagebreak.setAttribute("when", "after foot");
      grp.appendChild(pagebreak);
    }

    //group head
    if(rsdg->isGroupHeadShowing())
    {
      QDomElement ghead = doc.createElement("head");
      rsdg->getGroupHead()->buildXML(doc,ghead);
      grp.appendChild(ghead);
    }
    // group foot
    if(rsdg->isGroupFootShowing())
    {
      QDomElement gfoot = doc.createElement("foot");
      rsdg->getGroupFoot()->buildXML(doc,gfoot);
      grp.appendChild(gfoot);
    }

    section.appendChild(grp);
  }

  // detail section
  QDomElement gdetail = doc.createElement("detail");
  QDomElement key = doc.createElement("key");
  QDomElement kquery = doc.createElement("query");
  kquery.appendChild(doc.createTextNode(query()));
  key.appendChild(kquery);
  gdetail.appendChild(key);
  _detail->buildXML(doc,gdetail);
  section.appendChild(gdetail);
}
Esempio n. 3
0
void QLCPhysical_Test::loadWrongRoot()
{
	QDomDocument doc;

	QDomElement root = doc.createElement("Foosical");
	doc.appendChild(root);

	/* Bulb */
	QDomElement bulb = doc.createElement("Bulb");
	bulb.setAttribute("Type", "LED");
	bulb.setAttribute("Lumens", 18000);
	bulb.setAttribute("ColourTemperature", 6500);
	root.appendChild(bulb);

	/* Dimensions */
	QDomElement dim = doc.createElement("Dimensions");
	dim.setAttribute("Weight", 39);
	dim.setAttribute("Width", 530);
	dim.setAttribute("Height", 320);
	dim.setAttribute("Depth", 260);
	root.appendChild(dim);

	/* Lens */
	QDomElement lens = doc.createElement("Lens");
	lens.setAttribute("Name", "Fresnel");
	lens.setAttribute("DegreesMin", 8);
	lens.setAttribute("DegreesMax", 38);
	root.appendChild(lens);

	/* Focus */
	QDomElement focus = doc.createElement("Focus");
	focus.setAttribute("Type", "Head");
	focus.setAttribute("PanMax", 520);
	focus.setAttribute("TiltMax", 270);
	root.appendChild(focus);

	/* Technical */
	QDomElement technical=  doc.createElement("Technical");
	technical.setAttribute("PowerConsumption", 250);
	technical.setAttribute("DmxConnector", "5-pin");
	root.appendChild(technical);

	QVERIFY(p.loadXML(&root) == false);
}
QByteArray WeeklyTimesheetXmlWriter::saveToXml() const
{
    // now create the report:
    QDomDocument document = XmlSerialization::createXmlTemplate( "weekly-timesheet" );

    // find metadata and report element:
    QDomElement root = document.documentElement();
    QDomElement metadata = XmlSerialization::metadataElement( document );
    QDomElement charmVersion = document.createElement( "charmversion" );
    QDomText charmVersionString = document.createTextNode( CHARM_VERSION );
    charmVersion.appendChild( charmVersionString );
    metadata.appendChild( charmVersion );
    QDomElement report = XmlSerialization::reportElement( document );
    Q_ASSERT( !root.isNull() && !metadata.isNull() && !report.isNull() );

    // extend metadata tag: add year, and serial (week) number:
    {
        QDomElement yearElement = document.createElement( "year" );
        metadata.appendChild( yearElement );
        QDomText text = document.createTextNode( QString::number( m_year ) );
        yearElement.appendChild( text );
        QDomElement weekElement = document.createElement( "serial-number" );
        weekElement.setAttribute( "semantics", "week-number" );
        metadata.appendChild( weekElement );
        QDomText weektext = document.createTextNode( QString::number( m_weekNumber ) );
        weekElement.appendChild( weektext );
    }


    typedef QMap< TaskId, QVector<int> > SecondsMap;
    SecondsMap secondsMap;
    TimeSheetInfoList timeSheetInfo = TimeSheetInfo::filteredTaskWithSubTasks(
        TimeSheetInfo::taskWithSubTasks( m_dataModel, DaysInWeek, m_rootTask, secondsMap ),
        false ); // here, we don't care about active or not, because we only report on the tasks

    // extend report tag: add tasks and effort structure
    {   // tasks
        QDomElement tasks = document.createElement( "tasks" );
        report.appendChild( tasks );
        Q_FOREACH ( const TimeSheetInfo& info, timeSheetInfo ) {
            if ( info.taskId == 0 ) // the root task
                continue;
            const Task& modelTask = m_dataModel->getTask( info.taskId );
            tasks.appendChild( modelTask.toXml( document ) );
//             TaskId parentTask = DATAMODEL->parentItem( modelTask ).task().id();
//             QDomElement task = document.createElement( "task" );
//             task.setAttribute( "taskid", QString::number( info.taskId ) );
//             if ( parentTask != 0 )
//                 task.setAttribute( "parent", QString::number( parentTask ) );

//             QDomText name = document.createTextNode( modelTask.name() );
//             task.appendChild( name );
//             tasks.appendChild( task );
        }
    }
    {   // effort
        // make effort element:
        QDomElement effort = document.createElement( "effort" );
        report.appendChild( effort );

        // aggregate (group by task and day):
        typedef QPair<TaskId, QDate> Key;
        QMap< Key, Event> events;
        Q_FOREACH ( const Event& event, m_events ) {
            TimeSheetInfoList::iterator it;
            for ( it = timeSheetInfo.begin(); it != timeSheetInfo.end(); ++it )
                if ( ( *it ).taskId == event.taskId() ) break;
            if ( it == timeSheetInfo.end() )
                continue;
            Key key( event.taskId(), event.startDateTime().date() );
            if ( events.contains( key ) ) {
                // add to previous events:
                const Event& oldEvent = events[key];
                const int seconds = oldEvent.duration() + event.duration();
                const QDateTime start = oldEvent.startDateTime();
                const QDateTime end( start.addSecs( seconds ) );
                Q_ASSERT( start.secsTo( end ) == seconds );
                Event newEvent( oldEvent );
                newEvent.setStartDateTime( start );
                newEvent.setEndDateTime( end );
                Q_ASSERT( newEvent.duration() == seconds );
                QString comment = oldEvent.comment();
                if ( ! event.comment().isEmpty() ) {
                    if ( !comment.isEmpty() ) { // make separator
                        comment += " / ";
                    }
                    comment += event.comment();
                    newEvent.setComment( comment );
                }
                events[key] = newEvent;
            } else {
                // add this event:
                events[key] = event;
                events[key].setId( -events[key].id() ); // "synthetic" :-)
                // move to start at midnight in UTC (for privacy reasons)
                // never, never, never use setTime() here, it breaks on DST changes! (twice a year)
                QDateTime start( event.startDateTime().date(), QTime(0, 0, 0, 0), Qt::UTC );
                QDateTime end( start.addSecs( event.duration() ) );
                events[key].setStartDateTime( start );
                events[key].setEndDateTime( end );
                Q_ASSERT( events[key].duration() == event.duration() );
                Q_ASSERT( start.time() == QTime(0, 0, 0, 0) );
            }
        }
        // create elements:
        Q_FOREACH ( const Event & event, events ) {
            effort.appendChild( event.toXml( document ) );
        }
Esempio n. 5
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 );
  }
}
void XdgMenuLayoutProcessor::run()
{
    QDomDocument doc = mLayout.ownerDocument();
    mResult = doc.createElement(QLatin1String("Result"));
    mElement.appendChild(mResult);

    // Process childs menus ...............................
    {
        DomElementIterator it(mElement, QLatin1String("Menu"));
        while (it.hasNext())
        {
            QDomElement e = it.next();
            XdgMenuLayoutProcessor p(e, this);
            p.run();
        }
    }


    // Step 1 ...................................
    DomElementIterator it(mLayout);
    it.toFront();
    while (it.hasNext())
    {
        QDomElement e = it.next();

        if (e.tagName() == QLatin1String("Filename"))
            processFilenameTag(e);

        else if (e.tagName() == QLatin1String("Menuname"))
            processMenunameTag(e);

        else if (e.tagName() == QLatin1String("Separator"))
            processSeparatorTag(e);

        else if (e.tagName() == QLatin1String("Merge"))
        {
            QDomElement merge = mResult.ownerDocument().createElement(QLatin1String("Merge"));
            merge.setAttribute(QLatin1String("type"), e.attribute(QLatin1String("type")));
            mResult.appendChild(merge);
        }
    }

    // Step 2 ...................................
    {
        MutableDomElementIterator ri(mResult, QLatin1String("Merge"));
        while (ri.hasNext())
        {
            processMergeTag(ri.next());
        }
    }

    // Move result cilds to element .............
    MutableDomElementIterator ri(mResult);
    while (ri.hasNext())
    {
        mElement.appendChild(ri.next());
    }

    // Final ....................................
    mElement.removeChild(mResult);

    if (mLayout.parentNode() == mElement)
        mElement.removeChild(mLayout);

    if (mDefaultLayout.parentNode() == mElement)
        mElement.removeChild(mDefaultLayout);

}
Esempio n. 7
0
cmenu::cmenu(QString filename,bool *success)
{
	menusDoc=new QDomDocument("swim_menu");
	QFile f( filename );
	if ( !f.open( IO_ReadOnly ) ) 
	{
		*success=false;
		cout<<filename<<" not found"<<endl;
		return;
	}
	QString errorMsg;
	int errorLine, errorColumn;
	if ( !menusDoc->setContent( &f, false, &errorMsg,&errorLine,&errorColumn ) ) 
	{
		f.close();
		cout<<"Error while parsing menu :"<<endl<<errorMsg<<", Line: "<<errorLine<<" ,Column: "<<errorColumn<<endl;
		*success=false;
		return;
	}
	f.close();
	*success=true;
	//root element
	QDomElement docElem = menusDoc->documentElement();
	
	// assigning global configuration
	QDomNode globalNode = docElem.firstChild();
	if((!globalNode.isNull())&&(globalNode.nodeName().compare("global_config")==0))
	{
		QDomElement globalElement=globalNode.toElement();
		
		defaultImage=globalElement.attribute("defaultimage");
		defaultDir=globalElement.attribute("defaultdir","ltr");
		docsPath=globalElement.attribute("docspath","");
		imagePath=globalElement.attribute("imagepath","");
		firstPage=globalElement.attribute("firstpage");
		if (docsPath[docsPath.length()-1]!='/') docsPath.append('/');
		if (imagePath[imagePath.length()-1]!='/') imagePath.append('/');
	}
	
	// expanding the tree (add the plays to the menus level, because of the images problem)
	QDomNode menuNode = docElem.firstChild();
	while( !menuNode.isNull() ) 
	{
		if((menuNode.nodeName().compare("menu")==0)&&(menuNode.isElement()))
		{
			// if no firstpage defined, take the first menu you see.
			if (firstPage.isNull()) firstPage=menuNode.toElement().attribute("name");
			
			QDomNode linkNode=menuNode.firstChild();
			QDomElement linkElem;
			while(!linkNode.isNull())
			{
				linkElem=linkNode.toElement();
				if ((!linkElem.isNull()) && (linkElem.tagName().compare("link")==0) && (linkElem.attribute("type","menu").compare("play")==0))
				{
					QDomElement append = menusDoc->createElement("play");
					append.setAttribute("name",linkElem.attribute("name"));
					if (!linkElem.attribute("image").isNull()) append.setAttribute("image", linkElem.attribute("image"));
					// add this to the menus level.
					docElem.appendChild( append );
				}
				linkNode = linkNode.nextSibling();	
			}
		}
		menuNode = menuNode.nextSibling();
	}
}
Esempio n. 8
0
KWDWriter::KWDWriter(KOdfStore *store)
{
    _store = store;
    _doc = new QDomDocument("DOC");
    _docinfo = new QDomDocument("document-info");

    _doc->appendChild(_doc->createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""));
    _docinfo->appendChild(_docinfo->createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""));

    QDomElement infodoc = _docinfo->createElement("document-info");
    _docinfoMain = infodoc;
    _docinfo->appendChild(infodoc);

    tableNo = 1;
    insidetable = false;
    QDomElement kwdoc = _doc->createElement("DOC");
    kwdoc.setAttribute("editor", "HTML Import Filter");
    kwdoc.setAttribute("mime", "application/x-kword");
    _doc->appendChild(kwdoc);

    QDomElement paper = _doc->createElement("PAPER");
    kwdoc.appendChild(paper);
    paper.setAttribute("format", 1);
    paper.setAttribute("width", 595);
    paper.setAttribute("height", 841);
    paper.setAttribute("orientation", 0);
    paper.setAttribute("columns", 1);
    paper.setAttribute("columnspacing", 3);
    paper.setAttribute("hType", 0);
    paper.setAttribute("fType", 0);

    QDomElement borders = _doc->createElement("PAPERBORDERS");
    paper.appendChild(borders);
    borders.setAttribute("left", 20);
    borders.setAttribute("top", 10);
    borders.setAttribute("right", 10);
    borders.setAttribute("bottom", 10);

    QDomElement docattrs = _doc->createElement("ATTRIBUTES");
    kwdoc.appendChild(docattrs);
    docattrs.setAttribute("processing", 0);
    docattrs.setAttribute("standardpage", 1);
    docattrs.setAttribute("hasHeader", 0);
    docattrs.setAttribute("hasFooter", 0);
    //docattrs.setAttribute( "unit", "mm" ); // use KWord default instead

    QDomElement framesets = _doc->createElement("FRAMESETS");
    kwdoc.appendChild(framesets);
    QDomElement rootframeset = addFrameSet(framesets);
    _mainFrameset = rootframeset;
    QDomElement mainframe = addFrame(rootframeset, QRect(28, 28, 539, 757));

    QDomElement styles = _doc->createElement("STYLES");
    kwdoc.appendChild(styles);

    QDomElement standard = _doc->createElement("STYLE");
    styles.appendChild(standard);

    QDomElement  tmp;
    tmp = _doc->createElement("NAME");
    tmp.setAttribute("value", "Standard");
    standard.appendChild(tmp);

    tmp = _doc->createElement("FOLLOWING");
    tmp.setAttribute("name", "Standard");
    standard.appendChild(tmp);
    QDomElement fmt;

    fmt = _doc->createElement("FORMAT");
    fmt.setAttribute("id", "1");
    standard.appendChild(fmt);

    tmp = _doc->createElement("SIZE");
    tmp.setAttribute("value", "12"); // HACK !
    fmt.appendChild(tmp);


#define HEADINGSTYLE(a,b)     standard=_doc->createElement("STYLE");\
    styles.appendChild(standard);\
    tmp=_doc->createElement("NAME");\
    tmp.setAttribute("value",#a);\
    standard.appendChild(tmp);\
    tmp=_doc->createElement("FOLLOWING");\
    tmp.setAttribute("name","Standard");\
    standard.appendChild(tmp);\
    fmt=_doc->createElement("FORMAT");\
    fmt.setAttribute("id","1");\
    standard.appendChild(fmt);\
    tmp=_doc->createElement("SIZE");\
    tmp.setAttribute("value",#b);\
    fmt.appendChild(tmp);

    HEADINGSTYLE(h1, 20);
    HEADINGSTYLE(h2, 18);
    HEADINGSTYLE(h3, 16);
    HEADINGSTYLE(h4, 14);
    HEADINGSTYLE(h5, 10);
    HEADINGSTYLE(h6, 8);


}
//-----------------------
//读取文件创建元素
QDomElement FilterParameter::createElement(QDomDocument &doc)
{
	QDomElement parElem = doc.createElement("Param");
	parElem.setAttribute("name",this->fieldName);
	switch (this->fieldType)
	{
		case FilterParameter::PARBOOL:
        parElem.setAttribute("type","Bool");
        parElem.setAttribute("value",this->fieldVal.toString());
		break;
    case FilterParameter::PARSTRING:
        parElem.setAttribute("type","String");
        parElem.setAttribute("value",this->fieldVal.toString());
    break;
    case FilterParameter::PARINT:
        parElem.setAttribute("type","Int");
        parElem.setAttribute("value",this->fieldVal.toInt());
    break;
    case FilterParameter::PARFLOAT:
        parElem.setAttribute("type","Float");
        parElem.setAttribute("value",this->fieldVal.toString());
    break;
    case FilterParameter::PARABSPERC:
        parElem.setAttribute("type","AbsPerc");
        parElem.setAttribute("value",this->fieldVal.toString());
        parElem.setAttribute("min",QString::number(this->min));
        parElem.setAttribute("max",QString::number(this->max));
    break;
    case FilterParameter::PARCOLOR:
        parElem.setAttribute("type","Color");
        parElem.setAttribute("rgb",this->fieldVal.toString());
    break;
    case FilterParameter::PARENUM:
		{
        parElem.setAttribute("type","Enum");
        parElem.setAttribute("value",this->fieldVal.toString());
        QStringList::iterator kk;
        for(kk = this->enumValues.begin();kk!=this->enumValues.end();++kk){
        	QDomElement sElem = doc.createElement("EnumString");
        	sElem.setAttribute("value",(*kk));
        	parElem.appendChild(sElem);
        }
		}
    break;
    case FilterParameter::PARMATRIX:
        {
				parElem.setAttribute("type","Matrix44");
        QList<QVariant> matrixVals = this->fieldVal.toList();
        for(int i=0;i<16;++i)
          parElem.setAttribute(QString("val")+QString::number(i),matrixVals[i].toString());
					}
    break;
    case FilterParameter::PARMESH:
    	  parElem.setAttribute(TypeName(), MeshPointerName());
    	  //this is the mesh's position in the mesh document that was used
    	  parElem.setAttribute(ValueName(),(this->fieldVal.toString()));
    break;
    case FilterParameter::PARFLOATLIST:
		{
    	parElem.setAttribute(TypeName(), FloatListName());
    	QList<QVariant> values = this->fieldVal.toList();
			for(int i=0; i < values.size(); ++i)
				{
					QDomElement listElement = doc.createElement(ItemName());
					listElement.setAttribute(ValueName(), values[i].toString());
					parElem.appendChild(listElement);
        }
		}
    break;
    case FilterParameter::PARDYNFLOAT:
    	  parElem.setAttribute(TypeName(), DynamicFloatName());
    	  parElem.setAttribute(ValueName(), this->fieldVal.toString());
    	  parElem.setAttribute(MinName(), QString::number(this->min));
    	  parElem.setAttribute(MaxName(), QString::number(this->max));
    	  parElem.setAttribute(MaskName(),QString::number(this->mask));
    break;
    case FilterParameter::PAROPENFILENAME:
    	  parElem.setAttribute(TypeName(), OpenFileNameName());
    	  parElem.setAttribute(ValueName(), this->fieldVal.toString());
    break;
    case FilterParameter::PARSAVEFILENAME:
        parElem.setAttribute(TypeName(), SaveFileNameName());
        parElem.setAttribute(ValueName(), this->fieldVal.toString());
		break;
		    case FilterParameter::PARPOINT3F:
				{
        QList<QVariant> pointVals = this->fieldVal.toList();
				parElem.setAttribute("type","Point3f");
        parElem.setAttribute("x",QString::number(pointVals[0].toDouble()));
        parElem.setAttribute("y",QString::number(pointVals[1].toDouble()));
        parElem.setAttribute("z",QString::number(pointVals[2].toDouble()));
				}
				break;
    default: assert(0);
    }
	return parElem;
	}
Esempio n. 10
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 );
      }
Esempio n. 11
0
bool QgsLayoutTable::writePropertiesToElement( QDomElement &elem, QDomDocument &doc, const QgsReadWriteContext & ) const
{
  elem.setAttribute( QStringLiteral( "cellMargin" ), QString::number( mCellMargin ) );
  elem.setAttribute( QStringLiteral( "emptyTableMode" ), QString::number( static_cast< int >( mEmptyTableMode ) ) );
  elem.setAttribute( QStringLiteral( "emptyTableMessage" ), mEmptyTableMessage );
  elem.setAttribute( QStringLiteral( "showEmptyRows" ), mShowEmptyRows );
  elem.appendChild( QgsFontUtils::toXmlElement( mHeaderFont, doc, QStringLiteral( "headerFontProperties" ) ) );
  elem.setAttribute( QStringLiteral( "headerFontColor" ), QgsSymbolLayerUtils::encodeColor( mHeaderFontColor ) );
  elem.setAttribute( QStringLiteral( "headerHAlignment" ), QString::number( static_cast< int >( mHeaderHAlignment ) ) );
  elem.setAttribute( QStringLiteral( "headerMode" ), QString::number( static_cast< int >( mHeaderMode ) ) );
  elem.appendChild( QgsFontUtils::toXmlElement( mContentFont, doc, QStringLiteral( "contentFontProperties" ) ) );
  elem.setAttribute( QStringLiteral( "contentFontColor" ), QgsSymbolLayerUtils::encodeColor( mContentFontColor ) );
  elem.setAttribute( QStringLiteral( "gridStrokeWidth" ), QString::number( mGridStrokeWidth ) );
  elem.setAttribute( QStringLiteral( "gridColor" ), QgsSymbolLayerUtils::encodeColor( mGridColor ) );
  elem.setAttribute( QStringLiteral( "horizontalGrid" ), mHorizontalGrid );
  elem.setAttribute( QStringLiteral( "verticalGrid" ), mVerticalGrid );
  elem.setAttribute( QStringLiteral( "showGrid" ), mShowGrid );
  elem.setAttribute( QStringLiteral( "backgroundColor" ), QgsSymbolLayerUtils::encodeColor( mBackgroundColor ) );
  elem.setAttribute( QStringLiteral( "wrapBehavior" ), QString::number( static_cast< int >( mWrapBehavior ) ) );

  //columns
  QDomElement displayColumnsElem = doc.createElement( QStringLiteral( "displayColumns" ) );
  for ( QgsLayoutTableColumn *column : qgis::as_const( mColumns ) )
  {
    QDomElement columnElem = doc.createElement( QStringLiteral( "column" ) );
    column->writeXml( columnElem, doc );
    displayColumnsElem.appendChild( columnElem );
  }
  elem.appendChild( displayColumnsElem );

  //cell styles
  QDomElement stylesElem = doc.createElement( QStringLiteral( "cellStyles" ) );
  QMap< CellStyleGroup, QString >::const_iterator it = mCellStyleNames.constBegin();
  for ( ; it != mCellStyleNames.constEnd(); ++it )
  {
    QString styleName = it.value();
    QDomElement styleElem = doc.createElement( styleName );
    QgsLayoutTableStyle *style = mCellStyles.value( it.key() );
    if ( style )
    {
      style->writeXml( styleElem, doc );
      stylesElem.appendChild( styleElem );
    }
  }
  elem.appendChild( stylesElem );
  return true;
}
Esempio n. 12
0
bool QgsMapLayer::writeLayerXML( QDomElement& layerElement, QDomDocument& document, QString relativeBasePath )
{
  // use scale dependent visibility flag
  layerElement.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 );
  layerElement.setAttribute( "minimumScale", QString::number( minimumScale() ) );
  layerElement.setAttribute( "maximumScale", QString::number( maximumScale() ) );

  // ID
  QDomElement layerId = document.createElement( "id" );
  QDomText layerIdText = document.createTextNode( id() );
  layerId.appendChild( layerIdText );

  layerElement.appendChild( layerId );

  // data source
  QDomElement dataSource = document.createElement( "datasource" );

  QString src = source();

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  // TODO: what about postgres, mysql and others, they should not go through writePath()
  if ( vlayer && vlayer->providerType() == "spatialite" )
  {
    QgsDataSourceURI uri( src );
    QString database = QgsProject::instance()->writePath( uri.database(), relativeBasePath );
    uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() );
    src = uri.uri();
  }
  else if ( vlayer && vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = src.split( "|" );
    theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0], relativeBasePath );
    src = theURIParts.join( "|" );
  }
  else if ( vlayer && vlayer->providerType() == "gpx" )
  {
    QStringList theURIParts = src.split( "?" );
    theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0], relativeBasePath );
    src = theURIParts.join( "?" );
  }
  else if ( vlayer && vlayer->providerType() == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( src.toAscii() );
    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile(), relativeBasePath ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    src = QString::fromAscii( urlDest.toEncoded() );
  }
  else
  {
    bool handled = false;

    if ( !vlayer )
    {
      QgsRasterLayer *rlayer = qobject_cast<QgsRasterLayer *>( this );
      // Update path for subdataset
      if ( rlayer && rlayer->providerType() == "gdal" )
      {
        if ( src.startsWith( "NETCDF:" ) )
        {
          // NETCDF:filename:variable
          // filename can be quoted with " as it can contain colons
          QRegExp r( "NETCDF:(.+):([^:]+)" );
          if ( r.exactMatch( src ) )
          {
            QString filename = r.cap( 1 );
            if ( filename.startsWith( '"' ) && filename.endsWith( '"' ) )
              filename = filename.mid( 1, filename.length() - 2 );
            src = "NETCDF:\"" + QgsProject::instance()->writePath( filename, relativeBasePath ) + "\":" + r.cap( 2 );
            handled = true;
          }
        }
        else if ( src.startsWith( "HDF4_SDS:" ) )
        {
          // HDF4_SDS:subdataset_type:file_name:subdataset_index
          // filename can be quoted with " as it can contain colons
          QRegExp r( "HDF4_SDS:([^:]+):(.+):([^:]+)" );
          if ( r.exactMatch( src ) )
          {
            QString filename = r.cap( 2 );
            if ( filename.startsWith( '"' ) && filename.endsWith( '"' ) )
              filename = filename.mid( 1, filename.length() - 2 );
            src = "HDF4_SDS:" + r.cap( 1 ) + ":\"" + QgsProject::instance()->writePath( filename, relativeBasePath ) + "\":" + r.cap( 3 );
            handled = true;
          }
        }
        else if ( src.startsWith( "HDF5:" ) )
        {
          // HDF5:file_name:subdataset
          // filename can be quoted with " as it can contain colons
          QRegExp r( "HDF5:(.+):([^:]+)" );
          if ( r.exactMatch( src ) )
          {
            QString filename = r.cap( 1 );
            if ( filename.startsWith( '"' ) && filename.endsWith( '"' ) )
              filename = filename.mid( 1, filename.length() - 2 );
            src = "HDF5:\"" + QgsProject::instance()->writePath( filename, relativeBasePath ) + "\":" + r.cap( 2 );
            handled = true;
          }
        }
        else if ( src.contains( QRegExp( "^(NITF_IM|RADARSAT_2_CALIB):" ) ) )
        {
          // NITF_IM:0:filename
          // RADARSAT_2_CALIB:?:filename
          QRegExp r( "([^:]+):([^:]+):(.+)" );
          if ( r.exactMatch( src ) )
          {
            src = r.cap( 1 ) + ":" + r.cap( 2 ) + ":" + QgsProject::instance()->writePath( r.cap( 3 ), relativeBasePath );
            handled = true;
          }
        }
      }
    }

    if ( !handled )
      src = QgsProject::instance()->writePath( src, relativeBasePath );
  }

  QDomText dataSourceText = document.createTextNode( src );
  dataSource.appendChild( dataSourceText );

  layerElement.appendChild( dataSource );


  // layer name
  QDomElement layerName = document.createElement( "layername" );
  QDomText layerNameText = document.createTextNode( originalName() );
  layerName.appendChild( layerNameText );

  // layer title
  QDomElement layerTitle = document.createElement( "title" );
  QDomText layerTitleText = document.createTextNode( title() );
  layerTitle.appendChild( layerTitleText );

  // layer abstract
  QDomElement layerAbstract = document.createElement( "abstract" );
  QDomText layerAbstractText = document.createTextNode( abstract() );
  layerAbstract.appendChild( layerAbstractText );

  layerElement.appendChild( layerName );
  layerElement.appendChild( layerTitle );
  layerElement.appendChild( layerAbstract );

  // layer keyword list
  QStringList keywordStringList = keywordList().split( "," );
  if ( keywordStringList.size() > 0 )
  {
    QDomElement layerKeywordList = document.createElement( "keywordList" );
    for ( int i = 0; i < keywordStringList.size(); ++i )
    {
      QDomElement layerKeywordValue = document.createElement( "value" );
      QDomText layerKeywordText = document.createTextNode( keywordStringList.at( i ).trimmed() );
      layerKeywordValue.appendChild( layerKeywordText );
      layerKeywordList.appendChild( layerKeywordValue );
    }
    layerElement.appendChild( layerKeywordList );
  }

  // layer metadataUrl
  QString aDataUrl = dataUrl();
  if ( !aDataUrl.isEmpty() )
  {
    QDomElement layerDataUrl = document.createElement( "dataUrl" );
    QDomText layerDataUrlText = document.createTextNode( aDataUrl );
    layerDataUrl.appendChild( layerDataUrlText );
    layerDataUrl.setAttribute( "format", dataUrlFormat() );
    layerElement.appendChild( layerDataUrl );
  }

  // layer legendUrl
  QString aLegendUrl = legendUrl();
  if ( !aLegendUrl.isEmpty() )
  {
    QDomElement layerLegendUrl = document.createElement( "legendUrl" );
    QDomText layerLegendUrlText = document.createTextNode( aLegendUrl );
    layerLegendUrl.appendChild( layerLegendUrlText );
    layerLegendUrl.setAttribute( "format", legendUrlFormat() );
    layerElement.appendChild( layerLegendUrl );
  }

  // layer attribution
  QString aAttribution = attribution();
  if ( !aAttribution.isEmpty() )
  {
    QDomElement layerAttribution = document.createElement( "attribution" );
    QDomText layerAttributionText = document.createTextNode( aAttribution );
    layerAttribution.appendChild( layerAttributionText );
    layerAttribution.setAttribute( "href", attributionUrl() );
    layerElement.appendChild( layerAttribution );
  }

  // layer metadataUrl
  QString aMetadataUrl = metadataUrl();
  if ( !aMetadataUrl.isEmpty() )
  {
    QDomElement layerMetadataUrl = document.createElement( "metadataUrl" );
    QDomText layerMetadataUrlText = document.createTextNode( aMetadataUrl );
    layerMetadataUrl.appendChild( layerMetadataUrlText );
    layerMetadataUrl.setAttribute( "type", metadataUrlType() );
    layerMetadataUrl.setAttribute( "format", metadataUrlFormat() );
    layerElement.appendChild( layerMetadataUrl );
  }

  // timestamp if supported
  if ( timestamp() > QDateTime() )
  {
    QDomElement stamp = document.createElement( "timestamp" );
    QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) );
    stamp.appendChild( stampText );
    layerElement.appendChild( stamp );
  }

  layerElement.appendChild( layerName );

  // zorder
  // This is no longer stored in the project file. It is superfluous since the layers
  // are written and read in the proper order.

  // spatial reference system id
  QDomElement mySrsElement = document.createElement( "srs" );
  mCRS->writeXML( mySrsElement, document );
  layerElement.appendChild( mySrsElement );

#if 0
  // <transparencyLevelInt>
  QDomElement transparencyLevelIntElement = document.createElement( "transparencyLevelInt" );
  QDomText    transparencyLevelIntText    = document.createTextNode( QString::number( getTransparency() ) );
  transparencyLevelIntElement.appendChild( transparencyLevelIntText );
  maplayer.appendChild( transparencyLevelIntElement );
#endif

  // now append layer node to map layer node

  writeCustomProperties( layerElement, document );

  return writeXml( layerElement, document );

} // bool QgsMapLayer::writeXML
bool ProcessController::saveSettings(QDomDocument& doc, QDomElement& element)
{
    if(!mProcessList)
        return false;
    element.setAttribute("hostName", sensors().at(0)->hostName());
    element.setAttribute("sensorName", sensors().at(0)->name());
    element.setAttribute("sensorType", sensors().at(0)->type());

    element.setAttribute("version", QString::number(PROCESSHEADERVERSION));
    element.setAttribute("treeViewHeader", QString::fromLatin1(mProcessList->treeView()->header()->saveState().toBase64()));
    element.setAttribute("showTotals", mProcessList->showTotals()?1:0);

    element.setAttribute("units", (int)(mProcessList->units()));
    element.setAttribute("ioUnits", (int)(mProcessList->processModel()->ioUnits()));
    element.setAttribute("ioInformation", (int)(mProcessList->processModel()->ioInformation()));
    element.setAttribute("showCommandLineOptions", mProcessList->processModel()->isShowCommandLineOptions());
    element.setAttribute("showTooltips", mProcessList->processModel()->isShowingTooltips());
    element.setAttribute("normalizeCPUUsage", mProcessList->processModel()->isNormalizedCPUUsage());
    element.setAttribute("filterState", (int)(mProcessList->state()));

    SensorDisplay::saveSettings(doc, element);

    return true;
}
Esempio n. 14
0
QString HtmlUtil::docToNavdoc(const QString &data, QString &header, QString &nav)
{
    QDomDocument doc;
    QStringList srcLines = data.split("\n");
    QStringList navLines;
    QStringList dstLines;
    navLines.append("<table class=\"unruled\"><tbody><tr><td class=\"first\"><dl>");
    int index = 0;
    if (srcLines.length() >= 1) {
        header = findTitle(data);
        if (header.isEmpty()) {
            //<!-- How to Write Go Code -->
            QString line = srcLines.at(0);
            QRegExp reg("<!--([\\w\\s]*)-->");
            if (reg.indexIn(line) >= 0) {
                header = reg.cap(1);
                header.trimmed();
            }
        }
    }
    foreach(QString source, srcLines) {
        QString line = source.trimmed();
        index++;
        if (line.length() >= 10) {
            if (line.left(3) == "<h2") {
                if (doc.setContent(line)) {
                    QDomElement e = doc.firstChildElement("h2");
                    if (!e.isNull()) {
                        QString text = e.text();
                        QString id = e.attribute("id");
                        if (id.isEmpty()) {
                            id = QString("tmp_%1").arg(index);
                            e.setAttribute("id",id);
                        }
                        //<span class="navtop"><a href="#top">[Top]</a></span>
                        QDomElement span = doc.createElement("span");
                        span.setAttribute("class","navtop");
                        QDomElement a = doc.createElement("a");
                        a.setAttribute("href","#top");
                        QDomText top = doc.createTextNode("[Top]");
                        a.appendChild(top);
                        span.appendChild(a);
                        e.appendChild(span);

                        source = doc.toString();
                        navLines << QString("<dt><a href=\"#%1\">%2</a></dt>").arg(id).arg(text);
                    }
                }
            }
            else if (line.left(3) == "<h3") {
                if (doc.setContent(line)) {
                    QDomElement e = doc.firstChildElement("h3");
                    if (!e.isNull()) {
                        QString text = e.text();
                        QString id = e.attribute("id");
                        if (id.isEmpty()) {
                            id = QString("tmp_%1").arg(index);
                            e.setAttribute("id",id);
                        }
                        source = doc.toString();
                        navLines << QString("<dd><a href=\"#%1\">%2</a></dd>").arg(id).arg(text);
                    }
                }
           }
        }
        dstLines.append(source);
    }
Esempio n. 15
0
void Controller::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
	_this.setAttribute( "type", type() );
	_this.setAttribute( "name", name() );
}
void QgsAttributeEditorRelation::saveConfiguration( QDomElement& elem ) const
{
  elem.setAttribute( QStringLiteral( "relation" ), mRelation.id() );
  elem.setAttribute( QStringLiteral( "showLinkButton" ), mShowLinkButton );
  elem.setAttribute( QStringLiteral( "showUnlinkButton" ), mShowUnlinkButton );
}
void KisCurveRectangleMaskGenerator::toXML(QDomDocument& doc, QDomElement& e) const
{
    KisMaskGenerator::toXML(doc, e);
    e.setAttribute("type", "rect");
    e.setAttribute("softness_curve", curveString());
}
void QgsAttributeEditorField::saveConfiguration( QDomElement &elem ) const
{
  elem.setAttribute( QStringLiteral( "index" ), mIdx );
}
Esempio n. 19
0
/************************************************
 Its contents references an immediate sub-menu of the current menu, as such it should never contain
 a slash. If no such sub-menu exists the element should be ignored.
 This element may have various attributes, the default values are taken from the DefaultLayout key.

 show_empty [ bool ]
    defines whether a menu that contains no desktop entries and no sub-menus
    should be shown at all.

 inline [ bool ]
    If the inline attribute is "true" the menu that is referenced may be copied into the current
    menu at the current point instead of being inserted as sub-menu of the current menu.

 inline_limit [ int ]
    defines the maximum number of entries that can be inlined. If the sub-menu has more entries
    than inline_limit, the sub-menu will not be inlined. If the inline_limit is 0 (zero) there
    is no limit.

 inline_header [ bool ]
    defines whether an inlined menu should be preceded with a header entry listing the caption of
    the sub-menu.

 inline_alias [ bool ]
    defines whether a single inlined entry should adopt the caption of the inlined menu. In such
    case no additional header entry will be added regardless of the value of the inline_header
    attribute.

 Example: if a menu has a sub-menu titled "WordProcessor" with a single entry "OpenOffice 4.2", and
 both inline="true" and inline_alias="true" are specified then this would result in the
 "OpenOffice 4.2" entry being inlined in the current menu but the "OpenOffice 4.2" caption of the
 entry would be replaced with "WordProcessor".
 ************************************************/
void XdgMenuLayoutProcessor::processMenunameTag(const QDomElement &element)
{
    QString id = element.text();
    QDomElement menu = searchElement(QLatin1String("Menu"), QLatin1String("name"), id);
    if (menu.isNull())
        return;

    LayoutParams params = mDefaultParams;
    setParams(element, &params);

    int count = childsCount(menu);

    if (count == 0)
    {
        if (params.mShowEmpty)
        {
            menu.setAttribute(QLatin1String("keep"), QLatin1String("true"));
            mResult.appendChild(menu);
        }
        return;
    }


    bool doInline = params.mInline &&
                    (!params.mInlineLimit || params.mInlineLimit > count);

    bool doAlias = params.mInlineAlias &&
                   doInline && (count == 1);

    bool doHeader = params.mInlineHeader &&
                    doInline && !doAlias;


    if (!doInline)
    {
        mResult.appendChild(menu);
        return;
    }


    // Header ....................................
    if (doHeader)
    {
        QDomElement header = mLayout.ownerDocument().createElement(QLatin1String("Header"));

        QDomNamedNodeMap attrs = menu.attributes();
        for (int i=0; i < attrs.count(); ++i)
        {
            header.setAttributeNode(attrs.item(i).toAttr());
        }

        mResult.appendChild(header);
    }

    // Alias .....................................
    if (doAlias)
    {
        menu.firstChild().toElement().setAttribute(QLatin1String("title"), menu.attribute(QLatin1String("title")));
    }

    // Inline ....................................
    MutableDomElementIterator it(menu);
    while (it.hasNext())
    {
        mResult.appendChild(it.next());
    }

}
void stereoEnhancerControls::saveSettings( QDomDocument & _doc, 
							QDomElement & _this )
{
	_this.setAttribute( "width", m_widthModel.value() );
}
Esempio n. 21
0
void Dummy::writeData( QDomElement& element )
{
    element.setAttribute( "intVal",  _intVal );
    element.setAttribute( "doubleVal",  _doubleVal );
    element.setAttribute( "stringVal",  _stringVal );
}
Esempio n. 22
0
bool QgsComposerItem::_writeXml( QDomElement &itemElem, QDomDocument &doc ) const
{
  if ( itemElem.isNull() )
  {
    return false;
  }

  QDomElement composerItemElem = doc.createElement( QStringLiteral( "ComposerItem" ) );

  //frame
  if ( mFrame )
  {
    composerItemElem.setAttribute( QStringLiteral( "frame" ), QStringLiteral( "true" ) );
  }
  else
  {
    composerItemElem.setAttribute( QStringLiteral( "frame" ), QStringLiteral( "false" ) );
  }

  //background
  if ( mBackground )
  {
    composerItemElem.setAttribute( QStringLiteral( "background" ), QStringLiteral( "true" ) );
  }
  else
  {
    composerItemElem.setAttribute( QStringLiteral( "background" ), QStringLiteral( "false" ) );
  }

  //scene rect
  QPointF pagepos = pagePos();
  composerItemElem.setAttribute( QStringLiteral( "x" ), QString::number( pos().x() ) );
  composerItemElem.setAttribute( QStringLiteral( "y" ), QString::number( pos().y() ) );
  composerItemElem.setAttribute( QStringLiteral( "page" ), page() );
  composerItemElem.setAttribute( QStringLiteral( "pagex" ), QString::number( pagepos.x() ) );
  composerItemElem.setAttribute( QStringLiteral( "pagey" ), QString::number( pagepos.y() ) );
  composerItemElem.setAttribute( QStringLiteral( "width" ), QString::number( rect().width() ) );
  composerItemElem.setAttribute( QStringLiteral( "height" ), QString::number( rect().height() ) );
  composerItemElem.setAttribute( QStringLiteral( "positionMode" ), QString::number( static_cast< int >( mLastUsedPositionMode ) ) );
  composerItemElem.setAttribute( QStringLiteral( "zValue" ), QString::number( zValue() ) );
  composerItemElem.setAttribute( QStringLiteral( "outlineWidth" ), QString::number( mFrameWidth ) );
  composerItemElem.setAttribute( QStringLiteral( "frameJoinStyle" ), QgsSymbolLayerUtils::encodePenJoinStyle( mFrameJoinStyle ) );
  composerItemElem.setAttribute( QStringLiteral( "itemRotation" ), QString::number( mItemRotation ) );
  composerItemElem.setAttribute( QStringLiteral( "uuid" ), mUuid );
  composerItemElem.setAttribute( QStringLiteral( "id" ), mId );
  composerItemElem.setAttribute( QStringLiteral( "visibility" ), isVisible() );
  //position lock for mouse moves/resizes
  if ( mItemPositionLocked )
  {
    composerItemElem.setAttribute( QStringLiteral( "positionLock" ), QStringLiteral( "true" ) );
  }
  else
  {
    composerItemElem.setAttribute( QStringLiteral( "positionLock" ), QStringLiteral( "false" ) );
  }

  composerItemElem.setAttribute( QStringLiteral( "lastValidViewScaleFactor" ), QString::number( mLastValidViewScaleFactor ) );

  //frame color
  QDomElement frameColorElem = doc.createElement( QStringLiteral( "FrameColor" ) );
  frameColorElem.setAttribute( QStringLiteral( "red" ), QString::number( mFrameColor.red() ) );
  frameColorElem.setAttribute( QStringLiteral( "green" ), QString::number( mFrameColor.green() ) );
  frameColorElem.setAttribute( QStringLiteral( "blue" ), QString::number( mFrameColor.blue() ) );
  frameColorElem.setAttribute( QStringLiteral( "alpha" ), QString::number( mFrameColor.alpha() ) );
  composerItemElem.appendChild( frameColorElem );

  //background color
  QDomElement bgColorElem = doc.createElement( QStringLiteral( "BackgroundColor" ) );
  bgColorElem.setAttribute( QStringLiteral( "red" ), QString::number( mBackgroundColor.red() ) );
  bgColorElem.setAttribute( QStringLiteral( "green" ), QString::number( mBackgroundColor.green() ) );
  bgColorElem.setAttribute( QStringLiteral( "blue" ), QString::number( mBackgroundColor.blue() ) );
  bgColorElem.setAttribute( QStringLiteral( "alpha" ), QString::number( mBackgroundColor.alpha() ) );
  composerItemElem.appendChild( bgColorElem );

  //blend mode
  composerItemElem.setAttribute( QStringLiteral( "blendMode" ), QgsPainting::getBlendModeEnum( mBlendMode ) );

  //opacity
  composerItemElem.setAttribute( QStringLiteral( "opacity" ), QString::number( mOpacity ) );

  composerItemElem.setAttribute( QStringLiteral( "excludeFromExports" ), mExcludeFromExports );

  QgsComposerObject::writeXml( composerItemElem, doc );
  itemElem.appendChild( composerItemElem );

  return true;
}
Esempio n. 23
0
void Element::write(QDomElement& obj)
{
  Serializable::write(obj);
  // Set id.
  obj.setAttribute("id", getId());
}
Esempio n. 24
0
QDomDocument *Project::toXML() {
	QDomDocument *doc = new QDomDocument;

	QDomElement projectNode = doc->createElement("project");

	//
	// Cameras
	//
	QDomElement camerasNode = doc->createElement("cameras");
	foreach(CameraPtr cam, cameras_) {
		QDomElement cameraNode = doc->createElement("camera");

		cameraNode.setAttribute("id", cam->id());
		if(!cam->name().isEmpty() && cam->name() != cam->id())
			cameraNode.setAttribute("name", cam->name());

		// The projection matrix node is required, so no need to check for null
		QDomElement projectionMatrixNode = doc->createElement("projectionMatrix");
		projectionMatrixNode.setAttribute("m11", cam->P()(0, 0));
		projectionMatrixNode.setAttribute("m12", cam->P()(0, 1));
		projectionMatrixNode.setAttribute("m13", cam->P()(0, 2));
		projectionMatrixNode.setAttribute("m14", cam->P()(0, 3));
		projectionMatrixNode.setAttribute("m21", cam->P()(1, 0));
		projectionMatrixNode.setAttribute("m22", cam->P()(1, 1));
		projectionMatrixNode.setAttribute("m23", cam->P()(1, 2));
		projectionMatrixNode.setAttribute("m24", cam->P()(1, 3));
		projectionMatrixNode.setAttribute("m31", cam->P()(2, 0));
		projectionMatrixNode.setAttribute("m32", cam->P()(2, 1));
		projectionMatrixNode.setAttribute("m33", cam->P()(2, 2));
		projectionMatrixNode.setAttribute("m34", cam->P()(2, 3));
		cameraNode.appendChild(projectionMatrixNode);

		//
		QDomElement lensDistortionNode = doc->createElement("lensDistortion");
		if(qAbs(cam->lensDistortion()[0]) > 1e-10)
			lensDistortionNode.setAttribute("k1", cam->lensDistortion()[0]);

		if(qAbs(cam->lensDistortion()[1]) > 1e-10)
			lensDistortionNode.setAttribute("k2", cam->lensDistortion()[1]);

		if(qAbs(cam->lensDistortion()[2]) > 1e-10)
			lensDistortionNode.setAttribute("p1", cam->lensDistortion()[2]);

		if(qAbs(cam->lensDistortion()[3]) > 1e-10)
			lensDistortionNode.setAttribute("p2", cam->lensDistortion()[3]);

		if(qAbs(cam->lensDistortion()[4]) > 1e-10)
			lensDistortionNode.setAttribute("k3", cam->lensDistortion()[4]);

		if(lensDistortionNode.attributes().size() > 0)
			cameraNode.appendChild(lensDistortionNode);

		//
		if(cam->response().size() == 256) {
			QDomElement redResponseCurveNode = doc->createElement("response");
			QDomElement greenResponseCurveNode = doc->createElement("response");
			QDomElement blueResponseCurveNode = doc->createElement("response");

			redResponseCurveNode.setAttribute("channel", "red");
			greenResponseCurveNode.setAttribute("channel", "green");
			blueResponseCurveNode.setAttribute("channel", "blue");

			foreach(const Response &response, cam->response()) {
				if(fabs(response[0]) > 1e-10)
					redResponseCurveNode.appendChild( createSimpleElement(doc, "value", response[0]) );

				if(fabs(response[1]) > 1e-10)
					greenResponseCurveNode.appendChild( createSimpleElement(doc, "value", response[1]) );

				if(fabs(response[2]) > 1e-10)
					blueResponseCurveNode.appendChild( createSimpleElement(doc, "value", response[2]) );
			}

			if(redResponseCurveNode.childNodes().size() > 0) cameraNode.appendChild(redResponseCurveNode);
			if(greenResponseCurveNode.childNodes().size() > 0) cameraNode.appendChild(greenResponseCurveNode);
			if(blueResponseCurveNode.childNodes().size() > 0) cameraNode.appendChild(blueResponseCurveNode);
		}
Esempio n. 25
0
int main(int argc, char *argv[])
{
    KCmdLineOptions options;
    options.add("+file", ki18n("URL to open"));

    KCmdLineArgs::init(argc, argv, "testkhtml", 0, ki18n("Testkhtml"),
            "1.0", ki18n("a basic web browser using the KHTML library"));
    KCmdLineArgs::addCmdLineOptions(options);

    KApplication a;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs( );
    if ( args->count() == 0 ) {
	KCmdLineArgs::usage();
	::exit( 1 );
    }

    new KHTMLGlobal;

    KXmlGuiWindow *toplevel = new KXmlGuiWindow();
    KHTMLPart *doc = new KHTMLPart( toplevel, toplevel, KHTMLPart::BrowserViewGUI );

    Dummy *dummy = new Dummy( doc );
    QObject::connect( doc->browserExtension(), SIGNAL(openUrlRequest(KUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)),
		      dummy, SLOT(slotOpenURL(KUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)) );

    QObject::connect( doc, SIGNAL(completed()), dummy, SLOT(handleDone()) );

    if (args->url(0).url().right(4).toLower() == ".xml") {
        KParts::OpenUrlArguments args(doc->arguments());
        args.setMimeType("text/xml");
        doc->setArguments(args);
    }

    doc->openUrl( args->url(0) );

    toplevel->setCentralWidget( doc->widget() );
    toplevel->resize( 800, 600);

    QDomDocument d = doc->domDocument();
    QDomElement viewMenu = d.documentElement().firstChild().childNodes().item( 2 ).toElement();
    QDomElement e = d.createElement( "action" );
    e.setAttribute( "name", "debugRenderTree" );
    viewMenu.appendChild( e );
    e = d.createElement( "action" );
    e.setAttribute( "name", "debugDOMTree" );
    viewMenu.appendChild( e );
    e = d.createElement( "action" );
    e.setAttribute( "name", "debugDoBenchmark" );
    viewMenu.appendChild( e );

    QDomElement toolBar = d.documentElement().firstChild().nextSibling().toElement();
    e = d.createElement( "action" );
    e.setAttribute( "name", "editable" );
    toolBar.insertBefore( e, toolBar.firstChild() );
    e = d.createElement( "action" );
    e.setAttribute( "name", "navigable" );
    toolBar.insertBefore( e, toolBar.firstChild() );
    e = d.createElement( "action" );
    e.setAttribute( "name", "reload" );
    toolBar.insertBefore( e, toolBar.firstChild() );
    e = d.createElement( "action" );
    e.setAttribute( "name", "print" );
    toolBar.insertBefore( e, toolBar.firstChild() );

    KAction *action = new KAction(KIcon("view-refresh"),  "Reload", doc );
    doc->actionCollection()->addAction( "reload", action );
    QObject::connect(action, SIGNAL(triggered(bool)), dummy, SLOT(reload()));
    action->setShortcut(Qt::Key_F5);

    KAction *bench = new KAction( KIcon(), "Benchmark...", doc );
    doc->actionCollection()->addAction( "debugDoBenchmark", bench );
    QObject::connect(bench, SIGNAL(triggered(bool)), dummy, SLOT(doBenchmark()));

    KAction *kprint = new KAction(KIcon("document-print"),  "Print", doc );
    doc->actionCollection()->addAction( "print", kprint );
    QObject::connect(kprint, SIGNAL(triggered(bool)), doc->browserExtension(), SLOT(print()));
    kprint->setEnabled(true);
    KToggleAction *ta = new KToggleAction( KIcon("edit-rename"), "Navigable", doc );
    doc->actionCollection()->addAction( "navigable", ta );
    ta->setShortcuts( KShortcut() );
    ta->setChecked(doc->isCaretMode());
    QWidget::connect(ta, SIGNAL(toggled(bool)), dummy, SLOT(toggleNavigable(bool)));
    ta = new KToggleAction( KIcon("document-properties"), "Editable", doc );
    doc->actionCollection()->addAction( "editable", ta );
    ta->setShortcuts( KShortcut() );
    ta->setChecked(doc->isEditable());
    QWidget::connect(ta, SIGNAL(toggled(bool)), dummy, SLOT(toggleEditable(bool)));
    toplevel->guiFactory()->addClient( doc );

    doc->setJScriptEnabled(true);
    doc->setJavaEnabled(true);
    doc->setPluginsEnabled( true );
    doc->setURLCursor(QCursor(Qt::PointingHandCursor));
    a.setTopWidget(doc->widget());
    QWidget::connect(doc, SIGNAL(setWindowCaption(QString)),
		     doc->widget()->topLevelWidget(), SLOT(setCaption(QString)));
    doc->widget()->show();
    toplevel->show();
    doc->view()->viewport()->show();
    doc->view()->widget()->show();


    int ret = a.exec();
    return ret;
}
Esempio n. 26
0
QDomNode CGroupChar::toXML()
{

  QDomDocument doc("charinfo");

  QDomElement root = doc.createElement("playerData");
  root.setAttribute("name", QString(name) );
  root.setAttribute("color", color.name() );
  root.setAttribute("textHP", QString(textHP) );
  root.setAttribute("textMana", QString(textMana) );
  root.setAttribute("textMoves", QString(textMoves) );
  root.setAttribute("hp", hp );
  root.setAttribute("maxhp", maxhp );
  root.setAttribute("mana", mana);
  root.setAttribute("maxmana", maxmana);
  root.setAttribute("moves", moves );
  root.setAttribute("maxmoves", maxmoves );
  root.setAttribute("state", state );
  root.setAttribute("lastMovement", QString(lastMovement));
  root.setAttribute("room", pos );
  doc.appendChild(root);

  return root;
}
Esempio n. 27
0
File: mmp.cpp Progetto: Orpheon/lmms
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());
}
Esempio n. 28
0
/**
	Exporte tout ou partie du schema 
	@param whole_content Booleen (a vrai par defaut) indiquant si le XML genere doit
	representer l'integralite du schema ou seulement le contenu selectionne
	@return Un Document XML (QDomDocument)
*/
QDomDocument Diagram::toXml(bool whole_content) {
	// document
	QDomDocument document;
	
	// racine de l'arbre XML
	QDomElement racine = document.createElement("diagram");
	
	// add the application version number
	racine.setAttribute("version", QET::version);
	
	// proprietes du schema
	if (whole_content) {
		border_and_titleblock.titleBlockToXml(racine);
		border_and_titleblock.borderToXml(racine);
		
		// type de conducteur par defaut
		QDomElement default_conductor = document.createElement("defaultconductor");
		defaultConductorProperties.toXml(default_conductor);
		racine.appendChild(default_conductor);

		//autonumerotation of conductor
		if (!getNumerotation(Diagram::Conductors).isEmpty()) {
			QDomElement autonum = document.createElement("autonum");
			autonum.appendChild(getNumerotation(Diagram::Conductors).toXml(document, "conductor"));
			racine.appendChild(autonum);
		}
	}
	document.appendChild(racine);
	
	// si le schema ne contient pas d'element (et donc pas de conducteurs), on retourne de suite le document XML
	if (items().isEmpty()) return(document);
	
	// creation de trois listes : une qui contient les elements, une qui contient les conducteurs, une qui contient les champs de texte
	QList<Element *> list_elements;
	QList<Conductor *> list_conductors;
	QList<DiagramTextItem *> list_texts;
	QList<DiagramImageItem *> list_images;
	
	// Determine les elements a "XMLiser"
	foreach(QGraphicsItem *qgi, items()) {
		if (Element *elmt = qgraphicsitem_cast<Element *>(qgi)) {
			if (whole_content) list_elements << elmt;
			else if (elmt -> isSelected()) list_elements << elmt;
		} else if (Conductor *f = qgraphicsitem_cast<Conductor *>(qgi)) {
			if (whole_content) list_conductors << f;
			// lorsqu'on n'exporte pas tout le diagram, il faut retirer les conducteurs non selectionnes
			// et pour l'instant, les conducteurs non selectionnes sont les conducteurs dont un des elements n'est pas selectionne
			else if (f -> terminal1 -> parentItem() -> isSelected() && f -> terminal2 -> parentItem() -> isSelected()) {
				list_conductors << f;
			}
		} else if (IndependentTextItem *iti = qgraphicsitem_cast<IndependentTextItem *>(qgi)) {
			if (whole_content) list_texts << iti;
			else if (iti -> isSelected()) list_texts << iti;
		} else if (DiagramImageItem *dii = qgraphicsitem_cast<DiagramImageItem *>(qgi)) {
			if (whole_content) list_images << dii;
			else if (dii -> isSelected()) list_images << dii;
		}
	}
	
	// table de correspondance entre les adresses des bornes et leurs ids
	QHash<Terminal *, int> table_adr_id;
	
	// enregistrement des elements
	if (!list_elements.isEmpty()) {
		QDomElement elements = document.createElement("elements");
		foreach(Element *elmt, list_elements) {
			elements.appendChild(elmt -> toXml(document, table_adr_id));
		}
Esempio n. 29
0
void MythBurn::createConfigFile(const QString &filename)
{
    QDomDocument doc("mythburn");

    QDomElement root = doc.createElement("mythburn");
    doc.appendChild(root);

    QDomElement job = doc.createElement("job");
    job.setAttribute("theme", m_theme);
    root.appendChild(job);

    QDomElement media = doc.createElement("media");
    job.appendChild(media);

    // now loop though selected archive items and add them to the xml file
    ArchiveItem *a;
    MythUIButtonListItem *item;
    for (int x = 0; x < m_archiveButtonList->GetCount(); x++)
    {
        item = m_archiveButtonList->GetItemAt(x);
        if (!item)
            continue;

        a = qVariantValue<ArchiveItem *>(item->GetData());
        if (!a)
            continue;

        QDomElement file = doc.createElement("file");
        file.setAttribute("type", a->type.toLower() );
        file.setAttribute("usecutlist", a->useCutlist);
        file.setAttribute("filename", a->filename);
        file.setAttribute("encodingprofile", a->encoderProfile->name);
        if (a->editedDetails)
        {
            QDomElement details = doc.createElement("details");
            file.appendChild(details);
            details.setAttribute("title", a->title);
            details.setAttribute("subtitle", a->subtitle);
            details.setAttribute("startdate", a->startDate);
            details.setAttribute("starttime", a->startTime);
            QDomText desc = doc.createTextNode(a->description);
            details.appendChild(desc);
        }

        if (a->thumbList.size() > 0)
        {
            QDomElement thumbs = doc.createElement("thumbimages");
            file.appendChild(thumbs);

            for (int x = 0; x < a->thumbList.size(); x++)
            {
                QDomElement thumb = doc.createElement("thumb");
                thumbs.appendChild(thumb);
                ThumbImage *thumbImage = a->thumbList.at(x);
                thumb.setAttribute("caption", thumbImage->caption);
                thumb.setAttribute("filename", thumbImage->filename);
                thumb.setAttribute("frame", (int) thumbImage->frame);
            }
        }

        media.appendChild(file);
    }

    // add the options to the xml file
    QDomElement options = doc.createElement("options");
    options.setAttribute("createiso", m_bCreateISO);
    options.setAttribute("doburn", m_bDoBurn);
    options.setAttribute("mediatype", m_archiveDestination.type);
    options.setAttribute("dvdrsize", (qint64)m_archiveDestination.freeSpace);
    options.setAttribute("erasedvdrw", m_bEraseDvdRw);
    options.setAttribute("savefilename", m_saveFilename);
    job.appendChild(options);

    // finally save the xml to the file
    QFile f(filename);
    if (!f.open(QIODevice::WriteOnly))
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("MythBurn::createConfigFile: "
                    "Failed to open file for writing - %1") .arg(filename));
        return;
    }

    QTextStream t(&f);
    t << doc.toString(4);
    f.close();
}
/**
* \brief This function verify if a similar element is not already written and write the element at the good place
* \author Jules Gorny - ALCoV team, ISIT, UMR 6284 UdA – CNRS
* \param doc : QDomDocument containing the xml tree
* \param elemName : Name of the XML element
* \param elemValue : Value of the XML element
* \param attributes : QMap<QString, QString> with the attribute's name in key and the atttribute's value in value
* \param parentsStr : A string containing a hierarchy of parents written like .../.../grandFather/father (used to compare the parents of existing elements and the new one)
* \param parentsAttr : QMap<QString, QMap<QString, QString>> containing the parent name in the key and a map build like the attributes param in the value (used to compare the parents of existing elements and the new one)
* \param ui : in case we want to write a message to the user.
**/
void writeElement(QDomDocument &doc, QDomElement &addedNode, QString elemName, QString elemValue, QMap<QString, QString> attributes, QString parentsStr, QMap<QString, QMap<QString, QString>> parentsAttr, Ui::MainWindow *ui)
{
	QStringList parents;
	if(parentsStr != "")
		parents = parentsStr.split("/");

	/**
	* We try to find where we want to include our new node. For that we browse the XML tree keeping a track on the closer parent of our node we found.
	* This closer parent is named "last parent" cause it's the last we found while going deeper in the tree.
	**/
	QDomNodeList lastParentFoundList;
	QDomNode ourActualLastParent;
	//If we have at least one parent, we search the first one (it will be "Patient")
	if( parents.size() > 0 )
	{
		lastParentFoundList = doc.elementsByTagName(parents.at(0));
		ourActualLastParent = lastParentFoundList.at(0);
	}
	//If we don't have parents
	else
	{
		//And if there is no Patient node 
		if( doc.elementsByTagName("Patient").size() == 0 )
		{
			//We create the element at the root (if the program is well written, it's supposed to be a new Patient node)
			addedNode = doc.createElement(elemName);
			if( elemValue != "" )
			{
				QDomText nameText = doc.createTextNode(elemValue);
				addedNode.appendChild(nameText);
			}
			if( attributes.size() > 0 )
			{
				QMap<QString, QString>::Iterator it;
				for( it = attributes.begin() ; it != attributes.end() ; ++it)
					addedNode.setAttribute(it.key(), it.value());
			}
			doc.appendChild(addedNode);
		}
	}

	//The lastParent is now initialized with "Patient", we can browse the rest of the parents tree.
	for( int p=1; p<parents.size(); p++ )
	{
		//We search the list of nodes corresponding to second older parent name (after Patient)
		lastParentFoundList = ourActualLastParent.toElement().elementsByTagName(parents.at(p));
		//If we can't find any parent candidate, there is a problem in the program ...
		if( lastParentFoundList.size() == 0 )
		{
			addProgressMessage(ui, "Looks like the developper didn't do a great job. The parents list doesn't match the XML file we are browsing.", Qt::black, "", false);
		}
		//If there is at least one parent node found with that name, we will compare the attribute
		else
		{
			bool weFoundWhatWeWanted = false;
			//Browse the different parent candidates
			for( int f=0; f<lastParentFoundList.size(); f++ )
			{
				//We estimate that the attributes correspond to what we want
				bool areAllAttributesSimilar = true;
				QDomNamedNodeMap parentsAttributes = lastParentFoundList.at(f).attributes();
				//We browse the attribute to find if one attribute doesn't correspond
				for(int a=0; a<parentsAttributes.size(); a++)
				{
					QString parentAttrName = parentsAttributes.item(a).toAttr().name();
					QString parentAttrValue = parentsAttributes.item(a).toAttr().value();
					QMap<QString, QString> tempAttr = parentsAttr.find(parents.at(p)).value();
					//In that case, we continue to browse the different parent candidates
					if( !tempAttr.contains(parentAttrName) || tempAttr.find(parentAttrName).value() != parentAttrValue)
					{
						areAllAttributesSimilar = false;
						break;
					}
				}
				//If we found the perfect candidate, we keep it and stop brownsing the candidates. We can go deeper in the tree.
				if( areAllAttributesSimilar )
				{
					ourActualLastParent = lastParentFoundList.at(f);
					weFoundWhatWeWanted = true;
					break;
				}
			}
			//If we didn't find any corresponding parent, there is a problem in the program ...
			if( !weFoundWhatWeWanted )
			{
				addProgressMessage(ui, "Looks like the developper didn't do a great job. The parents list doesn't match the XML file we are browsing.", Qt::black, "", false);
			}
		}
	}
	
	//We finally found our closer parent !
	QDomNodeList sameElementFoundList;
	sameElementFoundList = ourActualLastParent.toElement().elementsByTagName(elemName);
	bool isAnElementSimilar = false;
	//We try to find a similar element (Name + attributes)
	for( int f=0; f<sameElementFoundList.size(); f++ )
	{
		bool areAllAttributesSimilar = true;
		QDomNamedNodeMap parentsAttributes = sameElementFoundList.at(f).attributes();
		for(int a=0; a<parentsAttributes.size(); a++)
		{
			QString parentAttrName = parentsAttributes.item(a).toAttr().name();
			QString parentAttrValue = parentsAttributes.item(a).toAttr().value();
			if( !attributes.contains(parentAttrName) || attributes.find(parentAttrName).value() != parentAttrValue)
			{
				areAllAttributesSimilar = false;
				break;
			}
		}
		if( areAllAttributesSimilar )
		{
			isAnElementSimilar = true;
			addedNode = sameElementFoundList.at(f).toElement();
			break;
		}
	}

	//If the element definitly doesn't exists, we create it
	if( !isAnElementSimilar )
	{
		addedNode = doc.createElement(elemName);
		if( elemValue != "" )
		{
			QDomText nameText = doc.createTextNode(elemValue);
			addedNode.appendChild(nameText);
		}
		if( attributes.size() > 0 )
		{
			QMap<QString, QString>::Iterator it;
			for( it = attributes.begin() ; it != attributes.end() ; ++it)
				addedNode.setAttribute(it.key(), it.value());
		}
		ourActualLastParent.toElement().appendChild(addedNode);
	}
}