// Add an object to this space from a dom element
void GOCXMLSpace::goc_addXMLObject(QDomElement xmlObjectElem){
	//Create an XMLObject from the dom element - in this XMLSpace
	GOCXMLObject *xmlObj = new GOCXMLObject(xmlObjectElem,this);
	
	QDomNode nObjNode = xmlObjectElem.firstChild();
	if(!nObjNode.isNull() && !nObjNode.isText()){//TODO: manage the text case and comments
		//Create a sub space of the object - if it has child(ren)
                xmlObj->goc_setXMLObjectSubbed(true);
	}
	GOCXMLSpace *xmlObjSubSpace = xmlObj->goc_getXMLObjectSpace();
	while(!nObjNode.isNull()) {
		
		QDomElement e = nObjNode.toElement(); // try to convert the node to an element.
		
		if(!nObjNode.isText()){
			//Add a new object
			xmlObjSubSpace->goc_addXMLObject(e);
		}else{
			//Update the node value
			QString sNodeValue = nObjNode.nodeValue();
			QVariant vNodeValue = QVariant(sNodeValue);
                        GOCAttribute *gocAtt = new GOCAttribute(xmlObj);
                        QSharedPointer<GOCAttribute> spAtt(gocAtt);
                        spAtt->attName = GOCOBJECT_OBJECTNODEVALUE;
                        spAtt->attValue = vNodeValue;
                        spAtt->attVisible = true;
                        spAtt->attRemovable = false;
			xmlObj->goc_setObjectNodeValue(sNodeValue);
            spAtt->attNameModifiable = false;
		}
		nObjNode = nObjNode.nextSibling();
	}

}
Example #2
0
/**
 * \en
 * Deletes row, having section tag
 * \_en
 * \ru
 * Рекурсивная функция. Удаляет строки, содержащие тег секции
 * \_ru
* \param node - \en context \_en \ru узел из которого нужно удалить строки \_ru
 */
void
aMSOTemplate::clearRow(QDomNode node)
{
QDomNode n = node.lastChild();
	while( !n.isNull() )
	{	
		if(n.isText())
		{
			QString str = n.nodeValue();
			QRegExp re;
			re.setPattern(QString("%1.*%2").arg(open_token_section).arg(close_token_section));
			re.setMinimal(true);
			int pos = re.search(str,0);
			if(pos!=-1)
			{
				QDomNode tmp = n;
				while(!tmp.parentNode().isNull())
				{
					tmp = tmp.parentNode();
					if( tmp.nodeName()=="Row" ) 
					{
						tmp.parentNode().removeChild(tmp);
						break;
					}
				}
			}
		}
		else
		{
			clearRow(n);
		}
		n = n.previousSibling();
	}	
}
Example #3
0
void Configure::printTree(QDomElement element,QString indent) {
    QDomNode n = element.firstChild();
    if(n.isText()) {
        qDebug()<<element.tagName()<<":"<<n.nodeValue();
        widget.textEditConfiguration->append(indent+element.tagName()+": "+n.nodeValue());
        // save interesting information
        if(element.tagName()=="type") {
            serverType=n.nodeValue();
        } else if(element.tagName()=="samplerate") {
            sampleRate=n.nodeValue().toInt();
        } else if(element.tagName()=="minfrequency") {
            minFrequency=n.nodeValue().toLong();
        } else if(element.tagName()=="maxfrequency") {
            maxFrequency=n.nodeValue().toLong();
        }
    } else {
        qDebug()<<element.tagName();
        widget.textEditConfiguration->append(indent+element.tagName());
        while(!n.isNull()) {
            QDomElement e = n.toElement(); // try to convert the node to an element.
            if(!e.isNull()) {
                if(e.hasAttributes()) {
                    QDomNamedNodeMap attributes=e.attributes();
                    qDebug()<<"attributes:"<<attributes.count();
                    for(int i=0;i<attributes.count();i++) {
                        QDomNode a=attributes.item(i);
                        qDebug()<<"attribute: "<<a.nodeName()<<":"<<a.nodeValue();
                    }
                }
                printTree(e,indent+"    ");
            }
            n = n.nextSibling();
        }
    }
}
Example #4
0
/**
 * \en
 * Return true, if node contain tag
 * \_en
 * \ru
 * Возвращает истину, когда текст ноды содержит тег с заданным именем.
 * \_en
 * \param node - \en context for searching \_en \ru узел, с которого осуществляется поиск. \_ru
 * \param sname - \en tag name \_en \ru имя тега для поиска \_ru
 * \param params - \en true, if find simple tag and false, if section \_en
 * 		\ru true, если ищется обычный тег и false, если ищется тег секции \_ru
 */
bool
aMSOTemplate::getNodeTags(QDomNode node, const QString &tagname, bool params )
{
  	if(node.isText())
	{
		QString str = node.nodeValue();
		QRegExp re;
		if(params)
		{
			re.setPattern(QString("%1.*%2").arg(open_token).arg(close_token));
		}
		else
		{
			re.setPattern(QString("%1.*%2").arg(open_token_section).arg(close_token_section));	
		}
		re.setMinimal(true);
		int pos = re.search(str,0);
		
		while(pos != -1)
		{
			if(tagname == str.mid(pos+2, re.matchedLength()-4))
			{
				return true;
			}
			pos+= re.matchedLength();
			pos = re.search(str,pos);
		}
		
	}
 return false;	
}
Example #5
0
static void helperToXmlAddDomElement(QXmlStreamWriter* stream, const QDomElement& element, const QStringList &omitNamespaces)
{
    stream->writeStartElement(element.tagName());

    /* attributes */
    QString xmlns = element.namespaceURI();
    if (!xmlns.isEmpty() && !omitNamespaces.contains(xmlns))
        stream->writeAttribute("xmlns", xmlns);
    QDomNamedNodeMap attrs = element.attributes();
    for (int i = 0; i < attrs.size(); i++)
    {
        QDomAttr attr = attrs.item(i).toAttr();
        stream->writeAttribute(attr.name(), attr.value());
    }

    /* children */
    QDomNode childNode = element.firstChild();
    while (!childNode.isNull())
    {
        if (childNode.isElement())
        {
            helperToXmlAddDomElement(stream, childNode.toElement(), QStringList() << xmlns);
        } else if (childNode.isText()) {
            stream->writeCharacters(childNode.toText().data());
        }
        childNode = childNode.nextSibling();
    }
    stream->writeEndElement();
}
Example #6
0
bool QDomNodeProto:: isText() const
{
  QDomNode *item = qscriptvalue_cast<QDomNode*>(thisObject());
  if (item)
    return item->isText();
  return false;
}
Example #7
0
bool Converter::convertHeader( QTextCursor *cursor, const QDomElement &element )
{
  const QString styleName = element.attribute( QStringLiteral("style-name") );
  const StyleFormatProperty property = mStyleInformation->styleProperty( styleName );

  QTextBlockFormat blockFormat;
  QTextCharFormat textFormat;
  property.applyBlock( &blockFormat );
  property.applyText( &textFormat );

  cursor->setBlockFormat( blockFormat );

  QDomNode child = element.firstChild();
  while ( !child.isNull() ) {
    if ( child.isElement() ) {
      const QDomElement childElement = child.toElement();
      if ( childElement.tagName() == QLatin1String( "span" ) ) {
        if ( !convertSpan( cursor, childElement, textFormat ) )
          return false;
      }
    } else if ( child.isText() ) {
      const QDomText childText = child.toText();
      if ( !convertTextNode( cursor, childText, textFormat ) )
        return false;
    }

    child = child.nextSibling();
  }

  emit addTitle( element.attribute( QStringLiteral("outline-level"), QStringLiteral("0") ).toInt(), element.text(), cursor->block() );

  return true;
}
Example #8
0
bool Converter::convertLink(QTextCursor *cursor, const QDomElement &element, const QTextCharFormat &format)
{
    int startPosition = cursor->position();

    QDomNode child = element.firstChild();
    while (!child.isNull())
    {
        if (child.isElement())
        {
            const QDomElement childElement = child.toElement();
            if (childElement.tagName() == QLatin1String("span"))
            {
                if (!convertSpan(cursor, childElement, format))
                    return false;
            }
        }
        else if (child.isText())
        {
            const QDomText childText = child.toText();
            if (!convertTextNode(cursor, childText, format))
                return false;
        }

        child = child.nextSibling();
    }

    int endPosition = cursor->position();
    USETODONEXT(endPosition);
    USETODONEXT(startPosition);
    return true;
}
Example #9
0
bool Converter::convertLink( QTextCursor *cursor, const QDomElement &element, const QTextCharFormat &format )
{
  int startPosition = cursor->position();

  QDomNode child = element.firstChild();
  while ( !child.isNull() ) {
    if ( child.isElement() ) {
      const QDomElement childElement = child.toElement();
      if ( childElement.tagName() == QLatin1String( "span" ) ) {
        if ( !convertSpan( cursor, childElement, format ) )
          return false;
      }
    } else if ( child.isText() ) {
      const QDomText childText = child.toText();
      if ( !convertTextNode( cursor, childText, format ) )
        return false;
    }

    child = child.nextSibling();
  }

  int endPosition = cursor->position();

  Okular::Action *action = new Okular::BrowseAction( QUrl(element.attribute( QStringLiteral("href") )) );
  emit addAction( action, startPosition, endPosition );

  return true;
}
/**
   Get the project title

   XML in file has this form:
\verbatim
   <qgis projectname="default project">
   <title>a project title</title>
\endverbatim

   @todo XXX we should go with the attribute xor title, not both.
*/
static void _getTitle( QDomDocument const &doc, QString & title )
{
  QDomNodeList nl = doc.elementsByTagName( "title" );

  title = "";                 // by default the title will be empty

  if ( !nl.count() )
  {
    QgsDebugMsg( "unable to find title element" );
    return;
  }

  QDomNode titleNode = nl.item( 0 );  // there should only be one, so zeroth element ok

  if ( !titleNode.hasChildNodes() ) // if not, then there's no actual text
  {
    QgsDebugMsg( "unable to find title element" );
    return;
  }

  QDomNode titleTextNode = titleNode.firstChild();  // should only have one child

  if ( !titleTextNode.isText() )
  {
    QgsDebugMsg( "unable to find title element" );
    return;
  }

  QDomText titleText = titleTextNode.toText();

  title = titleText.data();

} // _getTitle
Example #11
0
QString ExampleContent::extractTextFromParagraph(const QDomNode &parentNode)
{
    QString description;
    QDomNode node = parentNode.firstChild();

    while (!node.isNull()) {
        QString beginTag;
        QString endTag;
        if (node.isText())
            description += Colors::contentColor + node.nodeValue();
        else if (node.hasChildNodes()) {
            if (node.nodeName() == "b") {
                beginTag = "<b>";
                endTag = "</b>";
            } else if (node.nodeName() == "a") {
                beginTag = Colors::contentColor;
                endTag = "</font>";
            } else if (node.nodeName() == "i") {
                beginTag = "<i>";
                endTag = "</i>";
            } else if (node.nodeName() == "tt") {
                beginTag = "<tt>";
                endTag = "</tt>";
            }
            description += beginTag + this->extractTextFromParagraph(node) + endTag;
        }
        node = node.nextSibling();
    }

    return description;
}
Example #12
0
//! function
static bool nodeToVariant(const QDomNode &aNode,QVariant &aValue) {
    bool vRetval = false;
    QString vType, vValue;

    aValue = QVariant();
    if(!vRetval && aNode.isCDATASection()) {
        vValue = aNode.toCDATASection().data();
        vRetval = true;
    }

    if(!vRetval && aNode.isText()) {
        vValue = aNode.toText().data();
        vRetval = true;
    }

    if(!vRetval) return vRetval;
    if(vValue.isEmpty()) return false; // ????

    const QDomNode vParent = aNode.parentNode();
    if(vParent.isElement()) {
        vType = vParent.toElement().attribute(QString::fromLatin1("type"));
    }

    if(vType == QString::fromLatin1("bytearray")) {
        aValue = QVariant(vValue.toLatin1());
    }
    else if(vType == QString::fromLatin1("variant")) {
        QByteArray vArray(vValue.toLatin1());
        QDataStream vStream(&vArray, QIODevice::ReadOnly);
        vStream >> aValue;
    }
Example #13
0
/**
 * @brief XmlEditWidgetPrivate::findDomNodeScan find the nearest match to a position
 * @param node
 * @param nodeTarget
 * @param lineSearched
 * @param columnSearched
 * @param lastKnownNode: last known "good" position
 * @return
 */
bool XmlEditWidgetPrivate::findDomNodeScan(QDomNode node, QDomNode nodeTarget, const int lineSearched, const int columnSearched, FindNodeWithLocationInfo &info)
{
    int row = node.lineNumber();
    int col = node.columnNumber();
    if(!node.isDocument()) {
        if((lineSearched == row) && (columnSearched == col)) {
            info.matchedNode = nodeTarget ;
            return true ;
        }

        if((lineSearched == row) && (columnSearched == col)) {
            info.matchedNode = nodeTarget ;
            return true ;
        }
        if((lineSearched == row) && (columnSearched < col)) {
            info.matchedNode = nodeTarget ;
            return true ;
        }
        if((lineSearched < row)) {
            info.matchedNode = nodeTarget ;
            return true ;
        }
        if((lineSearched <= row)) {
            info.lastKnownNode = nodeTarget ;
        }

        if(node.nodeType() == QDomNode::ElementNode) {
            QDomElement element = node.toElement();
            QDomNamedNodeMap attributes = element.attributes();
            int numAttrs = attributes.length();
            for(int i = 0 ; i < numAttrs ; i++) {
                QDomNode node = attributes.item(i);
                QDomAttr attr = node.toAttr();
                if(findDomNodeScan(attr, nodeTarget, lineSearched, columnSearched, info)) {
                    return true;
                }
            } // for
        }
    }

    int nodes = node.childNodes().count();
    for(int i = 0 ; i < nodes ; i ++) {
        QDomNode childNode = node.childNodes().item(i) ;
        if(childNode.isText() || childNode.isCDATASection()) {
            if(findDomNodeScan(childNode, nodeTarget, lineSearched, columnSearched, info)) {
                return true;
            }
        } else {
            if(findDomNodeScan(childNode, childNode, lineSearched, columnSearched, info)) {
                return true ;
            }
        }
    }
    return false ;
}
Example #14
0
void SoftwareImporters::importJreepadFile(){
    typedef QPair<BasketScene *, QDomElement> basketAndElementPair;

    QString fileName = KFileDialog::getOpenFileName(KUrl("kfiledialog:///:ImportJreepadFile"),
                                                    "*.xml|XML files");
    if (fileName.isEmpty()) {
        return;
    }

    basketAndElementPair newElement;
    basketAndElementPair currentElement;
    QList<basketAndElementPair> elements;
    QList<BasketScene*> basketList;

    QDomDocument *doc = XMLWork::openFile("node", fileName);
    newElement.second = doc->documentElement();

    BasketScene *basket = 0;
    BasketFactory::newBasket(/*icon=*/"xml", /*name=*/doc->documentElement().attribute("title"), 
                             /*backgroundImage=*/"", /*backgroundColor=*/QColor(), 
                             /*textColor=*/QColor(), /*templateName=*/"1column", /*createIn=*/0);
    basket = Global::bnpView->currentBasket();
    basket->load();
    basketList << basket;
    newElement.first = basket;

    elements << newElement;

    while ( !elements.isEmpty() ) {
        currentElement = elements.takeFirst();
        for (QDomNode n = currentElement.second.firstChild(); !n.isNull(); n = n.nextSibling()) {
            if ( n.isText() ) {
                basket = currentElement.first;
                Note *note = NoteFactory::createNoteFromText(n.toText().data(), basket);
                basket->insertNote(note, basket->firstNote(), 
                                   Note::BottomColumn, QPoint(), /*animate=*/false);
            } else if ( n.isElement() ) {
                BasketFactory::newBasket(/*icon=*/"xml", /*name=*/n.toElement().attribute("title"), 
                                         /*backgroundImage=*/"", /*backgroundColor=*/QColor(), 
                                         /*textColor=*/QColor(), /*templateName=*/"1column", 
                                         /*createIn=*/currentElement.first);
                basket = Global::bnpView->currentBasket();
                basket->load();
                basketList << basket;
                newElement.first = basket;
                newElement.second = n.toElement();
                elements << newElement;
            }
        }
    }
    
    foreach (basket, basketList) {
        finishImport(basket);
    }
QString cDefinable::getNodeValue( const QDomElement &Tag )
{
	QString Value = QString();
	
	if( !Tag.hasChildNodes() )
		return "";
	else
	{
		QDomNode childNode = Tag.firstChild();
		while( !childNode.isNull() )
		{
			if( !childNode.isElement() )
			{
				if( childNode.isText() )
					Value += childNode.toText().data();
				childNode = childNode.nextSibling();
				continue;
			}
			QDomElement childTag = childNode.toElement();
			if( childTag.nodeName() == "random" )
			{
				if( childTag.attributes().contains("min") && childTag.attributes().contains("max") )
					Value += QString("%1").arg( RandomNum( childTag.attributeNode("min").nodeValue().toInt(), childTag.attributeNode("max").nodeValue().toInt() ) );
				else if( childTag.attributes().contains("valuelist") )
				{
					QStringList RandValues = QStringList::split(",", childTag.attributeNode("list").nodeValue());
					Value += RandValues[ RandomNum(0,RandValues.size()-1) ];
				}
				else if( childTag.attributes().contains( "list" ) )
				{
					Value += DefManager->getRandomListEntry( childTag.attribute( "list" ) );
				}
				else if( childTag.attributes().contains("dice") )
					Value += QString("%1").arg(rollDice(childTag.attributeNode("dice").nodeValue()));
				else
					Value += QString("0");
			}

			// Process the childnodes
			QDomNodeList childNodes = childTag.childNodes();

			for( int i = 0; i < childNodes.count(); i++ )
			{
				if( !childNodes.item( i ).isElement() )
					continue;

				Value += this->getNodeValue( childNodes.item( i ).toElement() );
			}
			childNode = childNode.nextSibling();
		}
	}
	return hex2dec( Value );
}
Example #16
0
bool Converter::convertParagraph( QTextCursor *cursor, const QDomElement &element, const QTextBlockFormat &parentFormat, bool merge )
{
  const QString styleName = element.attribute( QStringLiteral("style-name") );
  const StyleFormatProperty property = mStyleInformation->styleProperty( styleName );

  QTextBlockFormat blockFormat( parentFormat );
  QTextCharFormat textFormat;
  property.applyBlock( &blockFormat );
  property.applyText( &textFormat );

  if ( merge )
    cursor->mergeBlockFormat( blockFormat );
  else
    cursor->setBlockFormat( blockFormat );

  QDomNode child = element.firstChild();
  while ( !child.isNull() ) {
    if ( child.isElement() ) {
      const QDomElement childElement = child.toElement();
      if ( childElement.tagName() == QLatin1String( "span" ) ) {
        if ( !convertSpan( cursor, childElement, textFormat ) )
          return false;
      } else if ( childElement.tagName() == QLatin1String( "tab" ) ) {
        mCursor->insertText( QStringLiteral("    ") );
      } else if ( childElement.tagName() == QLatin1String( "s" ) ) {
        QString spaces;
        spaces.fill( QLatin1Char(' '), childElement.attribute( QStringLiteral("c") ).toInt() );
        mCursor->insertText( spaces );
      } else if ( childElement.tagName() == QLatin1String( "frame" ) ) {
        if ( !convertFrame( childElement ) )
          return false;
      } else if ( childElement.tagName() == QLatin1String( "a" ) ) {
        if ( !convertLink( cursor, childElement, textFormat ) )
          return false;
      } else if ( childElement.tagName() == QLatin1String( "annotation" ) ) {
        if ( !convertAnnotation( cursor, childElement ) )
          return false;
      }
    } else if ( child.isText() ) {
      const QDomText childText = child.toText();
      if ( !convertTextNode( cursor, childText, textFormat ) )
        return false;
    }

    child = child.nextSibling();
  }

  return true;
}
Example #17
0
void Select1::saveData()
{
  kDebug() <<"Select1::saveData()";
  kDebug() << ref().toString();
  kDebug() <<"Context:" << context().nodeName();
  Reference::Segment s;
  if( ref().segments().size() > 0 )
    s = ref().segments().last();

  QString txt;
  if( mProperties->appearance == Full ) {
    for( int i = 0; i < mRadioButtons.size() && i < mValues.size(); ++i ) {
      if( mRadioButtons[i]->isChecked() ) {
        txt = mValues[ i ];
        break;
      }
    }
  } else if( mProperties->appearance == Compact ) {
    if( mListWidget->currentRow() < mValues.size() )
      txt = mValues[ mListWidget->currentRow() ];
  } else { 
    if( mComboBox->currentIndex() < mValues.size() )
      txt = mValues[ mComboBox->currentIndex() ];
  }

  if ( s.isAttribute() ) {
    context().setAttribute( s.name(), txt );
  } else {
    QDomElement e = ref().applyElement( context() );
    if ( e.isNull() ) {
      e = createElement( ref() );
    }
    QDomNode n = e.firstChild();
    if( n.isNull() ) {
      n = mManager->document().createElement( txt );
      e.appendChild( n );
    }
    else {
      if( n.isText() ) {
        QDomText t = n.toText();
        t.setData( txt );
      } else if( n.isElement() ){
        n.toElement().setTagName( txt );
      }
    }
  }
}
Example #18
0
void output(QDomNode node)
{
  QDomNode next;
  if (node.nodeName()=="li") std::cout << "\n* ";
  if (node.nodeName()=="h1") std::cout << "\n= ";
  if (node.nodeName()=="h2") std::cout << "\n== ";
  if (node.nodeName()=="p") std::cout << "\n\n";
  if (node.nodeName()=="br") std::cout << "\n";
  if (node.isText()) std::cout << QString(node.nodeValue().toUtf8()).toStdString();
  if (node.hasChildNodes()) 
  {
    for (int i=0; i<=node.childNodes().count(); ++i) output(node.childNodes().at(i));
  }
  if (node.nodeName()=="p") std::cout << "\n\n";
  if (node.nodeName()=="h1") std::cout << " =";
  if (node.nodeName()=="h2") std::cout << " ==";
}
Example #19
0
bool Converter::convertSpan(QTextCursor *cursor, const QDomElement &element, const QTextCharFormat &format)
{
    const QString styleName = element.attribute("style-name");
    const StyleFormatProperty property = m_StyleInformation->styleProperty(styleName);

    QTextCharFormat textFormat(format);
    property.applyText(&textFormat);

    QDomNode child = element.firstChild();
    while (!child.isNull())
    {
        //// search <text:s/> 
        if (child.isText())
        {
            const QDomText childText = child.toText();
            if (!convertTextNode(cursor, childText, textFormat))
                return false;
        }
        else if (child.isElement())
        {
            const QDomElement childElement = child.toElement();
            if (childElement.tagName() == QLatin1String("tab"))
            {
                cursor->insertText("\t");
            }
            else if (childElement.tagName() == QLatin1String("s"))
            {
                QString spaces;
                spaces.fill(' ', childElement.attribute("c").toInt());
                cursor->insertText(spaces);
            }
            else if (childElement.tagName() == QLatin1String("frame"))
            {
                const int xpos = cursor->position();
                m_Cursor->setPosition(xpos, QTextCursor::MoveAnchor);
                if (!convertFrame(childElement))
                {
                    return false;
                }
            }
        }
        child = child.nextSibling();
    }

    return true;
}
Example #20
0
QString SkinContext::nodeToString(const QDomNode& node) const {
    QStringList result;
    QDomNode child = node.firstChild();
    while (!child.isNull()) {
        if (child.isElement()) {
            if (child.nodeName() == "Variable") {
                result.append(variableNodeToText(child.toElement()));
            } else {
                qDebug() << "Unhandled tag in node:" << child.nodeName();
            }
        } else if (child.isText()) {
            result.append(child.nodeValue());
        }
        // Ignore all other node types.
        child = child.nextSibling();
    }
    return result.join("");
}
Example #21
0
bool TextRegExp::load( QDomElement top, const QString& /*version*/)
{
    Q_ASSERT( top.tagName() == QString::fromLocal8Bit( "Text" ) );
    if ( top.hasChildNodes() ) {
        QDomNode child = top.firstChild();
        if ( ! child.isText() ) {
            KMessageBox::sorry( 0, i18n("<p>Element <b>Text</b> did not contain any textual data.</p>"),
                                i18n("Error While Loading From XML File") ) ;
            return false;
        }
        QDomText txtNode = child.toText();
        _text = txtNode.data();
    } else {
        _text = QString::fromLatin1( "" );
    }

    return true;
}
Example #22
0
bool Converter::convertSpan( QTextCursor *cursor, const QDomElement &element, const QTextCharFormat &format )
{
  const QString styleName = element.attribute( QStringLiteral("style-name") );
  const StyleFormatProperty property = mStyleInformation->styleProperty( styleName );

  QTextCharFormat textFormat( format );
  property.applyText( &textFormat );

  QDomNode child = element.firstChild();
  while ( !child.isNull() ) {
    if ( child.isText() ) {
      const QDomText childText = child.toText();
      if ( !convertTextNode( cursor, childText, textFormat ) )
        return false;
    }

    child = child.nextSibling();
  }

  return true;
}
Example #23
0
QMultiMap<QString, QVariantMap>
ServiceDefinition::queryResult(const QString &method,
                               const QString &data) const {
  // QVariantMap rv;

  QHash<QString, PrivateResultQuery> result = d->queryForMethod(method);
  QStringList queries = result.keys();

  QMultiMap<QString, QVariantMap> tagData;

  uint docType = d->documentType(method);

  qDebug() << Q_FUNC_INFO << "Doc Type :" << (docType);

  if (docType == 0) {
    QDomDocument dataRoot;
    if (dataRoot.setContent(data)) {
      Q_FOREACH(const QString & keyString, queries) {
        QDomNodeList filteredNodeList =
            dataRoot.elementsByTagName(result[keyString].tagName);

        for (int i = 0; i < filteredNodeList.count(); i++) {
          QDomNode dataNode = filteredNodeList.at(i);
          QDomNamedNodeMap dataNodeAttributes = dataNode.attributes();
          QVariantMap attributeData;

          Q_FOREACH(const QString & attrString, result[keyString].attributes) {
            attributeData[attrString] =
                dataNodeAttributes.namedItem(attrString).nodeValue();
          }
          if (dataNode.isText()) {
            QVariant textValue = d->getTextValueFromNode(dataNode);
            attributeData["NodeValue"] = textValue;
          } else {
            attributeData["NodeValue"] = QVariant();
          }

          tagData.insert(result[keyString].identifier, attributeData);
        }
      }
Example #24
0
/**
 * \en
 * Deletes tags from \a node
 * \_en
 * \ru
 * Удаляет рекурсивно теги из \a node.
 * \_ru
 * \param node - \en context \_en \ru узел из которого нужно удалить теги \_ru
 * \param section - \ru true, если надо удалить тег секции \_ru
 */
void
aMSOTemplate::clearTags(QDomNode node, bool section )
{
	if(node.isNull()) return;
	
	QDomNode n = node.lastChild();
	while( !n.isNull() )
	{	
		if(n.isText())
		{
			QString str = n.nodeValue();
			QRegExp re;
			if(section)
			{
				re.setPattern(QString("%1.*%2").arg(open_token_section).arg(close_token_section));
			}
			else
			{
				re.setPattern(QString("%1.*%2").arg(open_token).arg(close_token));
			}
			re.setMinimal(true);
			int pos = re.search(str,0);
		
			while(pos != -1)
			{
				str = str.remove(re);
				pos = re.search(str,0);
			}
			n.setNodeValue(str);			
		}
		else
		{
			clearTags(n,section);
		}
		n = n.previousSibling();
	}	
}
Example #25
0
Package *Package::parse(QDomElement *e, QString *err, bool validate)
{
    Package* p = new Package("test", "test");
    p->name = e->attribute("name");
    if (validate) {
        *err = WPMUtils::validateFullPackageName(p->name);
        if (!err->isEmpty()) {
            err->prepend(QObject::tr("Error in the attribute 'name' in <package>: "));
        }
    }

    p->title = XMLUtils::getTagContent(*e, "title");
    p->url = XMLUtils::getTagContent(*e, "url");
    p->description = XMLUtils::getTagContent(*e, "description");
    p->license = XMLUtils::getTagContent(*e, "license");

    QDomNodeList list = e->elementsByTagName("category");
    if (err->isEmpty()) {
        for (int i = 0; i < list.count(); i++) {
            QDomElement ch = list.at(i).toElement();
            QDomNode txt = ch.firstChild();
            if (txt.isText()) {
                QString v = txt.nodeValue().trimmed();
                p->categories.append(v);

                if (validate && err->isEmpty()) {
                    if (v.isEmpty()) {
                        *err = QObject::tr("Empty category");
                        break;
                    }
                }
            }
        }
    }

    if (err->isEmpty()) {
        list = e->elementsByTagName("link");
        for (int i = 0; i < list.count(); i++) {
            QDomElement ch = list.at(i).toElement();
            QString rel = ch.attribute("rel").trimmed();
            QString href = ch.attribute("href").trimmed();
            p->links.insert(rel, href);

            if (validate) {
                if (rel.isEmpty()) {
                    *err = QObject::tr("Empty attribute 'rel' in <link>");
                    break;
                }

                if (!Package::isValidURL(href)) {
                    *err = QObject::tr("Empty attribute 'href' in <link>");
                    break;
                }
            }
        }
    }

    if (err->isEmpty()) {
        if (p->getIcon().isEmpty()) {
            p->setIcon(XMLUtils::getTagContent(*e, "icon"));
        }
    }

    if (validate && err->isEmpty()) {
        if (!p->getIcon().isEmpty()) {
            if (!Package::isValidURL(p->getIcon())) {
                *err = QObject::tr("Empty icon URL");
            }
        }
    }

    if (err->isEmpty())
        return p;
    else {
        delete p;
        return 0;
    }
}
Example #26
0
//Fonction qui traite les <span> (styles internes aux paragraphes)
bool OpenDocument::traite_span(QTextCharFormat format, QTextCursor &curseur, QDomElement e, bool puces, bool tableau){

    SettingsManager settings;
    ErrorManager instance_erreur;
    QTextCharFormat format_span;
    if(e.tagName() == "text:span"){
        QString nom_format = e.attribute("text:style-name");
        format_span = cree_bloc_format(nom_format);
        //On merge le format
        format.merge(format_span);
        if(!format.hasProperty(QTextFormat::FontPointSize)){
            format.setFontPointSize(settings.getSettings(Taille).toInt());
        }
    }
    else{
        instance_erreur.Erreur_msg(tr("ODT : <span> invalide"), QMessageBox::Ignore);
    }

    //Maintenant on lit les <span>
    QDomNode enfants = e.firstChild();

    while(!enfants.isNull()){
        QDomNode sous_enfants = enfants.firstChild();

        //Détection d'éventuels sous-nœuds
        if(!sous_enfants.isNull() && sous_enfants.isElement()){
            //Si c'est une note, on se défausse
            if(sous_enfants.toElement().tagName() == "text:note-citation"){
                //On ne fait rien, les notes de bas de page ne sont pas encore gérées.
            }
            else{
                //Quoi que ce soit, ce n'est pas un <p>, on le rebalance à la fonction
                traite_span(format, curseur, e);
            }
        }

        //Type d'élément
        if(enfants.isElement()){
            QDomElement elem = enfants.toElement();

            if(elem.tagName() == "text:line-break"){
                curseur.insertText(QString(QChar::LineSeparator));
            }
            else if(elem.tagName() == "text:span"){
                traite_span(format, curseur, e, puces, tableau);
            }
            else if(elem.tagName() == "draw:frame"){

            }
            else if(elem.tagName() == "text:s"){
                curseur.insertText(QString(" "));
            }
            else if(elem.tagName() == "text:a"){
                traite_lien(curseur, elem, format);
            }
            else if(elem.tagName() == "text:tab"){
                curseur.insertText(QString("    "));
            }
            else{
                instance_erreur.Erreur_msg(tr("ODT : type de <span> non détecté"), QMessageBox::Ignore);
            }
        }
        else if(enfants.isText()){
            //On gére le texte
            QStringList contenu = enfants.nodeValue().split("\n");
            for(int i=0; i<contenu.size(); i++){
                if(puces){
                    //On récupère le style par défaut
                    QTextDocument *temp = new QTextDocument;
                    QTextCursor curseur2(temp);
                    curseur2.insertText(contenu.at(i), format);
                    contenu_puce.append(nettoye_code(temp->toHtml()));
                    delete temp;
                }
                else if(tableau){
                    QTextDocument *temp = new QTextDocument;
                    QTextCursor curseur2(temp);
                    curseur2.insertText(contenu.at(i), format);
                    case_tableau.append(nettoye_code(temp->toHtml()));
                }
                else{
                    curseur.insertText(contenu.at(i), format);
                }
            }
        }
        enfants = enfants.nextSibling();
    }
    return true;
}
void ReadAndWriteXML::parseEntry(const QDomElement &element, QTreeWidgetItem *parent, int parentLevel)
{
 //   item->setText(0, element.attribute("term"));
    QDomNode node = element.firstChild();
    while (!node.isNull()) {
        //qDebug() << "DomParser::parseEntry  node " << node.toElement().tagName();
    //    qDebug() << "DomParser::parseEntry  parsing node " << node.nodeName();
         if (node.isElement()) {
            //qDebug() << "DomParser::parseEntry "<< node.nodeName()<< " is element ";
            QTreeWidgetItem *childitem=new QTreeWidgetItem(parent, QStringList(QString("Type: %1").arg(node.nodeName())));
            parseEntry(node.toElement(), childitem,++parentLevel);
            QString _attr="";
            if (node.hasAttributes()) {
               childitem=new QTreeWidgetItem(childitem, QStringList(QString("Attributes node %1").arg(node.nodeName())));
               parseAttribute(node.attributes(), childitem, parentLevel);
            }
            node = node.nextSibling();
            continue;
         }
         if (node.isCDATASection()) {
             //qDebug() << "DomParser::parseEntry "<< node.nodeName()<< " is CDATASection --" << node.toText().data() << "--";
             new QTreeWidgetItem(parent, QStringList(QString("Type: %1 Value: %2").arg(node.nodeName(),node.toText().data())));
             node = node.nextSibling();
             continue;
         }
         if (node.isComment()) {
            //qDebug() << "DomParser::parseEntry "<< node.nodeName()<< " is comment --" << node.toText().data() << "--";
            new QTreeWidgetItem(parent, QStringList(QString("Type: %1 Value: %2").arg(node.nodeName(),node.toText().data())));
            node = node.nextSibling();
            continue;
         }
         if (node.isText()) {
            //qDebug() << "DomParser::parseEntry "<< node.nodeName()<< " text --" << node.toText().data() << "--";
            new QTreeWidgetItem(parent, QStringList(QString("Type: %1 Value: %2").arg(node.nodeName(),node.toText().data())));
            node = node.nextSibling();
            continue;
         }
         if (node.isDocument()) {
            //qDebug() << "DomParser::parseEntry "<< node.nodeName()<< " is document ";
            QTreeWidgetItem *childitem=new QTreeWidgetItem(parent, QStringList(QString("Type: %1").arg(node.nodeName())));
            parseEntry(node.toElement(), childitem,++parentLevel);
            node = node.nextSibling();
            continue;
         }
         if (node.isDocumentType()) {
            qDebug() << "DomParser::parseEntry "<< node.nodeName()<< " is  document type";
            QTreeWidgetItem *childitem=new QTreeWidgetItem(parent, QStringList(QString("Type: %1").arg(node.nodeName())));
            parseEntry(node.toElement(), childitem,++parentLevel);
            node = node.nextSibling();
            continue;
         }
         if (node.isDocumentFragment()) {
            qDebug() << "DomParser::parseEntry "<< node.nodeName()<< " is  document fragment";
            QTreeWidgetItem *childitem=new QTreeWidgetItem(parent, QStringList(QString("Type: %1").arg(node.nodeName())));
            parseEntry(node.toElement(), childitem,++parentLevel);
            node = node.nextSibling();
            continue;
         }
         if (node.isEntity() || node.isEntityReference () || node.isNotation () || node.isProcessingInstruction ()) {
             qDebug() << "DomParser::parseEntry "<< node.nodeName()<< " is  not supported";
             node = node.nextSibling();
             continue;
         }

        node = node.nextSibling();
    }
}
    bool operator()(QDomNode node) {
	if(!node.hasChildNodes() && !node.hasAttributes() && !node.isText()) {
	    return true;
	}
	return false;
    }
Example #29
0
void PMRaw::readAttributes( const PMXMLHelper& h )
{
   QDomNode e = h.element( ).firstChild( );
   if( e.isText( ) )
      m_code = e.toText( ).data( );
}
Example #30
0
//Lecture des paragraphes
bool OpenDocument::contenu_paragraphe(QDomElement e, QTextCursor &curseur, bool puces, bool h_item, bool tableau){
    ErrorManager instance_erreur;
    p_current++;
    case_tableau = "";
    //On change la QProgressBar
    //chargement->

    QString nom_style = e.attribute("text:style-name", "default");
    QTextCharFormat format = cree_bloc_format(nom_style);

    //On récupère le format de bloc
    QTextBlockFormat format_bloc = cree_bloc_format2(nom_style);
    //On ajoute un marginTop de 5 pour plus de lisibilité
    format_bloc.setTopMargin(2);

    //Style spécifique aux puces
    if(puces || h_item){
        int id_style = -1;
        for(int i=0; i<styles.size(); i++){
            //On parcourt les styles
            if(id_style >= 0){
                break;
            }
            for(int j=0; j<styles.at(i).size(); j++){
                //On rentre dans le QMultiMap
                if(puces){
                    if(styles.at(i).value("style-puces") == nom_style){
                        id_style = i;
                        //On sort de la boucle
                        break;
                    }
                }
                else{
                    //Ce ne peut être que le "h_item" sinon la boucle ne se déclencherait pas
                    if(styles.at(i).value("style-h") == nom_style){
                        id_style = i;
                        //On se casse
                        break;
                    }
                }
            }
        }
        if(id_style != -1){
            //On merge le style
            format.merge(cree_bloc_format(styles.at(id_style).value("style-puces")));
        }
    }

    //On applique le format au curseur
    curseur.setCharFormat(format);
    if(!tableau){
        curseur.beginEditBlock();
    }
    curseur.setBlockCharFormat(format);
    curseur.setBlockFormat(format_bloc);

    if(puces){
        contenu_puce.append("<li>");
        //On vérifie la taille
        int taille = format.fontPointSize();
        if(taille == 0){
            //Il y a eu un bug lors de la sélection du style, on applique la taille par défaut
            format.setFontPointSize(12);
        }
    }

    //Maintenant on lit les <span>
    QDomNode enfants = e.firstChild();
    while(!enfants.isNull()){
        if(enfants.isElement()){
            QDomElement type = enfants.toElement();

            //On parcours le type d'élément
            if(type.tagName() == "text:span"){
                traite_span(format, curseur, type, puces, tableau);
            }
            else if(type.tagName() == "text:a"){ //Il s'agit d'un lien
                traite_lien(curseur, type, format);
            }
            else if(type.tagName() == "text:line-break"){

            }
            else if(type.tagName() == "text:s"){
                curseur.insertText(QString(" "));
            }
            else if(type.tagName() == "text:tab"){
                curseur.insertText(QString("    "));
            }
            else if(type.tagName() == "draw:frame"){
                QDomNode enfants_image = type.firstChild();
                QString style_image = type.attribute("draw:style-name");
                if(enfants_image.toElement().tagName() == "draw:image"){
                    if(!traite_image(curseur, enfants_image.toElement(), style_image)){
                        instance_erreur.Erreur_msg(tr("ODT : Erreur lors de la lecture des images (return false)"), QMessageBox::Ignore);
                    }
                }
            }
            else if(type.tagName() == "text:list"){
                if(!contenu_puces(type, curseur)){
                    instance_erreur.Erreur_msg(tr("ODT : Une erreur est survenue lors de la lecture d'une liste à puces; elle ne sera pas affichée"), QMessageBox::Warning);
                }
                else{
                    QTextCursor curseur(document);
                    curseur.movePosition(QTextCursor::End);
                    curseur.movePosition(QTextCursor::PreviousBlock);
                    curseur.insertHtml(contenu_puce);
                    contenu_puce = "";
                }
            }
            else if(type.tagName() == "text:soft-page-break"){

            }
            else{
                instance_erreur.Erreur_msg(tr("ODT: Type de contenu non supporté : %1").arg(type.tagName()), QMessageBox::Ignore);
            }
        }
        else if(enfants.isText()){
            //On gére le texte
            if(!puces && !tableau){
                curseur.insertText(enfants.nodeValue(), format);
            }
            else if(tableau){
               case_tableau.append(enfants.nodeValue());
            }
            else{
                //Insertion du contenu des puces si on est dans un "p"
                //On récupère le style par défaut
                QTextDocument *temp = new QTextDocument;
                QTextCursor curseur(temp);
                curseur.insertText(enfants.nodeValue(), format);
                contenu_puce.append(nettoye_code(temp->toHtml()));
                delete temp;
            }

        }
        else{
            instance_erreur.Erreur_msg(tr("ODT : type de données non supporté"), QMessageBox::Ignore);
        }
        enfants = enfants.nextSibling();
    }

    //On a fini la boucle OU il n'y avait pas de <span>

    //On récupère le contenu
    if(!puces && !tableau){
        curseur.insertText("\n");
    }
    if(puces){
        contenu_puce.append("</li>");
    }
    if(!tableau){
        curseur.endEditBlock();
    }
    if(tableau){
        ligne_tableau.append(case_tableau);
    }
    //std::cout << e.text().toStdString() << std::endl;
    return true;
}