void SapoRemoteOptionsMgr::setStatusAndMessage(const QString &show, const QString &status)
{
	if (!_remotelySavedXML.isNull() && (show != _remotelySavedShow || status != _remotelySavedStatus)) {
		_remotelySavedShow = show;
		_remotelySavedStatus = status;
		
		QDomElement presenceNode = _remotelySavedXML.firstChildElement("mod_presence");
		QDomElement oldStatusNode = presenceNode.firstChildElement("var_status");
		QDomElement oldShowNode = presenceNode.firstChildElement("var_show");
		
		QDomElement newShowNode = _client->doc()->createElement("var_show");
		QDomText newShowNodeContents = _client->doc()->createTextNode(show);
		newShowNode.appendChild(newShowNodeContents);
		
		presenceNode.replaceChild(newShowNode, oldShowNode);
		
		QDomElement newStatusNode = _client->doc()->createElement("var_status");
		QDomText newStatusNodeContents = _client->doc()->createTextNode(status);
		newStatusNode.appendChild(newStatusNodeContents);
		
		presenceNode.replaceChild(newStatusNode, oldStatusNode);
		
		
		setRemoteOptions(_remotelySavedXML);
	}
}
Exemplo n.º 2
0
void Bookmarks::updateDomElement(QTreeWidgetItem* item, int column)
{
    QDomElement element = m_domElementForItem.value(item);
    if (!element.isNull()) {
        if (column == 0) {
            QDomElement oldTitleElement = element.firstChildElement("title");
            QDomElement newTitleElement = m_domDocument.createElement("title");

            QDomText newTitleText = m_domDocument.createTextNode(item->text(0));
            newTitleElement.appendChild(newTitleText);

            element.replaceChild(newTitleElement, oldTitleElement);
        }
        else {
            if (element.tagName() == "bookmark") {
                QDomElement oldDescElement = element.firstChildElement("desc");
                QDomElement newDescElement = m_domDocument.createElement("desc");
                QDomText newDesc = m_domDocument.createTextNode(item->text(1));//setAttribute("href", item->text(1));
                newDescElement.appendChild(newDesc);
                element.replaceChild(newDescElement, oldDescElement);
                element.setAttribute("href", item->data(1, Qt::UserRole).toString());
            }
        }
    }
}
Exemplo n.º 3
0
bool XmlHelper::SetXmlNodeContent(const QString &tag_name, const QString &text)
{
    QDomElement root = doc_.documentElement();
    QDomNodeList node_list = root.elementsByTagName(tag_name);
    if (node_list.count() > 0)
    {
        QDomElement elems = node_list.at(0).toElement();
        QDomNode old_node = elems.firstChild();
        if (elems.firstChild().isText())
        {
            elems.firstChild().setNodeValue(text);
            QDomNode new_node = elems.firstChild();
            elems.replaceChild(new_node, old_node);
        }
        else
        {
//            elems.firstChild().setNodeValue(text);
//            QDomText text_node;
//            text_node.setNodeValue(text);
//            QDomNode new_node = elems.firstChild();
//            new_node.appendChild(text_node);
//            elems.replaceChild(new_node, old_node);

            QDomText text_node = doc_.createTextNode(text);
            node_list.at(0).appendChild(text_node);
        }

        return true;
    }

    return false;
}
Exemplo n.º 4
0
bool XmlHelper::SetChildNodeValue(const QString &parent_tag, const QString &child_tag, QString &text)
{
    QDomElement root = doc_.documentElement();
    QDomNodeList nodelist = root.elementsByTagName(parent_tag);

    if (nodelist.count() == 0)
    {
        return false;
    }

    QDomNodeList childs = nodelist.at(0).childNodes();
    for (int i = 0; i < childs.count(); i++)
    {
        QDomNode child = childs.at(i);

        if (child.nodeName() == child_tag)
        {
            QDomElement elems = child.toElement();
            if (elems.firstChild().isText())
            {
                elems.firstChild().setNodeValue(text);
            }
            else
            {
                QDomText text_node;
                text_node.setNodeValue(text);
                elems.replaceChild(text_node, elems.firstChild());
            }

            return true;
        }
    }

    return false;
}
Exemplo n.º 5
0
bool KOfficePlugin::writeTextNode(QDomDocument & doc,
				  QDomNode & parentNode,
				  const QString  &nodeName,
				  const QString  &value) const
{
  if (parentNode.toElement().isNull()){
    kdDebug(7034) << "Parent node is Null or not an Element, cannot write node "
		  << nodeName << endl;
    return false;
  }

  // If the node does not exist, we create it...
  if (parentNode.namedItem(nodeName).isNull())
    QDomNode ex = parentNode.appendChild(doc.createElement(nodeName));

  // Now, we are sure we have a node
  QDomElement nodeA = parentNode.namedItem(nodeName).toElement();

  // Ooops... existing node were not of the good type...
  if (nodeA.isNull()){
    kdDebug(7034) << "Wrong type of node " << nodeName << ", should be Element"
		  << endl;
    return false;
  }

  QDomText txtNode = doc.createTextNode(value);

  // If the node has already Text Child, we replace it.
  if (nodeA.firstChild().isNull())
    nodeA.appendChild(txtNode);
  else
    nodeA.replaceChild( txtNode, nodeA.firstChild());
  return true;
}
void QgsProjectFileTransform::transform1400to1500()
{
  //Adapt the XML description of the composer legend model to version 1.5
  if ( mDom.isNull() )
  {
    return;
  }
  //Add layer id to <VectorClassificationItem>
  QDomNodeList layerItemList = mDom.elementsByTagName( "LayerItem" );
  QDomElement currentLayerItemElem;
  QString currentLayerId;

  for ( int i = 0; i < layerItemList.size(); ++i )
  {
    currentLayerItemElem = layerItemList.at( i ).toElement();
    if ( currentLayerItemElem.isNull() )
    {
      continue;
    }
    currentLayerId = currentLayerItemElem.attribute( "layerId" );

    QDomNodeList vectorClassificationList = currentLayerItemElem.elementsByTagName( "VectorClassificationItem" );
    QDomElement currentClassificationElem;
    for ( int j = 0; j < vectorClassificationList.size(); ++j )
    {
      currentClassificationElem = vectorClassificationList.at( j ).toElement();
      if ( !currentClassificationElem.isNull() )
      {
        currentClassificationElem.setAttribute( "layerId", currentLayerId );
      }
    }

    //replace the text items with VectorClassification or RasterClassification items
    QDomNodeList textItemList = currentLayerItemElem.elementsByTagName( "TextItem" );
    QDomElement currentTextItem;

    for ( int j = 0; j < textItemList.size(); ++j )
    {
      currentTextItem = textItemList.at( j ).toElement();
      if ( currentTextItem.isNull() )
      {
        continue;
      }

      QDomElement classificationElement;
      if ( vectorClassificationList.size() > 0 ) //we guess it is a vector layer
      {
        classificationElement = mDom.createElement( "VectorClassificationItem" );
      }
      else
      {
        classificationElement = mDom.createElement( "RasterClassificationItem" );
      }

      classificationElement.setAttribute( "layerId", currentLayerId );
      classificationElement.setAttribute( "text", currentTextItem.attribute( "text" ) );
      currentLayerItemElem.replaceChild( classificationElement, currentTextItem );
    }
  }
}
Exemplo n.º 7
0
bool KOfficePlugin::writeInfo( const KFileMetaInfo& info) const
{
  bool no_errors = true;
  QDomDocument doc = getMetaDocument(info.path());
  QDomElement base = getBaseNode(doc).toElement();
  if (base.isNull())
    return false;
  for (int i = 0; Information[i]; i+=2)
    no_errors = no_errors &&
      writeTextNode(doc, base, Information[i],
		    info[DocumentInfo][Information[i]].value().toString());
  // If we need a meta:keywords container, we create it.
  if (base.namedItem(metakeywords).isNull())
    base.appendChild(doc.createElement(metakeywords));
  QDomNode metaKeyNode = base.namedItem(metakeywords);

  QDomNodeList childs = doc.elementsByTagName(metakeyword);
  for (int i = childs.length(); i >= 0; --i){
	  metaKeyNode.removeChild( childs.item(i) );
  }
  QStringList keywordList = QStringList::split(",", info[DocumentInfo][metakeyword].value().toString().stripWhiteSpace(), false);
  for ( QStringList::Iterator it = keywordList.begin(); it != keywordList.end(); ++it ) {
	QDomElement elem = doc.createElement(metakeyword);
	metaKeyNode.appendChild(elem);
	elem.appendChild(doc.createTextNode((*it).stripWhiteSpace()));
    }

  // Now, we store the user-defined data
  QDomNodeList theElements = base.elementsByTagName(metauserdef);
  for (uint i = 0; i < theElements.length(); i++)
    {
      QDomElement el = theElements.item(i).toElement();
      if (el.isNull()){
	kdDebug(7034) << metauserdef << " is not an Element" << endl;
	no_errors = false;
      }

      QString s = info[UserDefined][el.attribute(metaname)].value().toString();
      if (s != el.text()){
	QDomText txt = doc.createTextNode(s);
	if (!el.firstChild().isNull())
	  el.replaceChild(txt, el.firstChild());
	else
	  el.appendChild(txt);
      }
    }

  if (!no_errors){
    kdDebug(7034) << "Errors were found while building " << metafile
	     	  << " for file " << info.path() << endl;
    // It is safer to avoid to manipulate meta.xml if errors, we abort.
    return false;
  }
  writeMetaData(info.path(), doc);
  return true;
}
Exemplo n.º 8
0
void writeJob::parsePropertyHideElement(QDomElement property,bool checked)
{
    QDomElement oldHideEle=property.firstChildElement("hide");

    QDomElement newHideEle = doc.createElement("hide");
//    newHideEle.setAttribute("name",oldDisplayType.attribute("name"));  //保留控件类型
    if(checked==true)
    {
        QDomText newHideTxt = doc.createTextNode("NO");
        newHideEle.appendChild(newHideTxt);
        property.replaceChild(newHideEle,oldHideEle);
    }
    if(checked==false)
    {
        QDomText newHideTxt = doc.createTextNode("YES");
        newHideEle.appendChild(newHideTxt);
        property.replaceChild(newHideEle,oldHideEle);
    }
}
Exemplo n.º 9
0
void QgsProjectFileTransform::transform0100to0110()
{
  if ( ! mDom.isNull() )
  {
#ifndef QT_NO_PRINTER
    //Change 'outlinewidth' in QgsSymbol
    QPrinter myPrinter( QPrinter::ScreenResolution );
    int screenDpi = myPrinter.resolution();
    double widthScaleFactor = 25.4 / screenDpi;

    QDomNodeList outlineWidthList = mDom.elementsByTagName( QStringLiteral( "outlinewidth" ) );
    for ( int i = 0; i < outlineWidthList.size(); ++i )
    {
      //calculate new width
      QDomElement currentOutlineElem = outlineWidthList.at( i ).toElement();
      double outlineWidth = currentOutlineElem.text().toDouble();
      outlineWidth *= widthScaleFactor;

      //replace old text node
      QDomNode outlineTextNode = currentOutlineElem.firstChild();
      QDomText newOutlineText = mDom.createTextNode( QString::number( outlineWidth ) );
      currentOutlineElem.replaceChild( newOutlineText, outlineTextNode );

    }

    //Change 'pointsize' in QgsSymbol
    QDomNodeList pointSizeList = mDom.elementsByTagName( QStringLiteral( "pointsize" ) );
    for ( int i = 0; i < pointSizeList.size(); ++i )
    {
      //calculate new size
      QDomElement currentPointSizeElem = pointSizeList.at( i ).toElement();
      double pointSize = currentPointSizeElem.text().toDouble();
      pointSize *= widthScaleFactor;

      //replace old text node
      QDomNode pointSizeTextNode = currentPointSizeElem.firstChild();
      QDomText newPointSizeText = mDom.createTextNode( QString::number( static_cast< int >( pointSize ) ) );
      currentPointSizeElem.replaceChild( newPointSizeText, pointSizeTextNode );
    }
#endif
  }
}
// Convenience to create a Dom Widget from widget box xml code.
DomUI *QDesignerWidgetBox::xmlToUi(const QString &name, const QString &xml, bool insertFakeTopLevel, QString *errorMessage)
{
    QDomDocument doc;
    int errorLine, errorColumn;
    if (!doc.setContent(xml, errorMessage, &errorLine, &errorColumn)) {
        *errorMessage = QObject::tr("A parse error occurred at line %1, column %2 of the XML code specified for the widget %3: %4\n%5").
                                 arg(errorLine).arg(errorColumn).arg(name).arg(*errorMessage).arg(xml);
        return 0;
    }

    if (!doc.hasChildNodes()) {
        *errorMessage = QObject::tr("The XML code specified for the widget %1 does not contain any widget elements.\n%2").arg(name).arg(xml);
        return 0;
    }

    QDomElement rootElement = doc.firstChildElement();
    const QString rootNode = rootElement.nodeName();

    const QString widgetTag = QLatin1String("widget");
    if (rootNode == widgetTag) { // 4.3 legacy ,wrap into DomUI
        DomUI *rc = new DomUI;
        DomWidget *widget = new DomWidget;
        widget->read(rootElement);
        if (insertFakeTopLevel)  {
            DomWidget *fakeTopLevel = new DomWidget;
            QList<DomWidget *> children;
            children.push_back(widget);
            fakeTopLevel->setElementWidget(children);
            rc->setElementWidget(fakeTopLevel);
        } else {
            rc->setElementWidget(widget);
        }
        return rc;
    }

    if (rootNode == QLatin1String("ui")) { // 4.4
        QDomElement widgetChild = rootElement.firstChildElement(widgetTag);
        if (widgetChild.isNull()) {
            *errorMessage = QObject::tr("The XML code specified for the widget %1 does not contain valid widget element\n%2").arg(name).arg(xml);
            return 0;
        }
        if (insertFakeTopLevel)  {
            QDomElement fakeTopLevel = doc.createElement(widgetTag);
            rootElement.replaceChild(fakeTopLevel, widgetChild);
            fakeTopLevel.appendChild(widgetChild);
        }
        DomUI *rc = new DomUI;
        rc->read(rootElement);
        return rc;
    }

    *errorMessage = QObject::tr("The XML code specified for the widget %1 contains an invalid root element %2.\n%3").arg(name).arg(rootNode).arg(xml);
    return 0;
}
Exemplo n.º 11
0
bool XmlHelper::SetXmlNodeContent(const QString &tag_name, const QString &text)
{
    if (!LoadXmlFile())
    {
        return false;
    }

    QDomElement root = doc_.documentElement();
    QDomNodeList node_list = root.elementsByTagName(tag_name);
    if (node_list.count() > 0)
    {
        QDomElement elems = node_list.at(0).toElement();
        QDomNode old_node = elems.firstChild();
        if (elems.firstChild().isText())
        {
            elems.firstChild().setNodeValue(text);
            QDomNode new_node = elems.firstChild();
            elems.replaceChild(new_node, old_node);
        }
        else
        {
            elems.firstChild().setNodeValue(text);
            QDomText text_node;
            text_node.setNodeValue(text);
            QDomNode new_node = elems.firstChild();
            new_node.appendChild(text_node);
            elems.replaceChild(new_node, old_node);
        }
        QFile file(file_name_);
        if (!file.open(QIODevice::WriteOnly))
        {
            return false;
        }
        QTextStream out(&file);
        doc_.save(out, 4);
        file.close();
        return true;
    }

    return false;
}
Exemplo n.º 12
0
bool plotsDialog::saveChanges()
{
#ifdef Q_OS_WIN32
    QFile ofile(globalpara.caseName),file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
    QDir dir = qApp->applicationDirPath();
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    QString bundleDir(dir.absolutePath());
    QFile ofile(globalpara.caseName),file(bundleDir+"/plotTemp.xml");
#endif
    QDomDocument odoc,doc;
    QDomElement oroot;
    QTextStream stream;
    stream.setDevice(&ofile);
    if(!ofile.open(QIODevice::ReadWrite|QIODevice::Text))
    {
        globalpara.reportError("Fail to open case file to update plot data.",this);
        return false;
    }
    else if(!odoc.setContent(&ofile))
    {
        globalpara.reportError("Fail to load xml document from case file to update plot data.",this);
        return false;
    }
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        globalpara.reportError("Fail to open plot temp file to update plot data.",this);
        return false;
    }
    else if(!doc.setContent(&file))
    {
        globalpara.reportError("Fail to load xml document from plot temp file to update plot data..",this);
        return false;
    }
    else
    {
        QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
        QDomNode copiedPlot = plotData.cloneNode(true);
        oroot = odoc.elementsByTagName("root").at(0).toElement();
        oroot.replaceChild(copiedPlot,odoc.elementsByTagName("plotData").at(0));

        ofile.resize(0);
        odoc.save(stream,4);
        file.close();
        ofile.close();
        stream.flush();
        return true;
    }
}
Exemplo n.º 13
0
void
XmlHeaderFunctions::replaceInHeader(QString pvlFilename,
                                    QString attname, QString value)
{
    QDomDocument doc;
    QFile f(pvlFilename);
    if (f.open(QIODevice::ReadOnly))
    {
        doc.setContent(&f);
        f.close();
    }

    int replace = -1;
    QDomElement topElement = doc.documentElement();
    QDomNodeList dlist = topElement.childNodes();
    for(int i=0; i<dlist.count(); i++)
    {
        if (dlist.at(i).nodeName() == attname)
        {
            replace = i;
            break;
        }
    }

    if (replace > -1)
    {
        QDomElement de = doc.createElement(attname);
        QDomText tn = doc.createTextNode(value);
        de.appendChild(tn);
        topElement.replaceChild(de, dlist.at(replace));
    }
    else
    {
        QDomElement de = doc.createElement(attname);
        QDomText tn = doc.createTextNode(value);
        de.appendChild(tn);
        topElement.appendChild(de);
    }

    QFile fout(pvlFilename);
    if (fout.open(QIODevice::WriteOnly))
    {
        QTextStream out(&fout);
        doc.save(out, 2);
        fout.close();
    }
    else
    {
        QMessageBox::information(0, "", QString("Cannot write to "+pvlFilename));
    }
}
Exemplo n.º 14
0
void OpenModelica::setInputParametersXml(QDomDocument &doc,MOParameters *parameters)
{
    QDomElement xfmi = doc.firstChildElement("fmiModelDescription");
    QDomElement oldxfmi = xfmi;

    QDomElement xExp = xfmi.firstChildElement("DefaultExperiment");
    QDomElement oldxExp = xExp;


    double starttime = parameters->value(OpenModelicaParameters::str(OpenModelicaParameters::STARTTIME),0).toDouble();
    double stoptime = parameters->value(OpenModelicaParameters::str(OpenModelicaParameters::STOPTIME),1).toDouble();
    int nbIntervals = parameters->value(OpenModelicaParameters::str(OpenModelicaParameters::NBINTERVALS),2).toInt();
    double stepSize = (stoptime-starttime)/nbIntervals;


    MOParameter * curParam;
    MOParameterListed* curParamListed;
    for(int i=0;i<parameters->size();i++)
    {
        curParam = parameters->at(i);

        if(!curParam->name().contains(" ")) // remove old parameters, temporary
        {
            if(curParam->name()==OpenModelicaParameters::str(OpenModelicaParameters::SOLVER))
            {
                curParamListed = dynamic_cast<MOParameterListed*>(curParam);
                xExp.setAttribute(curParamListed->name(),curParamListed->strValue());
            }
            else if(curParam->name()==OpenModelicaParameters::str(OpenModelicaParameters::OUTPUT))
            {
                curParamListed = dynamic_cast<MOParameterListed*>(curParam);
                xExp.setAttribute(curParamListed->name(),curParamListed->strValue());
            }
            else if (curParam->name()==OpenModelicaParameters::str(OpenModelicaParameters::NBINTERVALS))
            {
                xExp.setAttribute("stepSize",QString::number(stepSize));
            }
            else
            {
                xExp.setAttribute(curParam->name(),curParam->value().toString());
            }
        }
    }

    // update xfmi with new vars
    xfmi.replaceChild(xExp,oldxExp);
    doc.replaceChild(xfmi,oldxfmi);
}
Exemplo n.º 15
0
void QQMlDom::addependTextById(QDomDocument nDocument, QString element, QString text)
{

    QDomElement root = nDocument.documentElement();
    QDomNodeList nList = root.elementsByTagName(element);
    QDomNode nNode = nList.at(0);
    QDomElement nodeTag =  nNode.toElement();

    // create a new node with a QDomText child
    QDomElement newNodeTag = nDocument.createElement(QString(element));
    QDomText newNodeText = nDocument.createTextNode(QString(text));
    newNodeTag.appendChild(newNodeText);

    // replace existing node with new node
    root.replaceChild(newNodeTag, nodeTag);

}
Exemplo n.º 16
0
void writeJob::parsePropertyHideElement(QDomElement property, QString text, QString /*id*/)
{
    /// 先要从写上入手,写入id
    QDomElement oldDisplayType=property.firstChildElement("displaytype");
    /// 需要根据这个类型来判断
    qDebug()<<"changed widget type::"<<oldDisplayType.attribute("name");
    QString type=oldDisplayType.attribute("name");
    if(type=="lineedit")
    {
        QDomElement newDisplayType = doc.createElement("displaytype");
        newDisplayType.setAttribute("name",oldDisplayType.attribute("name"));  //保留控件类型
        newDisplayType.setAttribute("id",oldDisplayType.attribute("id"));  //保留控件类型
        QDomText newDisplayText = doc.createTextNode(text);
        newDisplayType.appendChild(newDisplayText);
        property.replaceChild(newDisplayType,oldDisplayType);
    }
}
Exemplo n.º 17
0
void XbelTree::updateDomElement(QTreeWidgetItem *item, int column)
{
    QDomElement element = domElementForItem.value(item);
    if (!element.isNull()) {
        if (column == 0) {
            QDomElement oldTitleElement = element.firstChildElement("title");
            QDomElement newTitleElement = domDocument.createElement("title");

            QDomText newTitleText = domDocument.createTextNode(item->text(0));
            newTitleElement.appendChild(newTitleText);

            element.replaceChild(newTitleElement, oldTitleElement);
        } else {
            if (element.tagName() == "bookmark")
                element.setAttribute("href", item->text(1));
        }
    }
}
Exemplo n.º 18
0
void ParserAlbum::writeCurrentInAlbum(int _current)
{
    m_pFile->close();
    if(!m_pFile->open(QIODevice::WriteOnly))
    {
        return;
    }
    QDomElement element = m_pDoc->documentElement();
    QDomElement node  = element.firstChild().toElement();
    while(node.tagName() != "current")
    {
        node = node.nextSibling().toElement();
    }
    QDomElement CurrentElement = createElement("current",QString::number(_current));
    element.replaceChild(CurrentElement,node);

    if(m_pFile->isOpen())
    {
        QTextStream(m_pFile) << m_pDoc->toString();
        m_pFile->close();
    }
}
Exemplo n.º 19
0
QgsMapLayer* QgsProjectParser::createLayerFromElement( const QDomElement& elem ) const
{
  if ( elem.isNull() || !mXMLDoc )
  {
    return 0;
  }

  QString uri;
  QString absoluteUri;
  QDomElement dataSourceElem = elem.firstChildElement( "datasource" );
  if ( !dataSourceElem.isNull() )
  {
    //convert relative pathes to absolute ones if necessary
    uri = dataSourceElem.text();
    absoluteUri = convertToAbsolutePath( uri );
    if ( uri != absoluteUri )
    {
      QDomText absoluteTextNode = mXMLDoc->createTextNode( absoluteUri );
      dataSourceElem.replaceChild( absoluteTextNode, dataSourceElem.firstChild() );
    }
  }

  QString id = layerId( elem );
  QgsMapLayer* layer = QgsMSLayerCache::instance()->searchLayer( absoluteUri, id );
  if ( layer )
  {
    //reading symbology every time is necessary because it could have been changed by a user SLD based request
    QString error;
    layer->readSymbology( elem, error );
    return layer;
  }

  QString type = elem.attribute( "type" );
  if ( type == "vector" )
  {
    layer = new QgsVectorLayer();
  }
  else if ( type == "raster" )
  {
    layer = new QgsRasterLayer();
  }
  else if ( elem.attribute( "embedded" ) == "1" ) //layer is embedded from another project file
  {
    QString project = convertToAbsolutePath( elem.attribute( "project" ) );
    QgsDebugMsg( QString( "Project path: %1" ).arg( project ) );
    QgsProjectParser* otherConfig = dynamic_cast<QgsProjectParser*>( QgsConfigCache::instance()->searchConfiguration( project ) );
    if ( !otherConfig )
    {
      return 0;
    }

    QMap< QString, QDomElement > layerMap = otherConfig->projectLayerElementsById();
    QMap< QString, QDomElement >::const_iterator layerIt = layerMap.find( elem.attribute( "id" ) );
    if ( layerIt == layerMap.constEnd() )
    {
      return 0;
    }
    return otherConfig->createLayerFromElement( layerIt.value() );
  }

  if ( layer )
  {
    layer->readXML( const_cast<QDomElement&>( elem ) ); //should be changed to const in QgsMapLayer
    layer->setLayerName( layerName( elem ) );
    QgsMSLayerCache::instance()->insertLayer( absoluteUri, id, layer );
  }
  return layer;
}
void QgsProjectFileTransform::transform0110to1000()
{
  if ( ! mDom.isNull() )
  {
    QDomNodeList layerList = mDom.elementsByTagName( "maplayer" );
    for ( int i = 0; i < layerList.size(); ++i )
    {
      QDomElement layerElem = layerList.at( i ).toElement();
      QString typeString = layerElem.attribute( "type" );
      if ( typeString != "vector" )
      {
        continue;
      }

      //datasource
      QDomNode dataSourceNode = layerElem.namedItem( "datasource" );
      if ( dataSourceNode.isNull() )
      {
        return;
      }
      QString dataSource = dataSourceNode.toElement().text();

      //provider key
      QDomNode providerNode = layerElem.namedItem( "provider" );
      if ( providerNode.isNull() )
      {
        return;
      }
      QString providerKey = providerNode.toElement().text();

      //create the layer to get the provider for int->fieldName conversion
      QgsVectorLayer* theLayer = new QgsVectorLayer( dataSource, "", providerKey, false );
      if ( !theLayer->isValid() )
      {
        delete theLayer;
        return;
      }

      QgsVectorDataProvider* theProvider = theLayer->dataProvider();
      if ( !theProvider )
      {
        return;
      }
      QgsFields theFields = theProvider->fields();

      //read classificationfield
      QDomNodeList classificationFieldList = layerElem.elementsByTagName( "classificationfield" );
      for ( int j = 0; j < classificationFieldList.size(); ++j )
      {
        QDomElement classificationFieldElem = classificationFieldList.at( j ).toElement();
        int fieldNumber = classificationFieldElem.text().toInt();
        if ( fieldNumber >= 0 && fieldNumber < theFields.count() )
        {
          QDomText fieldName = mDom.createTextNode( theFields[fieldNumber].name() );
          QDomNode nameNode = classificationFieldElem.firstChild();
          classificationFieldElem.replaceChild( fieldName, nameNode );
        }
      }

    }
  }
}
Exemplo n.º 21
0
Arquivo: main.cpp Projeto: Ryzh/voc
void save_vec_to_file(const QVector<word_t*>& vec, const QString& filename)
{
	if (vec.isEmpty())
	{
		return;
	}
	
	QDomDocument doc;

	QFile file(filename);

	//Clear the file and input an empty xml structure
	if (!file.open(QIODevice::WriteOnly))
	{
		return;
	}

	QTextStream s(&file);
	s << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << "\n";
	s << "<WordList/>" << "\n";
	file.close();

	if (!file.open(QIODevice::ReadOnly))
	{
		return;
	}

	QString errorString;
	int errorLine;
	int errorCol;
	if (!doc.setContent(&file, true, &errorString, &errorLine, &errorCol))
	{
	}
	file.close();

	QDomElement root = doc.documentElement();
	if (root.tagName() != "WordList")
	{
		return;
	}

	for (int i = 0; i < vec.size(); ++i)
	{
		QDomElement newnode = doc.createElement("Word");
		newnode.setAttribute("name", vec[i]->name);
		newnode.setAttribute("time", vec[i]->time);
		newnode.setAttribute("marks", vec[i]->marks);
		QDomText defText = doc.createTextNode(vec[i]->def);
		newnode.appendChild(defText);
		if (root.hasChildNodes())
		{
			QDomNode child = root.firstChild();
			bool bInserted = false;
			while (!child.isNull())
			{
				QDomElement e = child.toElement();
				if (e.attribute("name") == vec[i]->name)
				{
					//the word has been logged, replace it.
					//TODO : may need to sum up the marks field.
					root.replaceChild(newnode, child);
					bInserted = true;
					break;
				}
				else if (e.attribute("name") > vec[i]->name)
				{
					root.insertBefore(newnode, child);
					bInserted = true;
					break;
				}
				child = child.nextSibling();
			}
			if (!bInserted)
			{
				root.appendChild(newnode);
				bInserted = true;
			}
		}
		else
		{
			root.appendChild(newnode);
		}
	}
	QString xml = doc.toString();
	if (!file.open(QIODevice::WriteOnly))
	{
		return;
	}
	QTextStream ts(&file);
	ts << xml;
	file.flush();
	file.close();
}
Exemplo n.º 22
0
QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& elem, bool useCache ) const
{
  if ( elem.isNull() || !mXMLDoc )
  {
    return nullptr;
  }

  addJoinLayersForElement( elem );
  addGetFeatureLayers( elem );

  QDomElement dataSourceElem = elem.firstChildElement( "datasource" );
  QString uri = dataSourceElem.text();
  QString absoluteUri;
  // If QgsProject instance fileName is set,
  // Is converting relative pathes to absolute still relevant ?
  if ( !dataSourceElem.isNull() )
  {
    //convert relative pathes to absolute ones if necessary
    if ( uri.startsWith( "dbname" ) ) //database
    {
      QgsDataSourceUri dsUri( uri );
      if ( dsUri.host().isEmpty() ) //only convert path for file based databases
      {
        QString dbnameUri = dsUri.database();
        QString dbNameUriAbsolute = convertToAbsolutePath( dbnameUri );
        if ( dbnameUri != dbNameUriAbsolute )
        {
          dsUri.setDatabase( dbNameUriAbsolute );
          absoluteUri = dsUri.uri();
          QDomText absoluteTextNode = mXMLDoc->createTextNode( absoluteUri );
          dataSourceElem.replaceChild( absoluteTextNode, dataSourceElem.firstChild() );
        }
      }
    }
    else if ( uri.startsWith( "file:" ) ) //a file based datasource in url notation (e.g. delimited text layer)
    {
      QString filePath = uri.mid( 5, uri.indexOf( "?" ) - 5 );
      QString absoluteFilePath = convertToAbsolutePath( filePath );
      if ( filePath != absoluteFilePath )
      {
        QUrl destUrl = QUrl::fromEncoded( uri.toAscii() );
        destUrl.setScheme( "file" );
        destUrl.setPath( absoluteFilePath );
        absoluteUri = destUrl.toEncoded();
        QDomText absoluteTextNode = mXMLDoc->createTextNode( absoluteUri );
        dataSourceElem.replaceChild( absoluteTextNode, dataSourceElem.firstChild() );
      }
      else
      {
        absoluteUri = uri;
      }
    }
    else //file based data source
    {
      absoluteUri = convertToAbsolutePath( uri );
      if ( uri != absoluteUri )
      {
        QDomText absoluteTextNode = mXMLDoc->createTextNode( absoluteUri );
        dataSourceElem.replaceChild( absoluteTextNode, dataSourceElem.firstChild() );
      }
    }
  }

  QString id = layerId( elem );
  QgsMapLayer* layer = nullptr;
  if ( useCache )
  {
    layer = QgsMSLayerCache::instance()->searchLayer( absoluteUri, id, mProjectPath );
  }

  if ( layer )
  {
    if ( !QgsMapLayerRegistry::instance()->mapLayer( id ) )
      QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false );
    if ( layer->type() == QgsMapLayer::VectorLayer )
      addValueRelationLayersForLayer( dynamic_cast<QgsVectorLayer *>( layer ) );

    return layer;
  }

  QString type = elem.attribute( "type" );
  if ( type == "vector" )
  {
    layer = new QgsVectorLayer();
  }
  else if ( type == "raster" )
  {
    layer = new QgsRasterLayer();
  }
  else if ( elem.attribute( "embedded" ) == "1" ) //layer is embedded from another project file
  {
    QString project = convertToAbsolutePath( elem.attribute( "project" ) );
    QgsDebugMsg( QString( "Project path: %1" ).arg( project ) );

    QgsServerProjectParser* otherConfig = QgsConfigCache::instance()->serverConfiguration( project );
    if ( !otherConfig )
    {
      return nullptr;
    }
    return otherConfig->mapLayerFromLayerId( elem.attribute( "id" ), useCache );
  }

  if ( layer )
  {
    if ( layer->type() == QgsMapLayer::VectorLayer )
    {
      // see QgsEditorWidgetRegistry::mapLayerAdded()
      QObject::connect( layer, SIGNAL( readCustomSymbology( const QDomElement&, QString& ) ), QgsEditorWidgetRegistry::instance(), SLOT( readSymbology( const QDomElement&, QString& ) ) );
    }

    layer->readLayerXml( const_cast<QDomElement&>( elem ) ); //should be changed to const in QgsMapLayer
    //layer->setLayerName( layerName( elem ) );

    // Insert layer in registry and cache before addValueRelationLayersForLayer
    if ( !QgsMapLayerRegistry::instance()->mapLayer( id ) )
      QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false );
    if ( useCache )
    {
      QgsMSLayerCache::instance()->insertLayer( absoluteUri, id, layer, mProjectPath );
    }
    else
    {
      //todo: fixme
      //mLayersToRemove.push_back( layer );
    }

    if ( layer->type() == QgsMapLayer::VectorLayer )
    {
      addValueRelationLayersForLayer( dynamic_cast<QgsVectorLayer *>( layer ) );
    }
  }
  return layer;
}
Exemplo n.º 23
0
/**
  @brief Enregistre les parametres dans un fichier de configuration xml

*/
bool ConfigXmlFile::save(const QString& filename,Configurable* config){

#ifdef _DEBUG
    QPRINT("save config <"+config->getConfigName()+"> to: "+filename);
#endif
    QDomDocument doc;
    QFile f(filename);
    if(!f.open(QIODevice::ReadOnly)){
        return QRESULT_DESC(Result::CantOpenFile,f.errorString());
    }
    doc.setContent(&f);

    f.close();

    // obtient noeud principale
    QDomElement root = doc.documentElement().firstChildElement(config->getConfigName());

    //crée l'élément si il n'existe pas
    if(root.isNull()){
        root = doc.createElement(config->getConfigName());
        if(!root.isNull())
            doc.documentElement().appendChild(root);
    }
    if(root.isNull())
        return QRESULT_DESC(Result::CantEditXmlFile,"Création du noeud "+config->getConfigName());

    //noeuds enfants
    ConfigParamList list;
    config->configRead(list);

    //scan les parametres
    for(ConfigParamList::const_iterator cur = list.begin(); cur != list.end(); cur++){
        QString name = cur->first;

        // obtient noeud enfant
        QDomElement old_child = root.firstChildElement(name);

        //crée l'élément si il n'existe pas
        QDomElement child = doc.createElement(name);
        if(!child.isNull())
            root.appendChild(child);
        if(child.isNull())
            return QRESULT_DESC(Result::CantEditXmlFile,"Création du noeud "+name);

        //définit le texte
        QDomText text = doc.createTextNode(cur->second->getValue());
        child.appendChild(text);

        //insert / remplace le nouveau noeud
        if(!old_child.isNull())
            root.replaceChild(child,old_child);
        else
            root.appendChild(child);
    }

    //réouvre le fichier en écriture
    QTextStream sortie;
    f.setFileName(filename);
    if(!f.open(QIODevice::WriteOnly)){
        return QRESULT_DESC(Result::CantOpenFile,f.errorString());
    }
    sortie.setDevice(&f); // association du flux au fichier

    // insertion en début de document de <?xml version="1.0" ?>
//    QDomNode headNode = doc.createProcessingInstruction("xml","version=\"1.0\"");
//    doc.insertBefore(headNode, doc.firstChild());
    // sauvegarde dans le flux (deux espaces de décalage dans l'arborescence)
    doc.save(sortie, 2);
    f.close();

    return QRESULT_OK();
}
Exemplo n.º 24
0
void Bookmarks::parseFolderElement(const QDomElement &element,
                                   QTreeWidgetItem* parentItem, const QString &/*elementID*/)
{
    QDomElement parentElement(element);
    QString id = "";
    if (parentElement.tagName() == "folder") {
        //old files that their 'folder' tag don't use 'id' attribute
        // just contain 'folder' tag of type 'Verses'!
        id = parentElement.attribute("id", "Verses");
        parentElement.setAttribute("id", id);
    }

    QTreeWidgetItem* item = createItem(parentElement, parentItem, id);

    QString title;
    if (id == "Verses") {
        title = tr("Verses");
    }
    else {
        title = element.firstChildElement("title").text();
    }
    if (title.isEmpty()) {
        title = QObject::tr("Folder");
    }

    item->setIcon(0, m_folderIcon);
    item->setText(0, title);
    item->setToolTip(0, title);

    bool folded = (parentElement.attribute("folded") != "no");
    setItemExpanded(item, !folded);

    QDomElement child = parentElement.firstChildElement();
    while (!child.isNull()) {
        if (child.tagName() == "folder") {
//TODO: we can save labguage within a 'metadata' tag of this 'folder'
//          //update node title by new loaded translation
            QString id = child.attribute("id");
            QString title = child.firstChildElement("title").text();

            if (id.isEmpty()) {
                //old files that their 'folder' tags don't use 'id' attribute just contain 'folder' tags of type 'Verses'!
                id = "Verses";
                title = tr(title.toLocal8Bit().data());
                QDomElement oldTitleElement = child.firstChildElement("title");
                QDomElement newTitleElement = m_domDocument.createElement("title");
                QDomText newTitleText = m_domDocument.createTextNode(tr("Verses"));
                newTitleElement.appendChild(newTitleText);

                child.replaceChild(newTitleElement, oldTitleElement);
                child.setAttribute("id", "Verses");
            }
            parseFolderElement(child, item, id);
        }
        else if (child.tagName() == "bookmark") {
            QTreeWidgetItem* childItem = createItem(child, item);

            QString title = child.firstChildElement("title").text();
            if (title.isEmpty()) {
                title = QObject::tr("Folder");
            }

            QDomElement infoChild = child.firstChildElement("info");
            QDomElement metaData = infoChild.firstChildElement("metadata");
            while (!metaData.isNull()) {
                QString owner = metaData.attribute("owner");
                if (owner == "http://saaghar.pozh.org") {
                    break;
                }
                metaData = metaData.nextSiblingElement("metadata");
            }
            if (!metaData.isNull() && metaData.attribute("owner") == "http://saaghar.pozh.org") {
                childItem->setData(0, Qt::UserRole, metaData.text());
            }
            else {
                qDebug() << "This DOM-NODE SHOULD deleted--->" << title;
            }
            //href data URL data
            childItem->setData(1, Qt::UserRole, child.attribute("href", "http://saaghar.pozh.org"));
            childItem->setIcon(0, m_bookmarkIcon);
            childItem->setText(0, title);
            childItem->setToolTip(0, title);
            childItem->setText(1, child.firstChildElement("desc").text());
            childItem->setToolTip(1, child.firstChildElement("desc").text());
        }
        else if (child.tagName() == "separator") {
            QTreeWidgetItem* childItem = createItem(child, item);
            childItem->setFlags(item->flags() & ~(Qt::ItemIsSelectable | Qt::ItemIsEditable));
            childItem->setText(0, QString(30, 0xB7));
        }
        child = child.nextSiblingElement();
    }
}
Exemplo n.º 25
0
QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& elem, bool useCache ) const
{
  if ( elem.isNull() || !mXMLDoc )
  {
    return 0;
  }

  addJoinLayersForElement( elem, useCache );
  addValueRelationLayersForElement( elem, useCache );

  QDomElement dataSourceElem = elem.firstChildElement( "datasource" );
  QString uri = dataSourceElem.text();
  QString absoluteUri;
  if ( !dataSourceElem.isNull() )
  {
    //convert relative pathes to absolute ones if necessary
    if ( uri.startsWith( "dbname" ) ) //database
    {
      QgsDataSourceURI dsUri( uri );
      if ( dsUri.host().isEmpty() ) //only convert path for file based databases
      {
        QString dbnameUri = dsUri.database();
        QString dbNameUriAbsolute = convertToAbsolutePath( dbnameUri );
        if ( dbnameUri != dbNameUriAbsolute )
        {
          dsUri.setDatabase( dbNameUriAbsolute );
          absoluteUri = dsUri.uri();
          QDomText absoluteTextNode = mXMLDoc->createTextNode( absoluteUri );
          dataSourceElem.replaceChild( absoluteTextNode, dataSourceElem.firstChild() );
        }
      }
    }
    else if ( uri.startsWith( "file:" ) ) //a file based datasource in url notation (e.g. delimited text layer)
    {
      QString filePath = uri.mid( 5, uri.indexOf( "?" ) - 5 );
      QString absoluteFilePath = convertToAbsolutePath( filePath );
      if ( filePath != absoluteFilePath )
      {
        QUrl destUrl = QUrl::fromEncoded( uri.toAscii() );
        destUrl.setScheme( "file" );
        destUrl.setPath( absoluteFilePath );
        absoluteUri = destUrl.toEncoded();
        QDomText absoluteTextNode = mXMLDoc->createTextNode( absoluteUri );
        dataSourceElem.replaceChild( absoluteTextNode, dataSourceElem.firstChild() );
      }
      else
      {
        absoluteUri = uri;
      }
    }
    else //file based data source
    {
      absoluteUri = convertToAbsolutePath( uri );
      if ( uri != absoluteUri )
      {
        QDomText absoluteTextNode = mXMLDoc->createTextNode( absoluteUri );
        dataSourceElem.replaceChild( absoluteTextNode, dataSourceElem.firstChild() );
      }
    }
  }

  QString id = layerId( elem );
  QgsMapLayer* layer = 0;
  if ( useCache )
  {
    layer = QgsMSLayerCache::instance()->searchLayer( absoluteUri, id );
  }

  if ( layer )
  {
    return layer;
  }

  QString type = elem.attribute( "type" );
  if ( type == "vector" )
  {
    layer = new QgsVectorLayer();
  }
  else if ( type == "raster" )
  {
    layer = new QgsRasterLayer();
  }
  else if ( elem.attribute( "embedded" ) == "1" ) //layer is embedded from another project file
  {
    //todo: fixme
    /*
    QString project = convertToAbsolutePath( elem.attribute( "project" ) );
    QgsDebugMsg( QString( "Project path: %1" ).arg( project ) );

    QgsProjectParser* otherConfig = dynamic_cast<QgsProjectParser*>( QgsConfigCache::instance()->searchConfiguration( project ) );
    if ( !otherConfig )
    {
      return 0;
    }

    QHash< QString, QDomElement >::const_iterator layerIt = otherConfig->mProjectLayerElementsById.find( elem.attribute( "id" ) );
    if ( layerIt == otherConfig->mProjectLayerElementsById.constEnd() )
    {
      return 0;
    }
    return otherConfig->createLayerFromElement( layerIt.value() );
    */
  }

  if ( layer )
  {
    layer->readLayerXML( const_cast<QDomElement&>( elem ) ); //should be changed to const in QgsMapLayer
    layer->setLayerName( layerName( elem ) );
    if ( useCache )
    {
      QgsMSLayerCache::instance()->insertLayer( absoluteUri, id, layer, mProjectPath );
    }
    else
    {
      //todo: fixme
      //mLayersToRemove.push_back( layer );
    }
  }
  return layer;
}
Exemplo n.º 26
0
QString MessageValidator::validateMessage(QString message, bool* illformed, HTMLTextFormatter* formatter) {

    //    qDebug() << "IMG val0" << message;
    QDomDocument doc("document");
    *illformed = false;

    QString errorMessage;
    int line, column;
    QDomDocument tmpDoc; //used by textformatter

    xmlSource.setData(message);

    if (!doc.setContent(&xmlSource, &xmlReader, &errorMessage, &line, &column)) {
        qDebug() << errorMessage << " " << line << " " << column << message;
        *illformed = true;
        qDebug() << "WARNING: MessageValidator::validateMessage() - illformed message";
        return "illformed message!!!";
    }

    //now DOM tree will be traversed in preorder. 
    QStack<QDomElement> stack; //current element, QStack is used to avoid possible stack overflow in ordinary recursion
    stack.push(doc.documentElement());

    while (!stack.empty()) {
        QDomElement cur = stack.top();
        stack.pop();

        // Traverse through DOM Tree(cur), cut off bad elements/attributes 
        // and format text nodes using textFormatter

        //    qDebug() << QString(4, ' ') << cur.tagName();

        QString parentName = cur.tagName();
        NodeInfo curNI = allowed[parentName];

        //delete disallowed attributes
        for (int i = 0; i < cur.attributes().count(); i++) {
            QString attrName = cur.attributes().item(i).toAttr().name();

            if (!curNI.allowedAttributes.contains(attrName)) {
                //     qDebug() << "VALIDATIN ERR" << "TA" << attrName  << " in " << parentName;
                //   qDebug() << "note allowed attributes are:" << curNI.allowedAttributes;

                cur.attributes().removeNamedItem(attrName);
                i--;
            }
        }

        QDomNodeList children = cur.childNodes();

        for (int i = children.size() - 1; i >= 0; i--) {
            QDomNode node = children.at(i);

            if (node.isElement()) {
                QString childName = node.toElement().tagName();

                if (childName == "a") { // always show hyperlink destination
                    QString href = node.toElement().attribute("href");
                    node.appendChild(doc.createTextNode(" [ " + href + " ]"));
                }

                if (childName == "style") { //NOTE: this action is not XHTML-IM compliant! (css rules should be displayed, but it's stupid)
                    cur.removeChild(node);
                }
                else if (childName == "img") { //disabling images until they are whitelisted

                    QString href = node.toElement().attribute("src");

                    QDomElement newElement = doc.createElement("a");
                    newElement.setAttribute("class", "psi_disabled_image");
                    newElement.setAttribute("href", "javascript:psi_addToWhiteList('" + href + "')");
                    newElement.appendChild(doc.createTextNode("[ click here to display: " + href + " ]"));

                    cur.replaceChild(newElement, node);
                }
                else if (!curNI.allowedTags.contains(childName)) {//is subElement valid here?

                    qDebug() << "VALIDATIN ERR" << "TS" << childName << " in " << parentName;
                    qDebug() << "note allowed subElements are:" << curNI.allowedTags;

                    //append bad node's children (they will be validated in next loop iteration)
                    int j = 0;
                    while (node.hasChildNodes()) {
                        cur.insertBefore(node.firstChild(), node);
                        j++;
                    }

                    i = i + j; //j nodes were inserted

                    //delete bad node
                    cur.removeChild(node);
                }
                else {
                    stack.push(node.toElement());
                }
            }
            else if (node.isText() && !node.isCDATASection()) {
                if (!curNI.canHaveText) {
                    cur.removeChild(node);
                }
                else { //format text
                    QString formattedText = "<tmp>" + formatter->format(Qt::escape(node.toText().data()), cur) + "</tmp>";
                    //NOTE: we don't need to escape quotes, and we want this code be more reusable/decoupled, 
                    //NOTE: so we use Qt::escape() instead of TextUtil::escape()
                   
                    xmlSource.setData(formattedText);
                    tmpDoc.setContent(&xmlSource, &xmlReader);
                   
                    QDomNode tmpElement = tmpDoc.firstChild();
                    while (tmpElement.hasChildNodes()) { //append <tmp>'s children. They won't be validated
                        cur.insertBefore(tmpElement.firstChild(), node);
                    }
                    
                    cur.removeChild(node);
                }
            }
        }//foreach child
    } //stack/dfs

//    qDebug() << "IMG MV:" << doc.toString(0);
    return doc.toString(0);
}
Exemplo n.º 27
0
void ReportViewWidget::on_actionSaveQry_triggered()
{
	if (m_currentQry.isEmpty()) {

		ReportFileDialog fD(m_dirModel, this);
		start:
	    if (fD.exec() != QDialog::Accepted)
	         return;

		if (fD.fileName().isEmpty())
			return;

		m_currentQry = fD.path() + "/" + fD.fileName();

		if (QFile(m_currentQry).exists()) {
	        if (QMessageBox::question(this, "CuteFarm",
	                             tr("File %1 exists.\nReplace?")
	                             .arg(m_currentQry), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
	        	goto start;
		}

		QFile file(m_currentQry);
	    if (!file.open(QFile::WriteOnly | QFile::Text)) {
	        QMessageBox::warning(this, "CuteFarm",
	                             tr("Can not save file %1\n%2.")
	                             .arg(file.fileName())
	                             .arg(file.errorString()));
	        return;
	    }

	    QTextStream out(&file);
	    out << "<?xml version='1.0' encoding='UTF-8'?>\n"
	    	   "<!DOCTYPE qry>\n"
	    	   "<qry version=\"1.0\">\n"
	    	   "	<description>"+ Qt::escape(ui.textEditComt->toPlainText()) +"</description>\n"
	    	   "	<sql>"+ Qt::escape(ui.textEditSql->toPlainText()) +"</sql>\n"
	    	   "</qry>\n";

	    QModelIndex parent = ui.dirView->currentIndex().parent();
	    m_dirModel->refresh(parent);
	    file.close();
	    m_actnQryButton->setText(QFileInfo(file.fileName()).fileName());

	    return;
	}

    QFile file(m_currentQry);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "CuteFarm",
                             tr("Can not save file %1\n%2.")
                             .arg(QFile(m_currentQry).fileName())
                             .arg(file.errorString()));
        return;
    }

    QDomElement root = m_domDocument.documentElement();
    QDomElement oldDesc = root.firstChildElement("description");
    QDomElement newDesc = m_domDocument.createElement("description");
    QDomText newDescText = m_domDocument.createTextNode(ui.textEditComt->toPlainText());
    newDesc.appendChild(newDescText);
    root.replaceChild(newDesc, oldDesc);
    QDomElement oldSql = root.firstChildElement("sql");
    QDomElement newSql = m_domDocument.createElement("sql");
    QDomText newSqlText = m_domDocument.createTextNode(ui.textEditSql->toPlainText());
    newSql.appendChild(newSqlText);
    root.replaceChild(newSql, oldSql);

    const int IndentSize = 4;

    QTextStream out(&file);
    m_domDocument.save(out, IndentSize);
    file.close();
    QModelIndex parent = ui.dirView->currentIndex().parent();
    m_dirModel->refresh(parent);

    emit statusMsg(tr("Saved: %1").arg(m_currentQry), 5000);
}
Exemplo n.º 28
0
void ModPlusExeCtrl::setInputVariablesXml(QDomDocument & doc, QString modelName, MOVector<Variable> *variables)
{
    QDomElement xfmi = doc.firstChildElement("fmiModelDescription");
    QDomElement oldxfmi = xfmi;

    QDomElement xModelVars = xfmi.firstChildElement("ModelVariables");
    QDomElement oldxModelVars = xModelVars;

    QDomNodeList listScalarVars = xModelVars.elementsByTagName("ScalarVariable");


    // filling map
    QMap<QString,int> mapScalarVars; //<name,index in listScalarVars>
    QMap<QDomElement,QDomElement> mapNewScalarVars; // <old node,new node>
    QDomElement curVar;
    QDomElement oldVar;
    QDomElement newVar;
    int index;
    QDomElement oldType;
    QDomElement newType;
    QString localVarName;

    // create map for index looking
    for(int i=0;i<listScalarVars.size();i++)
    {
        curVar = listScalarVars.at(i).toElement();
        mapScalarVars.insert(curVar.attribute("name"),i);
    }

    // change variables values
    for(int i=0;i<variables->size();i++)
    {
        // getting local var name (name in init file does not contain model name)
        localVarName = variables->at(i)->name(Variable::SHORT);
        if(localVarName.contains(modelName))
          localVarName = localVarName.remove(modelName+".");

        index = mapScalarVars.value(localVarName,-1);
        if(index>-1)
        {
            oldVar = listScalarVars.at(index).toElement();
            newVar = oldVar;

            oldType = newVar.firstChildElement("Real");
            if(oldType.isNull())
                oldType = newVar.firstChildElement("Integer");
            if(oldType.isNull())
                oldType = newVar.firstChildElement("Boolean");

            if(!oldType.isNull())
            {
                newType = oldType;
                newType.setAttribute("start",variables->at(i)->value().toString());
                newVar.replaceChild(newType,oldType);
                xModelVars.replaceChild(newVar,oldVar);
            }
            xModelVars.replaceChild(newVar,oldVar);
        }
    }

    // update xfmi with new vars
    xfmi.replaceChild(xModelVars,oldxModelVars);
    doc.replaceChild(xfmi,oldxfmi);
}
Exemplo n.º 29
0
/// 目前太单纯,需要根据不同的控件来处理
void writeJob::parsePropertyElement(QDomElement property,QString text)
{
    QDomElement oldDisplayType=property.firstChildElement("displaytype");
    /// 需要根据这个类型来判断
    qDebug()<<"changed widget type::"<<oldDisplayType.attribute("name");
    QString type=oldDisplayType.attribute("name");

    // ------------------------------- 一般控件--------------------------//
    if(type=="lineedit" || type=="checkbox" || type=="spinbox" || type=="fileread" || type=="filesave")
    {
        QDomElement newDisplayType = doc.createElement("displaytype");
        newDisplayType.setAttribute("name",oldDisplayType.attribute("name"));  //保留控件类型
        QDomText newDisplayText = doc.createTextNode(text);
        newDisplayType.appendChild(newDisplayText);
        property.replaceChild(newDisplayType,oldDisplayType);
    }

    // ------------------------------- comboBox--------------------------//
    if(type=="combobox")
    {
        qDebug()<<"handle combobox";
        QDomElement optionEle=oldDisplayType.firstChildElement("option");
        QList<QDomElement> newEle;
        QList<QDomElement> oldEle;
        while(!optionEle.isNull())
        {
            if(optionEle.attribute("value")==text)
            {
                QDomElement newOptionEle = doc.createElement("option");
                newOptionEle.setAttribute("value",optionEle.attribute("value"));
                QDomText newOptionText = doc.createTextNode("checked");
                newOptionEle.appendChild(newOptionText);
                newEle.append(newOptionEle);
                oldEle.append(optionEle);
            }
            else
            {
                QDomElement newOptionEle = doc.createElement("option");
                newOptionEle.setAttribute("value",optionEle.attribute("value"));
                QDomText newOptionText = doc.createTextNode("unchecked");
                newOptionEle.appendChild(newOptionText);
                newEle.append(newOptionEle);
                oldEle.append(optionEle);
            }
            optionEle=optionEle.nextSiblingElement("option");
        }
        /// 需要替换全部保存,到最后一起替换,证实此方法可行,中途替换将导致循环的不进行
        for(int i=0;i<newEle.size();i++)
        {
            oldDisplayType.replaceChild(newEle[i],oldEle[i]);
        }
    }
    if(type=="filecombobox")
    {
        qDebug()<<"handle filecombobox";
        QDomElement optionEle=oldDisplayType.firstChildElement("option");

        QDomElement newOptionEle = doc.createElement("option");
        newOptionEle.setAttribute("value",text);  //保留控件类型
        QDomText newOptionText = doc.createTextNode(optionEle.text());
        newOptionEle.appendChild(newOptionText);
        oldDisplayType.replaceChild(newOptionEle,optionEle);
    }
    if(type=="radiobutton")
    {
        qDebug()<<"handle radiobutton:: this can`t be shown,beacuse of the anthoer parseProperty";
        /// 这个比较难搞,目前还没发出信号
    }
}