SimXmlElement SimXmlDoc::addElement(const std::string& elementName) { QSharedPointer<QDomElement> elementImpl(new QDomElement(impl()->createElement(QString::fromStdString(elementName)))); elementImpl->setAttribute("RefId", QUuid::createUuid().toString()); SimXmlElement result(elementImpl, *this); QDomElement documentElement = impl()->documentElement(); // insert in alphabetical order QDomNode n = documentElement.firstChild(); while (!n.isNull()) { if (n.isElement()) { QDomElement e = n.toElement(); // if element name is greater than new one if (e.tagName().toStdString() > elementName){ documentElement.insertBefore(*elementImpl, n); return result; } } n = n.nextSibling(); } documentElement.appendChild(*elementImpl); return result; }
StyleItem::StyleItem( QDomElement el, QString colors[], QDomElement defs ) { QDomElement name = el.firstChildElement("name"); this->name = name.text(); QDomElement svg = el.firstChildElement("svg"); if ( svg.isNull() ) { this->renderer = NULL; } else { if ( !defs.isNull() ) svg.insertBefore( defs, QDomNode() ); QDomDocument doc; doc.setContent( css ); svg.insertBefore( doc, QDomNode() ); QTextStream stream(&(this->svg)); svg.save(stream, 0); this->renderer = new QSvgRenderer( this->makeSvg( colors, STYLE_KEY_COLOR ).toAscii() ); } }
/*! * \brief TLMEditor::createAnnotationElement * Creates an Annotation tag for SubModel. * \param subModel * \param visible * \param origin * \param extent * \param rotation */ void TLMEditor::createAnnotationElement(QDomElement subModel, QString visible, QString origin, QString extent, QString rotation) { QDomElement annotation = mXmlDocument.createElement("Annotation"); annotation.setAttribute("Visible", visible); annotation.setAttribute("Origin", origin); annotation.setAttribute("Extent", extent); annotation.setAttribute("Rotation", rotation); subModel.insertBefore(annotation, QDomNode()); mpPlainTextEdit->setPlainText(mXmlDocument.toString()); }
bool XdgMenuReader::load(const QString& fileName, const QString& baseDir) { if (fileName.isEmpty()) { mErrorStr = tr("Menu file not defined."); return false; } QFileInfo fileInfo(QDir(baseDir), fileName); mFileName = fileInfo.canonicalFilePath(); mDirName = fileInfo.canonicalPath(); if (mBranchFiles.contains(mFileName)) return false; // Recursive loop detected mBranchFiles << mFileName; QFile file(mFileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { mErrorStr = tr("%1 not loading: %2").arg(fileName).arg(file.errorString()); return false; } //qDebug() << "Load file:" << mFileName; mMenu->addWatchPath(mFileName); QString errorStr; int errorLine; int errorColumn; if (!mXml.setContent(&file, true, &errorStr, &errorLine, &errorColumn)) { mErrorStr = tr("Parse error at line %1, column %2:\n%3") .arg(errorLine) .arg(errorColumn) .arg(errorStr); return false; } QDomElement root = mXml.documentElement(); QDomElement debugElement = mXml.createElement("FileInfo"); debugElement.setAttribute("file", mFileName); if (mParentReader) debugElement.setAttribute("parent", mParentReader->fileName()); QDomNode null; root.insertBefore(debugElement, null); processMergeTags(root); return true; }
void XmlFloTransBase::setEleNodeText(QDomElement &elenode, const QString &text) { if(elenode.firstChild().isNull() || !elenode.firstChild().isText()) { QDomText textnode = domDocument.createTextNode(text); elenode.insertBefore(textnode,elenode.firstChild()); } else { elenode.firstChild().setNodeValue(text); } }
void MainWindow::on_actionPage_backward_activated() { QDomElement root = document->documentElement(); QDomElement picture = album.toElement(); root.insertBefore(picture, picture.previousSiblingElement("photo")); if(album.previousSibling().isNull()) { ui->actionMove_backward->setEnabled(false); ui->actionPage_backward->setEnabled(false); } if(!album.nextSibling().isNull()) { ui->actionMove_forward->setEnabled(true); ui->actionPage_forward->setEnabled(true); } ui->statusBar->showMessage("Moved photo back one in album"); }
void writeJob::resetModuleName(const QString name) { qDebug()<<"writeJob::resetModuleName"; QDomElement root = doc.documentElement(); QDomElement modEle = root.firstChildElement("Module"); while (!modEle.isNull()) { if(modEle.attribute("name")==name && modEle.attribute("id")==moduleID) { /// 采用的替换法,多替换几次???难道仅仅是这个函数多执行几次??? QDomElement prevModEle=modEle.previousSiblingElement("Module"); root.insertBefore(modEle,prevModEle); break; } modEle = modEle.nextSiblingElement("Module"); } if(!write()) qDebug()<<"writeJob::reset job failed"; }
//节点最前插入 bool MainWindow::prependNode(const QString &strFilePath, const QString &strNodeName, const QMap<QString,QString> &nodeMap) { QDomDocument doc; //整个文档 QFile file(strFilePath); //xml文件 if (!file.open(QFile::ReadOnly | QFile::Text)) { return false ; } if(!doc.setContent(&file,true)) { file.close(); return false; } file.close(); //读结束 QDomElement root = doc.documentElement(); //根节点 QDomElement node = doc.createElement(strNodeName); //子节点 if (root.hasChildNodes()) //具有子节点 { QDomElement firstNode = root.firstChild().toElement(); //第一个子节点 root.insertBefore(node,firstNode); //插在前面 } else //不具有子节点 { root.appendChild(node); //直接插入 } QStringList tagNameList = nodeMap.keys(); //所有的tagName foreach(QString strTagName, tagNameList) { QString strTextNode = nodeMap.value(strTagName); QDomElement nodeElement = doc.createElement(strTagName); node.appendChild(nodeElement); //子节点的各节点(属性) QDomText textNode = doc.createTextNode(strTextNode); nodeElement.appendChild(textNode); //属性的内容 }
void XdgMenuPrivate::prependChilds(QDomElement& srcElement, QDomElement& destElement) { MutableDomElementIterator it(srcElement); it.toBack(); while(it.hasPrevious()) { QDomElement n = it.previous(); destElement.insertBefore(n, destElement.firstChild()); } if (srcElement.attributes().contains("deleted") && !destElement.attributes().contains("deleted") ) destElement.setAttribute("deleted", srcElement.attribute("deleted")); if (srcElement.attributes().contains("onlyUnallocated") && !destElement.attributes().contains("onlyUnallocated") ) destElement.setAttribute("onlyUnallocated", srcElement.attribute("onlyUnallocated")); }
void ConfigDocumentXML::onAddSection(int _n) { QDomElement config = document_.documentElement(); QDomElement e = document_.createElement(Section::XML_TAG); e.setAttribute(Section::XML_ATTRIBUTE_KEY, menuAddSection_->text(_n)); QDomNode n = config.firstChild(); QDomNode newChild; if (config.firstChild().isNull()) newChild = config.appendChild(e); else newChild = config.insertBefore(e, n); MIRO_ASSERT(!newChild.isNull()); new Section(newChild, listViewItem(), NULL, this, menuAddSection_->text(_n)); setModified(); }
void ConfigDocumentXML::onAddSection(int _n) { QDomElement config = document_.documentElement(); QDomElement e = document_.createElement(Section::XML_TAG); e.setAttribute(Section::XML_ATTRIBUTE_KEY, menuAddSection_->text(_n)); QDomNode n = config.firstChild(); QDomNode newChild; if (config.firstChild().isNull()) newChild = config.appendChild(e); else newChild = config.insertBefore(e, n); assert(!newChild.isNull()); // The constructor registers the constructed element new Section(newChild, treeWidgetItem(), // QTreeWidget for the ConfigDocumentXML NULL, this, // parent QObject menuAddSection_->text(_n)); setModified(); }
void QgsSingleBandGrayRenderer::toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap &props ) const { QgsStringMap newProps = props; // create base structure QgsRasterRenderer::toSld( doc, element, props ); // look for RasterSymbolizer tag QDomNodeList elements = element.elementsByTagName( QStringLiteral( "sld:RasterSymbolizer" ) ); if ( elements.size() == 0 ) return; // there SHOULD be only one QDomElement rasterSymbolizerElem = elements.at( 0 ).toElement(); // add Channel Selection tags // Need to insert channelSelection in the correct sequence as in SLD standard e.g. // after opacity or geometry or as first element after sld:RasterSymbolizer QDomElement channelSelectionElem = doc.createElement( QStringLiteral( "sld:ChannelSelection" ) ); elements = rasterSymbolizerElem.elementsByTagName( QStringLiteral( "sld:Opacity" ) ); if ( elements.size() != 0 ) { rasterSymbolizerElem.insertAfter( channelSelectionElem, elements.at( 0 ) ); } else { elements = rasterSymbolizerElem.elementsByTagName( QStringLiteral( "sld:Geometry" ) ); if ( elements.size() != 0 ) { rasterSymbolizerElem.insertAfter( channelSelectionElem, elements.at( 0 ) ); } else { rasterSymbolizerElem.insertBefore( channelSelectionElem, rasterSymbolizerElem.firstChild() ); } } // for gray band QDomElement channelElem = doc.createElement( QStringLiteral( "sld:GrayChannel" ) ); channelSelectionElem.appendChild( channelElem ); // set band QDomElement sourceChannelNameElem = doc.createElement( QStringLiteral( "sld:SourceChannelName" ) ); sourceChannelNameElem.appendChild( doc.createTextNode( QString::number( grayBand() ) ) ); channelElem.appendChild( sourceChannelNameElem ); // set ContrastEnhancement if ( contrastEnhancement() ) { QDomElement contrastEnhancementElem = doc.createElement( QStringLiteral( "sld:ContrastEnhancement" ) ); contrastEnhancement()->toSld( doc, contrastEnhancementElem ); // do changes to minValue/maxValues depending on stretching algorithm. This is necessary because // geoserver do a first stretch on min/max, then apply colo map rules. In some combination is necessary // to use real min/max values and in othere the actual edited min/max values switch ( contrastEnhancement()->contrastEnhancementAlgorithm() ) { case QgsContrastEnhancement::StretchAndClipToMinimumMaximum: case QgsContrastEnhancement::ClipToMinimumMaximum: { // with this renderer export have to be check against real min/max values of the raster QgsRasterBandStats myRasterBandStats = mInput->bandStatistics( grayBand(), QgsRasterBandStats::Min | QgsRasterBandStats::Max ); // if minimum range differ from the real minimum => set is in exported SLD vendor option if ( !qgsDoubleNear( contrastEnhancement()->minimumValue(), myRasterBandStats.minimumValue ) ) { // look for VendorOption tag to look for that with minValue attribute QDomNodeList elements = contrastEnhancementElem.elementsByTagName( QStringLiteral( "sld:VendorOption" ) ); for ( int i = 0; i < elements.size(); ++i ) { QDomElement vendorOption = elements.at( i ).toElement(); if ( vendorOption.attribute( QStringLiteral( "name" ) ) != QStringLiteral( "minValue" ) ) continue; // remove old value and add the new one vendorOption.removeChild( vendorOption.firstChild() ); vendorOption.appendChild( doc.createTextNode( QString::number( myRasterBandStats.minimumValue ) ) ); } } break; } case QgsContrastEnhancement::UserDefinedEnhancement: break; case QgsContrastEnhancement::NoEnhancement: break; case QgsContrastEnhancement::StretchToMinimumMaximum: break; } channelElem.appendChild( contrastEnhancementElem ); } // for each color set a ColorMapEntry tag nested into "sld:ColorMap" tag // e.g. <ColorMapEntry color="#EEBE2F" quantity="-300" label="label" opacity="0"/> QList< QPair< QString, QColor > > classes; legendSymbologyItems( classes ); // add ColorMap tag QDomElement colorMapElem = doc.createElement( QStringLiteral( "sld:ColorMap" ) ); rasterSymbolizerElem.appendChild( colorMapElem ); // TODO: add clip intervals basing on real min/max without trigger // min/max calculation again that can takes a lot for remote or big images // // contrast enhancement against a color map can be SLD simulated playing with ColorMapEntryies // each ContrastEnhancementAlgorithm need a specific management. // set type of ColorMap ramp [ramp, intervals, values] // basing on interpolation algorithm of the raster shader QList< QPair< QString, QColor > > colorMapping( classes ); switch ( contrastEnhancement()->contrastEnhancementAlgorithm() ) { case ( QgsContrastEnhancement::StretchAndClipToMinimumMaximum ): case ( QgsContrastEnhancement::ClipToMinimumMaximum ): { QString lowValue = classes[0].first; QColor lowColor = classes[0].second; lowColor.setAlpha( 0 ); QString highValue = classes[1].first; QColor highColor = classes[1].second; highColor.setAlpha( 0 ); colorMapping.prepend( QPair< QString, QColor >( lowValue, lowColor ) ); colorMapping.append( QPair< QString, QColor >( highValue, highColor ) ); break; } case ( QgsContrastEnhancement::StretchToMinimumMaximum ): { colorMapping[0].first = QStringLiteral( "0" ); colorMapping[1].first = QStringLiteral( "255" ); break; } case ( QgsContrastEnhancement::UserDefinedEnhancement ): break; case ( QgsContrastEnhancement::NoEnhancement ): break; } // create tags QList< QPair< QString, QColor > >::ConstIterator it; for ( it = colorMapping.begin(); it != colorMapping.constEnd() ; ++it ) { // set low level color mapping QDomElement lowColorMapEntryElem = doc.createElement( QStringLiteral( "sld:ColorMapEntry" ) ); colorMapElem.appendChild( lowColorMapEntryElem ); lowColorMapEntryElem.setAttribute( QStringLiteral( "color" ), it->second.name() ); lowColorMapEntryElem.setAttribute( QStringLiteral( "quantity" ), it->first ); if ( it->second.alphaF() == 0.0 ) { lowColorMapEntryElem.setAttribute( QStringLiteral( "opacity" ), QString::number( it->second.alpha() ) ); } } }
void schedulexmldata::addschedulexmldata(QString tmpscheduledate, QString tmpid, QString tmptheme, QString tmpoccurtime, QString tmpoccuraddress, /*QString tmpremindtime, QString tmpremindway, QString tmpremindsequence,*/ QString tmpeventrepeat, QString tmpdetail) { QFile file("/home/user/.scheduledata.xml"); if(!file.open(QIODevice::ReadOnly)) return; QDomDocument doc; if(!doc.setContent(&file)){ file.close(); return; } file.close(); QDomText text; QDomElement root = doc.documentElement(); QDomElement scheduledate = doc.createElement(QString("scheduledate")); QDomAttr scheduledateattr = doc.createAttribute(QString("scheduledateattr")); scheduledate.setAttributeNode(scheduledateattr); QDomElement schedule = doc.createElement(QString("schedule")); QDomNode n = root.firstChild(); if(n.toElement().attribute(QString("scheduledateattr")) == "00000000"){ root.removeChild(n); root.appendChild(scheduledate); scheduledateattr.setValue(tmpscheduledate); scheduledate.appendChild(schedule); }else{ bool scheduledateisexistence = false; while(!n.isNull()){ if((n.previousSibling().toElement().attribute(QString("scheduledateattr")) < tmpscheduledate) &&( tmpscheduledate < n.toElement().attribute(QString("scheduledateattr")))){ root.insertBefore(scheduledate, n); scheduledateattr.setValue(tmpscheduledate); scheduledate.appendChild(schedule); scheduledateisexistence = true; }else if(tmpscheduledate == n.toElement().attribute(QString("scheduledateattr"))){ n.toElement().appendChild(schedule); scheduledateisexistence = true; } n = n.nextSibling(); } if(!scheduledateisexistence){ root.appendChild(scheduledate); scheduledateattr.setValue(tmpscheduledate); scheduledate.appendChild(schedule); } } if(tmpid == "-10"){ QDomNode nn = root.firstChild(); while(!nn.isNull()){ if(tmpscheduledate == nn.toElement().attribute(QString("scheduledateattr"))){ QDomNodeList schedulelist = nn.toElement().elementsByTagName(QString("schedule")); tmpid.setNum(schedulelist.count() - 1); qDebug() << tmpid; } nn = nn.nextSibling(); } } QDomAttr scheduleid = doc.createAttribute(QString("id")); scheduleid.setValue(QString(tmpid)); schedule.setAttributeNode(scheduleid); QDomElement theme = doc.createElement(QString("theme")); text = doc.createTextNode(QString(tmptheme)); theme.appendChild(text); schedule.appendChild(theme); QDomElement occurtime = doc.createElement(QString("occurtime")); text = doc.createTextNode(QString(tmpoccurtime)); occurtime.appendChild(text); schedule.appendChild(occurtime); QDomElement occuraddress = doc.createElement(QString("occuraddress")); text = doc.createTextNode(QString(tmpoccuraddress)); occuraddress.appendChild(text); schedule.appendChild(occuraddress); // QDomElement remindtime = doc.createElement(QString("remindtime")); // text = doc.createTextNode(QString(tmpremindtime)); // remindtime.appendChild(text); // schedule.appendChild(remindtime); // QDomElement remindway = doc.createElement(QString("remindway")); // text = doc.createTextNode(QString(tmpremindway)); // remindway.appendChild(text); // schedule.appendChild(remindway); // QDomElement remindsequence = doc.createElement(QString("remindsequence")); // text = doc.createTextNode(QString(tmpremindsequence)); // remindsequence.appendChild(text); // schedule.appendChild(remindsequence); QDomElement eventrepeat = doc.createElement(QString("eventrepeat")); text = doc.createTextNode(QString(tmpeventrepeat)); eventrepeat.appendChild(text); schedule.appendChild(eventrepeat); QDomElement detail = doc.createElement(QString("detail")); text = doc.createTextNode(QString(tmpdetail)); detail.appendChild(text); schedule.appendChild(detail); if( !file.open(QIODevice::WriteOnly | QIODevice::Truncate)) return; QTextStream out(&file); doc.save(out, 4); file.close(); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); if (a.arguments().count() <= 1) { qWarning() << "Argument expected: url to open"; return 1; } new KHTMLGlobal; KXmlGuiWindow *toplevel = new KXmlGuiWindow(); KHTMLPart *doc = new KHTMLPart(toplevel, toplevel, KHTMLPart::BrowserViewGUI); Dummy *dummy = new Dummy(doc); QObject::connect(doc->browserExtension(), SIGNAL(openUrlRequest(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)), dummy, SLOT(slotOpenURL(QUrl,KParts::OpenUrlArguments,KParts::BrowserArguments))); QObject::connect(doc, SIGNAL(completed()), dummy, SLOT(handleDone())); QUrl url = QUrl::fromUserInput(a.arguments().at(1)); // TODO support for relative paths if (url.path().right(4).toLower() == ".xml") { KParts::OpenUrlArguments args(doc->arguments()); args.setMimeType("text/xml"); doc->setArguments(args); } doc->openUrl(url); toplevel->setCentralWidget(doc->widget()); toplevel->resize(800, 600); QDomDocument d = doc->domDocument(); QDomElement viewMenu = d.documentElement().firstChild().childNodes().item(2).toElement(); QDomElement e = d.createElement("action"); e.setAttribute("name", "debugRenderTree"); viewMenu.appendChild(e); e = d.createElement("action"); e.setAttribute("name", "debugDOMTree"); viewMenu.appendChild(e); e = d.createElement("action"); e.setAttribute("name", "debugDoBenchmark"); viewMenu.appendChild(e); QDomElement toolBar = d.documentElement().firstChild().nextSibling().toElement(); e = d.createElement("action"); e.setAttribute("name", "editable"); toolBar.insertBefore(e, toolBar.firstChild()); e = d.createElement("action"); e.setAttribute("name", "navigable"); toolBar.insertBefore(e, toolBar.firstChild()); e = d.createElement("action"); e.setAttribute("name", "reload"); toolBar.insertBefore(e, toolBar.firstChild()); e = d.createElement("action"); e.setAttribute("name", "print"); toolBar.insertBefore(e, toolBar.firstChild()); QAction *action = new QAction(QIcon::fromTheme("view-refresh"), "Reload", doc); doc->actionCollection()->addAction("reload", action); QObject::connect(action, SIGNAL(triggered(bool)), dummy, SLOT(reload())); doc->actionCollection()->setDefaultShortcut(action, Qt::Key_F5); QAction *bench = new QAction(QIcon(), "Benchmark...", doc); doc->actionCollection()->addAction("debugDoBenchmark", bench); QObject::connect(bench, SIGNAL(triggered(bool)), dummy, SLOT(doBenchmark())); QAction *kprint = new QAction(QIcon::fromTheme("document-print"), "Print", doc); doc->actionCollection()->addAction("print", kprint); QObject::connect(kprint, SIGNAL(triggered(bool)), doc->browserExtension(), SLOT(print())); kprint->setEnabled(true); KToggleAction *ta = new KToggleAction(QIcon::fromTheme("edit-rename"), "Navigable", doc); doc->actionCollection()->addAction("navigable", ta); ta->setShortcuts(QList<QKeySequence>()); ta->setChecked(doc->isCaretMode()); QWidget::connect(ta, SIGNAL(toggled(bool)), dummy, SLOT(toggleNavigable(bool))); ta = new KToggleAction(QIcon::fromTheme("document-properties"), "Editable", doc); doc->actionCollection()->addAction("editable", ta); ta->setShortcuts(QList<QKeySequence>()); ta->setChecked(doc->isEditable()); QWidget::connect(ta, SIGNAL(toggled(bool)), dummy, SLOT(toggleEditable(bool))); toplevel->guiFactory()->addClient(doc); doc->setJScriptEnabled(true); doc->setJavaEnabled(true); doc->setPluginsEnabled(true); doc->setURLCursor(QCursor(Qt::PointingHandCursor)); a.setActiveWindow(doc->widget()); QWidget::connect(doc, SIGNAL(setWindowCaption(QString)), doc->widget()->topLevelWidget(), SLOT(setCaption(QString))); doc->widget()->show(); toplevel->show(); doc->view()->viewport()->show(); doc->view()->widget()->show(); int ret = a.exec(); return ret; }
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(); }
void TestKHTML::setupActions() { QDomDocument document = m_part->domDocument(); QDomElement fileMenu = document.documentElement().firstChild().childNodes().item( 0 ).toElement(); QDomElement quitElement = document.createElement("action"); quitElement.setAttribute("name", KStandardAction::name(KStandardAction::Quit)); fileMenu.appendChild(quitElement); QDomElement viewMenu = document.documentElement().firstChild().childNodes().item( 2 ).toElement(); QDomElement element = document.createElement("action"); element.setAttribute("name", "debugRenderTree"); viewMenu.appendChild(element); element = document.createElement("action"); element.setAttribute("name", "debugDOMTree"); viewMenu.appendChild(element); QDomElement toolBar = document.documentElement().firstChild().nextSibling().toElement(); element = document.createElement("action"); element.setAttribute("name", "editable"); toolBar.insertBefore(element, toolBar.firstChild()); element = document.createElement("action"); element.setAttribute("name", "navigable"); toolBar.insertBefore(element, toolBar.firstChild()); element = document.createElement("action"); element.setAttribute("name", "reload"); toolBar.insertBefore(element, toolBar.firstChild()); element = document.createElement("action"); element.setAttribute("name", "print"); toolBar.insertBefore(element, toolBar.firstChild()); KAction *action = new KAction(KIcon("view-refresh"), "Reload", this ); m_part->actionCollection()->addAction( "reload", action ); connect(action, SIGNAL(triggered(bool)), this, SLOT(reload())); action->setShortcut(Qt::Key_F5); KAction *kprint = new KAction(KIcon("document-print"), "Print", this ); m_part->actionCollection()->addAction( "print", kprint ); connect(kprint, SIGNAL(triggered(bool)), m_part->browserExtension(), SLOT(print())); kprint->setEnabled(true); KToggleAction *ta = new KToggleAction( KIcon("edit-rename"), "Navigable", this ); actionCollection()->addAction( "navigable", ta ); ta->setShortcuts( KShortcut() ); ta->setChecked(m_part->isCaretMode()); connect(ta, SIGNAL(toggled(bool)), this, SLOT(toggleNavigable(bool))); ta = new KToggleAction( KIcon("document-properties"), "Editable", this ); actionCollection()->addAction( "editable", ta ); ta->setShortcuts( KShortcut() ); ta->setChecked(m_part->isEditable()); connect(ta, SIGNAL(toggled(bool)), this, SLOT(toggleEditable(bool))); KStandardAction::quit( kapp, SLOT(quit()), m_part->actionCollection() ); guiFactory()->addClient(m_part); }
QDomElement FormatImporter::importBasket(const QString &folderName) { // Load the XML file: QDomDocument *document = XMLWork::openFile("basket", Global::basketsFolder() + folderName + "/.basket"); if (!document) { kDebug() << "Import Baskets: Failed to read the basket file!"; return QDomElement(); } QDomElement docElem = document->documentElement(); // Import properties (change <background color=""> to <appearance backgroundColor="">, and figure out if is a checklist or not): QDomElement properties = XMLWork::getElement(docElem, "properties"); QDomElement background = XMLWork::getElement(properties, "background"); QColor backgroundColor = QColor(background.attribute("color")); if (backgroundColor.isValid() && (backgroundColor != kapp->palette().color(QPalette::Base))) { // Use the default color if it was already that color: QDomElement appearance = document->createElement("appearance"); appearance.setAttribute("backgroundColor", backgroundColor.name()); properties.appendChild(appearance); } QDomElement disposition = document->createElement("disposition"); disposition.setAttribute("mindMap", "false"); disposition.setAttribute("columnCount", "1"); disposition.setAttribute("free", "false"); bool isCheckList = XMLWork::trueOrFalse( XMLWork::getElementText(properties, "showCheckBoxes", false) ); // Insert all notes in a group (column): 1/ rename "items" to "group", 2/ add "notes" to root, 3/ move "group" into "notes" QDomElement column = XMLWork::getElement(docElem, "items"); column.setTagName("group"); QDomElement notes = document->createElement("notes"); notes.appendChild(column); docElem.appendChild(notes); // Import notes from older representations: QDomNode n = column.firstChild(); while ( ! n.isNull() ) { QDomElement e = n.toElement(); if (!e.isNull()) { e.setTagName("note"); QDomElement content = XMLWork::getElement(e, "content"); // Add Check tag: if (isCheckList) { bool isChecked = XMLWork::trueOrFalse(e.attribute("checked", "false")); XMLWork::addElement(*document, e, "tags", (isChecked ? "todo_done" : "todo_unchecked")); } // Import annotations as folded groups: QDomElement parentE = column; QString annotations = XMLWork::getElementText(e, "annotations", ""); if (!annotations.isEmpty()) { QDomElement annotGroup = document->createElement("group"); column.insertBefore(annotGroup, e); annotGroup.setAttribute("folded", "true"); annotGroup.appendChild(e); parentE = annotGroup; // Create the text note and add it to the DOM tree: QDomElement annotNote = document->createElement("note"); annotNote.setAttribute("type", "text"); annotGroup.appendChild(annotNote); QString annotFileName = Tools::fileNameForNewFile("annotations1.txt", Basket::fullPathForFolderName(folderName)); QString annotFullPath = Basket::fullPathForFolderName(folderName) + "/" + annotFileName; QFile file(annotFullPath); if (file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream << annotations; file.close(); } XMLWork::addElement(*document, annotNote, "content", annotFileName); n = annotGroup; } // Import Launchers from 0.3.x, 0.4.0 and 0.5.0-alphas: QString runCommand = e.attribute("runcommand"); // Keep compatibility with 0.4.0 and 0.5.0-alphas versions runCommand = XMLWork::getElementText(e, "action", runCommand); // Keep compatibility with 0.3.x versions if ( ! runCommand.isEmpty() ) { // An import should be done // Prepare the launcher note: QString title = content.attribute("title", ""); QString icon = content.attribute("icon", ""); if (title.isEmpty()) title = runCommand; if (icon.isEmpty()) icon = NoteFactory::iconForCommand(runCommand); // Import the launcher note: // Adapted version of "QString launcherName = NoteFactory::createNoteLauncherFile(runCommand, title, icon, this)": QString launcherContent = QString( "[Desktop Entry]\n" "Exec=%1\n" "Name=%2\n" "Icon=%3\n" "Encoding=UTF-8\n" "Type=Application\n").arg(runCommand, title, icon.isEmpty() ? QString("exec") : icon); QString launcherFileName = Tools::fileNameForNewFile("launcher.desktop", Global::basketsFolder() + folderName /*+ "/"*/); QString launcherFullPath = Global::basketsFolder() + folderName /*+ "/"*/ + launcherFileName; QFile file(launcherFullPath); if (file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream.setCodec("UTF-8"); stream << launcherContent; file.close(); } // Add the element to the DOM: QDomElement launcherElem = document->createElement("note"); parentE.insertBefore(launcherElem, e); launcherElem.setAttribute("type", "launcher"); XMLWork::addElement(*document, launcherElem, "content", launcherFileName); } // Import unknown ns to 0.6.0: if (e.attribute("type") == "unknow") e.setAttribute("type", "unknown"); // Import links from version < 0.5.0: if (!content.attribute("autotitle").isEmpty() && content.attribute("autoTitle").isEmpty()) content.setAttribute("autoTitle", content.attribute("autotitle")); if (!content.attribute("autoicon").isEmpty() && content.attribute("autoIcon").isEmpty()) content.setAttribute("autoIcon", content.attribute("autoicon")); } n = n.nextSibling(); } // Save the resulting XML file: QFile file(Global::basketsFolder() + folderName + "/.basket"); if (file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream.setCodec("UTF-8"); // QString xml = document->toString(); // stream << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"; // stream << xml; stream << document->toString(); // Document is ALREADY using UTF-8 file.close(); } else kDebug() << "Import Baskets: Failed to save the basket file!"; // Return the newly created properties (to put in the basket tree): return properties; }
void saveScene(QWidget *parent, SceneContext *ctx, const QString &targetFile) { QDomElement root = ctx->doc.documentElement(); // ==================================================================== // Serialize the sensor configuration // ==================================================================== QList<QDomElement> oldSensors = findAllChildren(root, "sensor"); const ref_vector<Sensor> sensors = ctx->scene->getSensors(); ref_vector<Sensor>::const_iterator it = std::find(sensors.begin(), sensors.end(), ctx->scene->getSensor()); if (it == sensors.end()) SLog(EError, "Number of sensors did not match between loaded scene and XML file!"); QDomElement sensor, oldSensor; if (oldSensors.size() == 0) ; // ok -- scene did not contain a sensor before else if ((size_t) oldSensors.size() != ctx->scene->getSensors().size()) SLog(EError, "Number of sensors did not match between loaded scene and XML file!"); else oldSensor = oldSensors[it-sensors.begin()]; if (oldSensor.isNull()) { sensor = ctx->doc.createElement("sensor"); root.insertAfter(sensor, QDomNode()); } else { sensor = ctx->doc.createElement("sensor"); root.insertAfter(sensor, oldSensor); root.removeChild(oldSensor); } setProperties(ctx->doc, sensor, ctx->scene->getSensor()->getProperties()); // ==================================================================== // Serialize the sampler configuration // ==================================================================== QDomElement sampler = ctx->doc.createElement("sampler"); sensor.appendChild(sampler); setProperties(ctx->doc, sampler, ctx->scene->getSampler()->getProperties()); // ==================================================================== // Serialize the film configuration // ==================================================================== QDomElement film = ctx->doc.createElement("film"); sensor.appendChild(film); Properties filmProps(ctx->scene->getFilm()->getProperties()); if (filmProps.getPluginName() == "ldrfilm") { /* Also export the tonemapper settings */ if (ctx->toneMappingMethod == EGamma) { filmProps.setString("tonemapMethod", "gamma", false); filmProps.setFloat("exposure", ctx->exposure, false); filmProps.removeProperty("key"); filmProps.removeProperty("burn"); } else { filmProps.setString("tonemapMethod", "reinhard", false); filmProps.setFloat("key", ctx->reinhardKey, false); filmProps.setFloat("burn", (ctx->reinhardBurn + 10) / 20.0f, false); filmProps.removeProperty("exposure"); } filmProps.setFloat("gamma", ctx->srgb ? -1 : ctx->gamma, false); } setProperties(ctx->doc, film, filmProps); // ==================================================================== // Serialize the reconstruction filter configuration // ==================================================================== QDomElement rfilter = ctx->doc.createElement("rfilter"); film.appendChild(rfilter); setProperties(ctx->doc, rfilter, ctx->scene->getFilm()->getReconstructionFilter()->getProperties()); // ==================================================================== // Serialize medium references of the sensor // ==================================================================== QList<QDomElement> oldSensorReferences = findAllChildren(oldSensor, "ref"); oldSensorReferences.append(findAllChildren(oldSensor, "medium")); for (int i=0; i<oldSensorReferences.size(); ++i) sensor.appendChild(ctx->doc.importNode(oldSensorReferences[i], true)); // ==================================================================== // Serialize the integrator configuration // ==================================================================== QDomElement oldIntegratorNode = findUniqueChild(root, "integrator"); QDomElement newIntegratorNode = ctx->doc.createElement("integrator"); const Integrator *integrator = ctx->scene->getIntegrator(); setProperties(ctx->doc, newIntegratorNode, integrator->getProperties()); processSubIntegrators(ctx->doc, integrator, newIntegratorNode); root.insertBefore(newIntegratorNode, oldIntegratorNode); root.removeChild(oldIntegratorNode); QFile file; file.setFileName(targetFile); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) { QMessageBox::critical(parent, parent->tr("Unable to save"), parent->tr("Unable to save changes: could not open the destination file <b>%1</b>.").arg(targetFile), QMessageBox::Ok); return; } /* Clean up the XML output generated by Qt so that it is more suitable for human consumption .. Beware: the code below is tailored to Qt's output and won't work on arbitrary XML files */ QString textContent = ctx->doc.toString(); QTextStream input(&textContent); QTextStream output(&file); cleanupXML(input, output); file.close(); }
int main(int argc, char *argv[]) { KCmdLineArgs::init(argc, argv, "Testkhtml", "a basic web browser using the KHTML library", "1.0"); KCmdLineArgs::addCmdLineOptions(options); KApplication a; KCmdLineArgs *args = KCmdLineArgs::parsedArgs( ); if ( args->count() == 0 ) { KCmdLineArgs::usage(); ::exit( 1 ); } KHTMLFactory *fac = new KHTMLFactory(); KMainWindow *toplevel = new KMainWindow(); KHTMLPart *doc = new KHTMLPart( toplevel, 0, toplevel, 0, KHTMLPart::BrowserViewGUI ); Dummy *dummy = new Dummy( doc ); QObject::connect( doc->browserExtension(), SIGNAL( openURLRequest( const KURL &, const KParts::URLArgs & ) ), dummy, SLOT( slotOpenURL( const KURL&, const KParts::URLArgs & ) ) ); if (args->url(0).url().right(4).find(".xml", 0, false) == 0) { KParts::URLArgs ags(doc->browserExtension()->urlArgs()); ags.serviceType = "text/xml"; doc->browserExtension()->setURLArgs(ags); } doc->openURL( args->url(0) ); // DOMTreeView * dtv = new DOMTreeView(0, doc, "DomTreeView"); // dtv->show(); toplevel->setCentralWidget( doc->widget() ); toplevel->resize( 640, 800); // dtv->resize(toplevel->width()/2, toplevel->height()); QDomDocument d = doc->domDocument(); QDomElement viewMenu = d.documentElement().firstChild().childNodes().item( 2 ).toElement(); QDomElement e = d.createElement( "action" ); e.setAttribute( "name", "debugRenderTree" ); viewMenu.appendChild( e ); e = d.createElement( "action" ); e.setAttribute( "name", "debugDOMTree" ); viewMenu.appendChild( e ); QDomElement toolBar = d.documentElement().firstChild().nextSibling().toElement(); e = d.createElement( "action" ); e.setAttribute( "name", "reload" ); toolBar.insertBefore( e, toolBar.firstChild() ); e = d.createElement( "action" ); e.setAttribute( "name", "print" ); toolBar.insertBefore( e, toolBar.firstChild() ); (void)new KAction( "Reload", "reload", Qt::Key_F5, dummy, SLOT( reload() ), doc->actionCollection(), "reload" ); KAction* kprint = new KAction( "Print", "print", 0, doc->browserExtension(), SLOT( print() ), doc->actionCollection(), "print" ); kprint->setEnabled(true); toplevel->guiFactory()->addClient( doc ); doc->setJScriptEnabled(true); doc->setJavaEnabled(true); doc->setURLCursor(QCursor(Qt::PointingHandCursor)); a.setTopWidget(doc->widget()); QWidget::connect(doc, SIGNAL(setWindowCaption(const QString &)), doc->widget(), SLOT(setCaption(const QString &))); doc->widget()->show(); toplevel->show(); ((QScrollView *)doc->widget())->viewport()->show(); int ret = a.exec(); //delete doc; //delete dtv; khtml::Cache::clear(); khtml::CSSStyleSelector::clear(); khtml::RenderStyle::cleanup(); delete fac; return ret; }
int main(int argc, char *argv[]) { KCmdLineOptions options; options.add("+file", ki18n("URL to open")); KCmdLineArgs::init(argc, argv, "testkhtml", 0, ki18n("Testkhtml"), "1.0", ki18n("a basic web browser using the KHTML library")); KCmdLineArgs::addCmdLineOptions(options); KApplication a; KCmdLineArgs *args = KCmdLineArgs::parsedArgs( ); if ( args->count() == 0 ) { KCmdLineArgs::usage(); ::exit( 1 ); } new KHTMLGlobal; KXmlGuiWindow *toplevel = new KXmlGuiWindow(); KHTMLPart *doc = new KHTMLPart( toplevel, toplevel, KHTMLPart::BrowserViewGUI ); Dummy *dummy = new Dummy( doc ); QObject::connect( doc->browserExtension(), SIGNAL(openUrlRequest(KUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)), dummy, SLOT(slotOpenURL(KUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)) ); QObject::connect( doc, SIGNAL(completed()), dummy, SLOT(handleDone()) ); if (args->url(0).url().right(4).toLower() == ".xml") { KParts::OpenUrlArguments args(doc->arguments()); args.setMimeType("text/xml"); doc->setArguments(args); } doc->openUrl( args->url(0) ); toplevel->setCentralWidget( doc->widget() ); toplevel->resize( 800, 600); QDomDocument d = doc->domDocument(); QDomElement viewMenu = d.documentElement().firstChild().childNodes().item( 2 ).toElement(); QDomElement e = d.createElement( "action" ); e.setAttribute( "name", "debugRenderTree" ); viewMenu.appendChild( e ); e = d.createElement( "action" ); e.setAttribute( "name", "debugDOMTree" ); viewMenu.appendChild( e ); e = d.createElement( "action" ); e.setAttribute( "name", "debugDoBenchmark" ); viewMenu.appendChild( e ); QDomElement toolBar = d.documentElement().firstChild().nextSibling().toElement(); e = d.createElement( "action" ); e.setAttribute( "name", "editable" ); toolBar.insertBefore( e, toolBar.firstChild() ); e = d.createElement( "action" ); e.setAttribute( "name", "navigable" ); toolBar.insertBefore( e, toolBar.firstChild() ); e = d.createElement( "action" ); e.setAttribute( "name", "reload" ); toolBar.insertBefore( e, toolBar.firstChild() ); e = d.createElement( "action" ); e.setAttribute( "name", "print" ); toolBar.insertBefore( e, toolBar.firstChild() ); KAction *action = new KAction(KIcon("view-refresh"), "Reload", doc ); doc->actionCollection()->addAction( "reload", action ); QObject::connect(action, SIGNAL(triggered(bool)), dummy, SLOT(reload())); action->setShortcut(Qt::Key_F5); KAction *bench = new KAction( KIcon(), "Benchmark...", doc ); doc->actionCollection()->addAction( "debugDoBenchmark", bench ); QObject::connect(bench, SIGNAL(triggered(bool)), dummy, SLOT(doBenchmark())); KAction *kprint = new KAction(KIcon("document-print"), "Print", doc ); doc->actionCollection()->addAction( "print", kprint ); QObject::connect(kprint, SIGNAL(triggered(bool)), doc->browserExtension(), SLOT(print())); kprint->setEnabled(true); KToggleAction *ta = new KToggleAction( KIcon("edit-rename"), "Navigable", doc ); doc->actionCollection()->addAction( "navigable", ta ); ta->setShortcuts( KShortcut() ); ta->setChecked(doc->isCaretMode()); QWidget::connect(ta, SIGNAL(toggled(bool)), dummy, SLOT(toggleNavigable(bool))); ta = new KToggleAction( KIcon("document-properties"), "Editable", doc ); doc->actionCollection()->addAction( "editable", ta ); ta->setShortcuts( KShortcut() ); ta->setChecked(doc->isEditable()); QWidget::connect(ta, SIGNAL(toggled(bool)), dummy, SLOT(toggleEditable(bool))); toplevel->guiFactory()->addClient( doc ); doc->setJScriptEnabled(true); doc->setJavaEnabled(true); doc->setPluginsEnabled( true ); doc->setURLCursor(QCursor(Qt::PointingHandCursor)); a.setTopWidget(doc->widget()); QWidget::connect(doc, SIGNAL(setWindowCaption(QString)), doc->widget()->topLevelWidget(), SLOT(setCaption(QString))); doc->widget()->show(); toplevel->show(); doc->view()->viewport()->show(); doc->view()->widget()->show(); int ret = a.exec(); return ret; }
void writeJob::dragModuleName(const QString name, const int index, const int allRow, const QString upOrDown) { qDebug()<<"4.dragModuleName"; QDomElement root = doc.documentElement(); QDomElement modEle = root.firstChildElement("Module"); if(index==0) //插到头 { while (!modEle.isNull()) { if(modEle.attribute("name")==name && modEle.attribute("id")==moduleID) { QDomElement firstModEle=root.firstChildElement("Module"); root.insertBefore(modEle,firstModEle); break; } modEle = modEle.nextSiblingElement("Module"); } } else if(index==(allRow-1)) // 插到尾 { while (!modEle.isNull()) { if(modEle.attribute("name")==name && modEle.attribute("id")==moduleID) { QDomElement lastModEle=root.lastChildElement("Module"); root.insertAfter(modEle,lastModEle); break; } modEle = modEle.nextSiblingElement("Module"); } } else //其他情况 { QDomElement insertAfterEle; QDomElement rightEle; insertAfterEle=modEle; //难道还要分上到下,下到上?? if(upOrDown=="up") { for(int i=0; i<index-1;i++) { modEle = modEle.nextSiblingElement("Module"); insertAfterEle=modEle; qDebug()<<i<<insertAfterEle.attribute("name"); } } if(upOrDown=="down") { for(int i=0; i<index;i++) { modEle = modEle.nextSiblingElement("Module"); insertAfterEle=modEle; qDebug()<<i<<insertAfterEle.attribute("name"); } } modEle=root.firstChildElement("Module"); while (!modEle.isNull()) { if(modEle.attribute("name")==name && modEle.attribute("id")==moduleID) { rightEle=modEle; qDebug()<<rightEle.attribute("name")<<insertAfterEle.attribute("name"); root.insertAfter(rightEle,insertAfterEle); break; } modEle = modEle.nextSiblingElement("Module"); } } if(!write()) qDebug()<<"delete job failed"; }
bool KXMLGUIClient::mergeXML( QDomElement &base, const QDomElement &additive, KActionCollection *actionCollection ) { static const QString &tagAction = KGlobal::staticQString( "Action" ); static const QString &tagMerge = KGlobal::staticQString( "Merge" ); static const QString &tagSeparator = KGlobal::staticQString( "Separator" ); static const QString &attrName = KGlobal::staticQString( "name" ); static const QString &attrAppend = KGlobal::staticQString( "append" ); static const QString &attrWeakSeparator = KGlobal::staticQString( "weakSeparator" ); static const QString &tagMergeLocal = KGlobal::staticQString( "MergeLocal" ); static const QString &tagText = KGlobal::staticQString( "text" ); static const QString &attrAlreadyVisited = KGlobal::staticQString( "alreadyVisited" ); static const QString &attrNoMerge = KGlobal::staticQString( "noMerge" ); static const QString &attrOne = KGlobal::staticQString( "1" ); // there is a possibility that we don't want to merge in the // additive.. rather, we might want to *replace* the base with the // additive. this can be for any container.. either at a file wide // level or a simple container level. we look for the 'noMerge' // tag, in any event and just replace the old with the new if ( additive.attribute(attrNoMerge) == attrOne ) // ### use toInt() instead? (Simon) { base.parentNode().replaceChild(additive, base); return true; } QString tag; // iterate over all elements in the container (of the global DOM tree) QDomNode n = base.firstChild(); while ( !n.isNull() ) { QDomElement e = n.toElement(); n = n.nextSibling(); // Advance now so that we can safely delete e if (e.isNull()) continue; tag = e.tagName(); // if there's an action tag in the global tree and the action is // not implemented, then we remove the element if ( tag == tagAction ) { QCString name = e.attribute( attrName ).utf8(); // WABA if ( !actionCollection->action( name ) || (kapp && !kapp->authorizeKAction(name))) { // remove this child as we aren't using it base.removeChild( e ); continue; } } // if there's a separator defined in the global tree, then add an // attribute, specifying that this is a "weak" separator else if ( tag == tagSeparator ) { e.setAttribute( attrWeakSeparator, (uint)1 ); // okay, hack time. if the last item was a weak separator OR // this is the first item in a container, then we nuke the // current one QDomElement prev = e.previousSibling().toElement(); if ( prev.isNull() || ( prev.tagName() == tagSeparator && !prev.attribute( attrWeakSeparator ).isNull() ) || ( prev.tagName() == tagText ) ) { // the previous element was a weak separator or didn't exist base.removeChild( e ); continue; } } // the MergeLocal tag lets us specify where non-standard elements // of the local tree shall be merged in. After inserting the // elements we delete this element else if ( tag == tagMergeLocal ) { QDomNode it = additive.firstChild(); while ( !it.isNull() ) { QDomElement newChild = it.toElement(); it = it.nextSibling(); if (newChild.isNull() ) continue; if ( newChild.tagName() == tagText ) continue; if ( newChild.attribute( attrAlreadyVisited ) == attrOne ) continue; QString itAppend( newChild.attribute( attrAppend ) ); QString elemName( e.attribute( attrName ) ); if ( ( itAppend.isNull() && elemName.isEmpty() ) || ( itAppend == elemName ) ) { // first, see if this new element matches a standard one in // the global file. if it does, then we skip it as it will // be merged in, later QDomElement matchingElement = findMatchingElement( newChild, base ); if ( matchingElement.isNull() || newChild.tagName() == tagSeparator ) base.insertBefore( newChild, e ); } } base.removeChild( e ); continue; } // in this last case we check for a separator tag and, if not, we // can be sure that its a container --> proceed with child nodes // recursively and delete the just proceeded container item in // case its empty (if the recursive call returns true) else if ( tag != tagMerge ) { // handle the text tag if ( tag == tagText ) continue; QDomElement matchingElement = findMatchingElement( e, additive ); if ( !matchingElement.isNull() ) { matchingElement.setAttribute( attrAlreadyVisited, (uint)1 ); if ( mergeXML( e, matchingElement, actionCollection ) ) { base.removeChild( e ); continue; } // Merge attributes const QDomNamedNodeMap attribs = matchingElement.attributes(); const uint attribcount = attribs.count(); for(uint i = 0; i < attribcount; ++i) { const QDomNode node = attribs.item(i); e.setAttribute(node.nodeName(), node.nodeValue()); } continue; } else { // this is an important case here! We reach this point if the // "local" tree does not contain a container definition for // this container. However we have to call mergeXML recursively // and make it check if there are actions implemented for this // container. *If* none, then we can remove this container now if ( mergeXML( e, QDomElement(), actionCollection ) ) base.removeChild( e ); continue; } } } //here we append all child elements which were not inserted //previously via the LocalMerge tag n = additive.firstChild(); while ( !n.isNull() ) { QDomElement e = n.toElement(); n = n.nextSibling(); // Advance now so that we can safely delete e if (e.isNull()) continue; QDomElement matchingElement = findMatchingElement( e, base ); if ( matchingElement.isNull() ) { base.appendChild( e ); } } // do one quick check to make sure that the last element was not // a weak separator QDomElement last = base.lastChild().toElement(); if ( (last.tagName() == tagSeparator) && (!last.attribute( attrWeakSeparator ).isNull()) ) { base.removeChild( last ); } // now we check if we are empty (in which case we return "true", to // indicate the caller that it can delete "us" (the base element // argument of "this" call) bool deleteMe = true; n = base.firstChild(); while ( !n.isNull() ) { QDomElement e = n.toElement(); n = n.nextSibling(); // Advance now so that we can safely delete e if (e.isNull()) continue; tag = e.tagName(); if ( tag == tagAction ) { // if base contains an implemented action, then we must not get // deleted (note that the actionCollection contains both, // "global" and "local" actions if ( actionCollection->action( e.attribute( attrName ).utf8() ) ) { deleteMe = false; break; } } else if ( tag == tagSeparator ) { // if we have a separator which has *not* the weak attribute // set, then it must be owned by the "local" tree in which case // we must not get deleted either QString weakAttr = e.attribute( attrWeakSeparator ); if ( weakAttr.isEmpty() || weakAttr.toInt() != 1 ) { deleteMe = false; break; } } // in case of a merge tag we have unlimited lives, too ;-) else if ( tag == tagMerge ) { // deleteMe = false; // break; continue; } // a text tag is NOT enough to spare this container else if ( tag == tagText ) { continue; } // what's left are non-empty containers! *don't* delete us in this // case (at this position we can be *sure* that the container is // *not* empty, as the recursive call for it was in the first loop // which deleted the element in case the call returned "true" else { deleteMe = false; break; } } return deleteMe; }
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); }
static void setProperties(QDomDocument &doc, QDomElement &element, const Properties &props) { element.setAttribute("type", props.getPluginName().c_str()); std::vector<std::string> propertyNames; props.putPropertyNames(propertyNames); for (std::vector<std::string>::const_iterator it = propertyNames.begin(); it != propertyNames.end(); ++it) { QDomElement property; switch (props.getType(*it)) { case Properties::EBoolean: property = doc.createElement("boolean"); property.setAttribute("value", props.getBoolean(*it) ? "true" : "false"); break; case Properties::EInteger: property = doc.createElement("integer"); property.setAttribute("value", QString::number(props.getInteger(*it))); break; case Properties::EFloat: property = doc.createElement("float"); property.setAttribute("value", QString::number(props.getFloat(*it))); break; case Properties::EString: property = doc.createElement("string"); property.setAttribute("value", props.getString(*it).c_str()); break; case Properties::EAnimatedTransform: { const AnimatedTransform *trafo = props.getAnimatedTransform(*it); std::set<Float> times; trafo->collectKeyframes(times); property = doc.createElement("animation"); for (std::set<Float>::iterator it2 = times.begin(); it2 != times.end(); ++it2) { const Matrix4x4 &matrix = trafo->eval(*it2).getMatrix(); QDomElement trafoTag = doc.createElement("transform"); QDomElement matrixTag = doc.createElement("matrix"); QString value; for (int i=0; i<4; ++i) for (int j=0; j<4; ++j) value += QString("%1 ").arg(matrix(i, j)); matrixTag.setAttribute("value", value); trafoTag.setAttribute("time", *it2); trafoTag.appendChild(matrixTag); property.appendChild(trafoTag); } } break; case Properties::ETransform: { /* Captures the subset of transformations that are used by Mitsuba's perspective and orthographic camera classes */ property = doc.createElement("transform"); Transform trafo = props.getTransform(*it); if (trafo.hasScale()) { QDomElement scale = doc.createElement("scale"); Float valueX = trafo(Vector(1, 0, 0)).length(); Float valueY = trafo(Vector(0, 1, 0)).length(); Float valueZ = trafo(Vector(0, 0, 1)).length(); if (std::abs(1-valueX) < 1e-3f) valueX = 1.0f; if (std::abs(1-valueY) < 1e-3f) valueY = 1.0f; if (std::abs(1-valueZ) < 1e-3f) valueZ = 1.0f; scale.setAttribute("x", QString("%1").arg(valueX)); scale.setAttribute("y", QString("%1").arg(valueY)); scale.setAttribute("z", QString("%1").arg(valueZ)); property.appendChild(scale); trafo = trafo * Transform::scale(Vector(1.0f/valueX, 1.0f/valueY, 1.0f/valueZ)); } QDomElement lookAt = doc.createElement("lookat"); property.appendChild(lookAt); if (trafo.det3x3() < 0) { QDomElement scale = doc.createElement("scale"); scale.setAttribute("x", "-1"); property.insertBefore(scale, lookAt); } Point p = trafo(Point(0,0,0)); Point t = p + trafo(Vector(0,0,1)); Vector u = trafo(Vector(0,1,0)); lookAt.setAttribute("origin", QString("%1, %2, %3").arg(p.x).arg(p.y).arg(p.z)); lookAt.setAttribute("up", QString("%1, %2, %3").arg(u.x).arg(u.y).arg(u.z)); lookAt.setAttribute("target", QString("%1, %2, %3").arg(t.x).arg(t.y).arg(t.z)); } break; default: SLog(EError, "setProperties(): \"%s\": Unable to handle elements of type %i", (*it).c_str(), props.getType(*it)); } property.setAttribute("name", (*it).c_str()); element.appendChild(property); } }