예제 #1
0
void SearchView::requestEnded(QNetworkReply *e)
{
    for(int i=0; i<mWidgets.count(); i++)
        mWidgets.at(i)->hide();
    mWidgets.clear();

    QDomDocument xml;
    if (xml.setContent(e->readAll()))
    {
        QDomElement root = xml.documentElement();
        QDomNodeList topLevel = root.childNodes();

        /* Google search */
        if (topLevel.count() > 0)
        {
            SearchViewTitle *titleGoogleSearch = new SearchViewTitle("Google Search", mWidget);
            mWidgets.push_back(titleGoogleSearch);

            mGoogleSearch.clear();
        }

        for(int i=0; i<topLevel.count(); i++)
        {
            QDomElement suggestion = topLevel.at(i).toElement();
            QDomNodeList nodes = suggestion.childNodes();
            for(int j=0; j<nodes.count(); j++)
            {
                QDomElement s = nodes.at(j).toElement();
                if (s.tagName() == "suggestion")
                {
                    SearchViewItem *it = new SearchViewItem(s.attribute("data"), mWidget);
                    mWidgets.push_back(it);
                    mGoogleSearch.push_back(s.attribute("data"));
                }
            }
        }
    }

    if (mGoogleSearch.count() > 0)
    {
        SearchViewSeparator *sepGoogleSearch = new SearchViewSeparator(mWidget);
        mWidgets.push_back(sepGoogleSearch);
    }

    /* Service */
    SearchViewTitle *titleService = new SearchViewTitle("Services", mWidget);
    mWidgets.push_back(titleService);

    for(int i=0; i<mServices.keys().count(); i++)
    {
        QString s = "\"";
        s += mWord;
        s += "\" on ";
        s += mServices.keys().at(i);

        SearchViewItem *it = new SearchViewItem(s, mWidget);
        mWidgets.push_back(it);
    }

    if (mWord.isEmpty())
    {
        this->organize();
        return;
    }

    if (Application::getWindow()->getWebContainer()->getWebView()->url().isLocalFile())
    {
        SearchViewSeparator *sepService = new SearchViewSeparator(mWidget);
        mWidgets.push_back(sepService);

        /* On this page */
        SearchViewTitle *titleOnThisPage = new SearchViewTitle("On this page", mWidget);
        mWidgets.push_back(titleOnThisPage);

        QString oc = mWord;
        oc += " (";
        oc += QString::number(searchOccurrences());
        oc += " results)";
        SearchViewItem *it = new SearchViewItem(oc, mWidget);
        mWidgets.push_back(it);
    }

    /*Application::getWindow()->getWebContainer()->getWebView()->findText("", QWebPage::HighlightAllOccurrences);
    Application::getWindow()->getWebContainer()->getWebView()->findText(mWord, QWebPage::HighlightAllOccurrences);
    for(int i=0; i<mOnThisPage.count(); i++)
    {
        SearchViewItem *it = new SearchViewItem(mOnThisPage.at(i), mWidget);
        mWidgets.push_back(it);
    }*/
    this->organize();
}
예제 #2
0
/**
 * Create a PositionableLabel, then add to a target JLayeredPane
 * @param element Top level QDomElement to unpack.
 * @param o  an Editor as an Object
 */
/*public*/ void SignalHeadIconXml::load(QDomElement element, QObject* o) throw (Exception)
{
 // create the objects
 Editor* ed = (Editor*)o;
 l = new SignalHeadIcon(ed);
 QString name;

 QString attr = element.attribute("signalhead");
 if (attr == NULL) {
     log->error("incorrect information for signal head; must use signalhead name");
     ed->loadFailed();
     return;
 } else {
     name = attr;
 }

 SignalHead* sh = static_cast<SignalHeadManager*>(InstanceManager::getDefault("SignalHeadManager"))->getSignalHead(name);
 if (sh != NULL)
 {
  l->setSignalHead(new NamedBeanHandle<SignalHead*>(name, (SignalHead*)sh));
 }
 else
 {
  log->error("SignalHead named '"+attr+"' not found.");
 //    ed.loadFailed();
  return;
 }
 int rotation = 0;
 try
 {
  attr = element.attribute("rotate");
  rotation = attr.toInt();
 }
 catch (DataConversionException e)
 {
 }
 catch ( NullPointerException e)
 {  // considered normal if the attributes are not present
 }

 //@SuppressWarnings("unchecked")
 QDomNodeList aspects = element.childNodes();
 if (aspects.size()>0)
 {
  QDomElement icons = element.firstChildElement("icons");
  QDomElement elem = element;
  if (!icons.isNull())
  {
   // @SuppressWarnings("unchecked")
   QDomNodeList c = icons.childNodes();
   aspects = c;
   elem = icons;
  }
  for (int i=0; i<aspects.size(); i++)
  {
   QString aspect = aspects.at(i).toElement().tagName();
   NamedIcon* icon = loadIcon(l, aspect, elem, "SignalHead \""+name+"\": icon \""+aspect+"\" ", ed);
   if (icon!=NULL)
   {
    l->setIcon(_nameMap.value(aspect), icon);
   }
   else
   {
    log->info("SignalHead \""+name+"\": icon \""+aspect+"\" removed");
   }
  }
  log->debug(QString::number(aspects.size())+" icons loaded for "+l->getNameString());
 }
 else
 {
  // old style as attributes - somewhere around pre 2.5.4
  NamedIcon* icon = loadSignalIcon("red", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Red"), icon);
  }
  icon = loadSignalIcon("yellow", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Yellow"), icon);
  }
  icon = loadSignalIcon("green", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Green"), icon);
  }
  icon = loadSignalIcon("lunar", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Lunar"), icon);
  }
  icon = loadSignalIcon("held", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Red"), icon);
  }
  icon = loadSignalIcon("dark", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Dark"), icon);
  }
  icon = loadSignalIcon("flashred", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Flashing Red"), icon);
  }
  icon = loadSignalIcon("flashyellow", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Flashing Yellow"), icon);
  }
  icon = loadSignalIcon("flashgreen", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Flashing Green"), icon);
  }
  icon = loadSignalIcon("flashlunar", rotation, l, element, name, ed);
  if (icon!=NULL)
  {
   l->setIcon(tr("Flashing Lunar"), icon);
  }
 }
 QDomElement elem = element.firstChildElement("iconmaps");
 if (!elem.isNull())
 {
  attr = elem.attribute("family");
  if (attr!=NULL)
  {
   l->setFamily(attr);
  }
 }
// try
// {
 bool bok;
  attr = element.attribute("clickmode");
  if (attr!="") {
      l->setClickMode(attr.toInt(&bok));
  }
// }
 if(!bok)
 {
  log->error("Failed on clickmode attribute: "/*+e.getMessage()*/);
 }

 try
 {
  attr = element.attribute("litmode");
  if (attr!=NULL)
  {
   l->setLitMode(attr=="yes"?true:false);
  }
 }
 catch (DataConversionException e)
 {
  log->error("Failed on litmode attribute: "+e.getMessage());
 }
 // load individual item's option settings after editor has set its global settings
 loadCommonAttributes((Positionable*)l, Editor::SIGNALS, element);

 l->setDisplayLevel(Editor::SIGNALS);
 ed->putItem((Positionable*)l);
}
예제 #3
0
void
XSPFLoader::gotBody()
{
    QDomDocument xmldoc;
    bool namespaceProcessing = true;
    xmldoc.setContent( m_body, namespaceProcessing );
    QDomElement docElement( xmldoc.documentElement() );

    QString origTitle;
    QDomNodeList tracklist;
    QDomElement n = docElement.firstChildElement();
    for ( ; !n.isNull(); n = n.nextSiblingElement() )
    {
        if ( n.namespaceURI() == m_NS && n.localName() == "title" )
        {
            origTitle = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
        {
            m_creator = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "info" )
        {
            m_info = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "trackList" )
        {
            tracklist = n.childNodes();
        }
    }

    m_title = origTitle;
    if ( m_title.isEmpty() )
        m_title = tr( "New Playlist" );
    if ( !m_overrideTitle.isEmpty() )
        m_title = m_overrideTitle;

    bool shownError = false;
    for ( unsigned int i = 0; i < tracklist.length(); i++ )
    {
        QDomNode e = tracklist.at( i );

        QString artist, album, track, duration, annotation, url;
        QDomElement n = e.firstChildElement();
        for ( ; !n.isNull(); n = n.nextSiblingElement() )
        {
            if ( n.namespaceURI() == m_NS && n.localName() == "duration" )
            {
                duration = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "annotation" )
            {
                annotation = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
            {
                artist = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "album" )
            {
                album = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "title" )
            {
                track = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "url" )
            {
                url = n.text();
            }
        }

        if ( artist.isEmpty() || track.isEmpty() )
        {
            if ( !shownError )
            {
                emit error( InvalidTrackError );
                shownError = true;
            }
            continue;
        }

        query_ptr q = Tomahawk::Query::get( artist, track, album, uuid(), false );
        q->setDuration( duration.toInt() / 1000 );
        if ( !url.isEmpty() )
            q->setResultHint( url );

        m_entries << q;
    }

    if ( m_autoResolve )
    {
        for ( int i = m_entries.size() - 1; i >= 0; i-- )
            Pipeline::instance()->resolve( m_entries[ i ] );
    }

    if ( origTitle.isEmpty() && m_entries.isEmpty() )
    {
        emit error( ParseError );
        if ( m_autoCreate )
            deleteLater();
        return;
    }

    if ( m_autoCreate )
    {
        m_playlist = Playlist::create( SourceList::instance()->getLocal(),
                                       uuid(),
                                       m_title,
                                       m_info,
                                       m_creator,
                                       false,
                                       m_entries );

        // 10 minute default---for now, no way to change it
        new Tomahawk::XspfUpdater( m_playlist, 600000, m_autoUpdate, m_url.toString() );
        emit ok( m_playlist );
    }
    else
    {

        if( !m_entries.isEmpty() )
            emit tracks( m_entries );
    }

    if ( m_autoDelete )
        deleteLater();

}
예제 #4
0
void QgsSvgCache::replaceElemParams( QDomElement& elem, const QColor& fill, const QColor& outline, double outlineWidth )
{
  if ( elem.isNull() )
  {
    return;
  }

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

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

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

  QDomNodeList childList = elem.childNodes();
  int nChildren = childList.count();
  for ( int i = 0; i < nChildren; ++i )
  {
    QDomElement childElem = childList.at( i ).toElement();
    replaceElemParams( childElem, fill, outline, outlineWidth );
  }
}
예제 #5
0
const QString QgsLegacyHelpers::convertEditType( QgsVectorLayer::EditType editType, QgsEditorWidgetConfig& cfg, QgsVectorLayer* vl, const QString& name, const QDomElement editTypeElement )
{
  QString widgetType = "TextEdit"; // Fallback

  switch ( editType )
  {
    case QgsVectorLayer::ValueMap:
    {
      widgetType = "ValueMap";
      QDomNodeList valueMapNodes = editTypeElement.childNodes();

      for ( int j = 0; j < valueMapNodes.size(); j++ )
      {
        QDomElement value = valueMapNodes.at( j ).toElement();
        cfg.insert( value.attribute( "key" ), value.attribute( "value" ) );
      }
      break;
    }

    case QgsVectorLayer::EditRange:
    {
      widgetType = "Range";
      cfg.insert( "Style", "Edit" );
      cfg.insert( "Min", editTypeElement.attribute( "min" ).toFloat() );
      cfg.insert( "Max", editTypeElement.attribute( "max" ).toFloat() );
      cfg.insert( "Step", editTypeElement.attribute( "step" ).toFloat() );
      break;
    }

    case QgsVectorLayer::SliderRange:
    {
      widgetType = "SliderRange";
      cfg.insert( "Style", "Slider" );
      cfg.insert( "Min", editTypeElement.attribute( "min" ).toFloat() );
      cfg.insert( "Max", editTypeElement.attribute( "max" ).toFloat() );
      cfg.insert( "Step", editTypeElement.attribute( "step" ).toFloat() );
      break;
    }

    case QgsVectorLayer::DialRange:
    {
      widgetType = "DialRange";
      cfg.insert( "Style", "Dial" );
      cfg.insert( "Min", editTypeElement.attribute( "min" ).toFloat() );
      cfg.insert( "Max", editTypeElement.attribute( "max" ).toFloat() );
      cfg.insert( "Step", editTypeElement.attribute( "step" ).toFloat() );
      break;
    }

    case QgsVectorLayer::CheckBox:
    {
      widgetType = "CheckBox";
      cfg.insert( "CheckedState", editTypeElement.attribute( "checked" ) );
      cfg.insert( "UncheckedState", editTypeElement.attribute( "unchecked" ) );
      break;
    }

    case QgsVectorLayer::ValueRelation:
    {
      widgetType = "ValueRelation";
      cfg.insert( "AllowNull", editTypeElement.attribute( "allowNull" ) == "true" );
      cfg.insert( "OrderByValue", editTypeElement.attribute( "orderByValue" ) == "true" );
      cfg.insert( "AllowMulti", editTypeElement.attribute( "allowMulti", "false" ) == "true" );
      QString filterExpression;
      if ( editTypeElement.hasAttribute( "filterAttributeColumn" ) &&
           editTypeElement.hasAttribute( "filterAttributeValue" ) )
      {
        filterExpression = QString( "\"%1\"='%2'" )
                           .arg( editTypeElement.attribute( "filterAttributeColumn" ) )
                           .arg( editTypeElement.attribute( "filterAttributeValue" ) );
      }
      else
      {
        filterExpression  = editTypeElement.attribute( "filterExpression", QString::null );
      }
      cfg.insert( "FilterExpression", filterExpression );
      cfg.insert( "Layer", editTypeElement.attribute( "layer" ) );
      cfg.insert( "Key", editTypeElement.attribute( "key" ) );
      cfg.insert( "Value", editTypeElement.attribute( "value" ) );

      break;
    }

    case QgsVectorLayer::Calendar:
    {
      widgetType = "DateTime";
      cfg.insert( "display_format", editTypeElement.attribute( "dateFormat" ) );
      cfg.insert( "field_format", "yyyy-MM-dd" );
      break;
    }

    case QgsVectorLayer::Photo:
    {
      widgetType = "Photo";
      cfg.insert( "Width", editTypeElement.attribute( "widgetWidth" ).toInt() );
      cfg.insert( "Height", editTypeElement.attribute( "widgetHeight" ).toInt() );
      break;
    }

    case QgsVectorLayer::WebView:
    {
      widgetType = "WebView";
      cfg.insert( "Width", editTypeElement.attribute( "widgetWidth" ).toInt() );
      cfg.insert( "Height", editTypeElement.attribute( "widgetHeight" ).toInt() );
      break;
    }

    case QgsVectorLayer::Classification:
    {
      widgetType = "Classification";
      break;
    }

    case QgsVectorLayer::FileName:
    {
      widgetType = "FileName";
      break;
    }

    case QgsVectorLayer::Immutable:
    {
      widgetType = "TextEdit";
      cfg.insert( "IsMultiline", false );
      vl->setFieldEditable( vl->pendingFields().fieldNameIndex( name ), false );
      break;
    }

    case QgsVectorLayer::Hidden:
    {
      widgetType = "Hidden";
      break;
    }

    case QgsVectorLayer::LineEdit:
    {
      widgetType = "TextEdit";
      cfg.insert( "IsMultiline", false );
      break;
    }

    case QgsVectorLayer::TextEdit:
    {
      widgetType = "TextEdit";
      cfg.insert( "IsMultiline", true );
      cfg.insert( "UseHtml", false );
      break;
    }

    case QgsVectorLayer::Enumeration:
    {
      widgetType = "Enumeration";
      break;
    }

    case QgsVectorLayer::UniqueValues:
    {
      widgetType = "UniqueValues";
      cfg.insert( "Editable", false );
      break;
    }

    case QgsVectorLayer::UniqueValuesEditable:
    {
      widgetType = "UniqueValues";
      cfg.insert( "Editable", true );
      break;
    }

    case QgsVectorLayer::UuidGenerator:
    {
      widgetType = "UuidGenerator";
      break;
    }

    case QgsVectorLayer::Color:
    {
      widgetType = "Color";
      break;
    }

    case QgsVectorLayer::EditorWidgetV2: // Should not land here
      break;
  }

  return widgetType;
}
bool ParupaintPanvasInputOutput::loadORA(ParupaintPanvas * panvas, const QString & filename, QString & errorStr)
{
	Q_ASSERT(panvas);
	if(filename.isEmpty())
		return (errorStr = "Enter a filename to save to.").isEmpty();

#ifdef QT_XML_LIB

	KZip zip(filename);
	if(!zip.open(QIODevice::ReadOnly))
		return (errorStr = "Couldn't read ORA").isEmpty();

	const KArchiveDirectory * d = zip.directory();

	const auto * mte = d->entry("mimetype");
	if(!mte->isFile())
		return (errorStr = "Is not a file...").isEmpty();
	const KArchiveFile *mtf = static_cast<const KArchiveFile*>(mte);
	if(mtf->data() != "image/openraster")
		return (errorStr = "File is not ORA.").isEmpty();

	// okay, it's an ORA.
	const auto * stacke = d->entry("stack.xml");
	if(!stacke->isFile())
		return (errorStr = "Corrupted ORA?").isEmpty();
	const KArchiveFile *stf = static_cast<const KArchiveFile*>(stacke);
	
	QDomDocument doc;
	if(!doc.setContent(stf->data(), true))
		return (errorStr = "doc.setContent error").isEmpty();

	QDomElement element = doc.documentElement();
	QSize imagesize(element.attribute("w").toInt(),
			element.attribute("h").toInt());

	if(imagesize.isEmpty())
		return (errorStr = "Invalid size.").isEmpty();

	//okay, load the images
	
	// Oras can't be animation so we don't need
	// a special filtering thing
	panvas->setBackgroundColor(Qt::transparent);
	panvas->clearCanvas();
	panvas->resize(imagesize);

	const QDomElement stackroot = doc.documentElement().firstChildElement("stack");
	for(auto l = 0; l < stackroot.childNodes().count(); l++){
		QDomElement e = stackroot.childNodes().at(l).toElement();
		if(e.isNull()) continue;
		if(e.tagName() != "layer") continue;
		
		const QString name = e.attribute("name");
		const QString src = e.attribute("src");
		const qreal opacity = e.attribute("opacity").toDouble();
		const QString composite = e.attribute("composite-op");
		const bool visible = (e.attribute("visibility") == "visible");
		const qreal x = e.attribute("x").toDouble();
		const qreal y = e.attribute("y").toDouble();


		const auto * layer_entry = d->entry(src);
		if(!layer_entry->isFile()) continue;
		const KArchiveFile *layer_file = static_cast<const KArchiveFile*>(layer_entry);

		QByteArray byte_array = layer_file->data();

		QImage original_pic;
		original_pic.loadFromData(byte_array);

		QImage pic(imagesize, original_pic.format());
		pic.fill(0);
		QPainter paint(&pic);

		auto rp = original_pic.rect();
		auto rr = rp;
		rr.adjust(x, y, x, y);
		paint.drawImage(rr, original_pic, rp);
		
		paint.end();

		ParupaintLayer * layer = new ParupaintLayer(panvas);
		layer->setMode(composite);
		layer->setVisible(visible);
		layer->setName(name);

		layer->insertFrame(new ParupaintFrame(pic, layer, opacity));
		panvas->insertLayer(layer, 0);

	}
	if(true) return true;
#endif
	return (errorStr = "unable to load ora files").isEmpty();
}
예제 #7
0
void
XSPFLoader::gotBody()
{
    qDebug() << Q_FUNC_INFO;

    QDomDocument xmldoc;
    bool namespaceProcessing = true;
    xmldoc.setContent( m_body, namespaceProcessing );
    QDomElement docElement( xmldoc.documentElement() );

    QString origTitle;
    QDomNodeList tracklist;
    QDomElement n = docElement.firstChildElement();
    for ( ; !n.isNull(); n = n.nextSiblingElement() ) {
        if (n.namespaceURI() == m_NS && n.localName() == "title") {
            origTitle = n.text();
        } else if (n.namespaceURI() == m_NS && n.localName() == "creator") {
            m_creator = n.text();
        } else if (n.namespaceURI() == m_NS && n.localName() == "info") {
            m_info = n.text();
        } else if (n.namespaceURI() == m_NS && n.localName() == "trackList") {
            tracklist = n.childNodes();
        }
    }

    m_title = origTitle;
    if ( m_title.isEmpty() )
        m_title = tr( "New Playlist" );

    bool shownError = false;
    for ( unsigned int i = 0; i < tracklist.length(); i++ )
    {
        QDomNode e = tracklist.at( i );

        QString artist, album, track, duration, annotation;
        QDomElement n = e.firstChildElement();
        for ( ; !n.isNull(); n = n.nextSiblingElement() ) {
            if (n.namespaceURI() == m_NS && n.localName() == "duration") {
                duration = n.text();
            } else if (n.namespaceURI() == m_NS && n.localName() == "annotation") {
                annotation = n.text();
            } else if (n.namespaceURI() == m_NS && n.localName() == "creator") {
                artist = n.text();
            } else if (n.namespaceURI() == m_NS && n.localName() == "album") {
                album = n.text();
            } else if (n.namespaceURI() == m_NS && n.localName() == "title") {
                track = n.text();
            }
        }
        
        if( artist.isEmpty() || track.isEmpty() ) {
            if( !shownError ) {
                QMessageBox::warning( 0, tr( "Failed to save tracks" ), tr( "Some tracks in the playlist do not contain an artist and a title. They will be ignored." ), QMessageBox::Ok );
                shownError = true;
            }
            continue;
        }

        plentry_ptr p( new PlaylistEntry );
        p->setGuid( uuid() );
        p->setDuration( duration.toInt() / 1000 );
        p->setLastmodified( 0 );
        p->setAnnotation( annotation );

        p->setQuery( Tomahawk::Query::get( artist, track, album, uuid() ) );
        p->query()->setDuration( duration.toInt() / 1000 );
        m_entries << p;
    }

    if ( origTitle.isEmpty() && m_entries.isEmpty() )
    {
        if ( m_autoCreate )
        {
            QMessageBox::critical( 0, tr( "XSPF Error" ), tr( "This is not a valid XSPF playlist." ) );
            deleteLater();
            return;
        }
        else
        {
            emit failed();
            return;
        }
    }

    if ( m_autoCreate )
    {
        m_playlist = Playlist::create( SourceList::instance()->getLocal(),
                                       uuid(),
                                       m_title,
                                       m_info,
                                       m_creator,
                                       false );

        m_playlist->createNewRevision( uuid(), m_playlist->currentrevision(), m_entries );
        deleteLater();
    }

    emit ok( m_playlist );
}
예제 #8
0
bool
NetworkObject::loadGraphML(QString flnm)
{
  m_fileName = flnm;

  QDomDocument doc;
  QFile f(flnm.toLatin1().data());
  if (f.open(QIODevice::ReadOnly))
    {
      doc.setContent(&f);
      f.close();
    }

  QDomElement main = doc.documentElement();
  getKey(main);

//  m_log->insertPlainText("Node Attributes \n");
//  for(int i=0; i<m_nodeAtt.count(); i++)
//    m_log->insertPlainText("     "+m_nodeAtt[i]+"\n");
//  m_log->insertPlainText("\n");
//  m_log->insertPlainText("Edge Attributes \n");
//  for(int i=0; i<m_edgeAtt.count(); i++)
//    m_log->insertPlainText("     "+m_edgeAtt[i]+"\n");
//  m_log->insertPlainText("\n");
 
  QDomNodeList dlist = main.childNodes();
  for(int i=0; i<dlist.count(); i++)
    {
      if (dlist.at(i).isElement())
	{
	  QDomElement ele = dlist.at(i).toElement();
	  QString str = ele.nodeName();
	  if (str == "graph")
	    {
	      QDomNodeList nnodes = ele.elementsByTagName("node");
	      loadNodeInfo(nnodes);

	      QDomNodeList nedges = ele.elementsByTagName("edge");
	      loadEdgeInfo(nedges);
	    }
	}
    }

  //---------------------
  Vec bmin = m_vertexCenters[0];
  Vec bmax = m_vertexCenters[0];
  for(int i=0; i<m_vertexCenters.count(); i++)
    {
      bmin = StaticFunctions::minVec(bmin, m_vertexCenters[i]);
      bmax = StaticFunctions::maxVec(bmax, m_vertexCenters[i]);
    }
  m_centroid = (bmin + bmax)/2;
  
  m_enclosingBox[0] = Vec(bmin.x, bmin.y, bmin.z);
  m_enclosingBox[1] = Vec(bmax.x, bmin.y, bmin.z);
  m_enclosingBox[2] = Vec(bmax.x, bmax.y, bmin.z);
  m_enclosingBox[3] = Vec(bmin.x, bmax.y, bmin.z);
  m_enclosingBox[4] = Vec(bmin.x, bmin.y, bmax.z);
  m_enclosingBox[5] = Vec(bmax.x, bmin.y, bmax.z);
  m_enclosingBox[6] = Vec(bmax.x, bmax.y, bmax.z);
  m_enclosingBox[7] = Vec(bmin.x, bmax.y, bmax.z);


//  m_nX = (bmax.x - bmin.x) + 1;
//  m_nY = (bmax.y - bmin.y) + 1;
//  m_nZ = (bmax.z - bmin.z) + 1;
  m_nX = bmax.x;
  m_nY = bmax.y;
  m_nZ = bmax.z;

  if (!Global::batchMode())
    {
      QString str;
      str = QString("Grid Size : %1 %2 %3\n").arg(m_nX).arg(m_nY).arg(m_nZ);
      str += QString("Vertices : %1\n").arg(m_vertexCenters.count());
      str += QString("Edges : %1\n").arg(m_edgeNeighbours.count());
      str += QString("\n");
      str += QString("Vertex Attributes : %1\n").arg(m_vertexAttribute.count());
      for(int i=0; i<m_vertexAttribute.count(); i++)
	str += QString(" %1\n").arg(m_vertexAttribute[i].first);
      str += QString("\n");
      str += QString("Edge Attributes : %1\n").arg(m_edgeAttribute.count());
      for(int i=0; i<m_edgeAttribute.count(); i++)
	str += QString(" %1\n").arg(m_edgeAttribute[i].first);
      
      QMessageBox::information(0, "Network loaded", str);
    }

  m_Vatt = 0;
  m_Eatt = 0;
  m_Vminmax.clear();
  m_Eminmax.clear();
  m_userVminmax.clear();
  m_userEminmax.clear();

  for(int i=0; i<m_vertexAttribute.count(); i++)
    {
      float vmin = m_vertexAttribute[i].second[0];
      float vmax = m_vertexAttribute[i].second[0];
      for(int j=1; j<m_vertexAttribute[i].second.count(); j++)
	{
	  vmin = qMin((float)m_vertexAttribute[i].second[j], vmin);
	  vmax = qMax((float)m_vertexAttribute[i].second[j], vmax);
	}
      m_Vminmax.append(qMakePair(vmin, vmax));
      m_userVminmax.append(qMakePair((vmin+vmax)/2, vmax));
    }

  for(int i=0; i<m_edgeAttribute.count(); i++)
    {
      float emin = m_edgeAttribute[i].second[0];
      float emax = m_edgeAttribute[i].second[0];
      for(int j=1; j<m_edgeAttribute[i].second.count(); j++)
	{
	  emin = qMin((float)m_edgeAttribute[i].second[j], emin);
	  emax = qMax((float)m_edgeAttribute[i].second[j], emax);
	}
      m_Eminmax.append(qMakePair(emin, emax));
      m_userEminmax.append(qMakePair((emin+emax)/2, emax));
    }

//  QString str;
//  str += "Vertex\n";
//  for(int i=0; i<m_vertexAttribute.count(); i++)
//    {
//      str += m_vertexAttribute[i].first + QString("  %1 %2\n").\
//	arg(m_Vminmax[i].first).
//	arg(m_Vminmax[i].second);
//    }
//  str += "\n\nEdges\n";
//  for(int i=0; i<m_edgeAttribute.count(); i++)
//    {
//      str += m_edgeAttribute[i].first + QString("  %1 %2\n").\
//	arg(m_Eminmax[i].first).
//	arg(m_Eminmax[i].second);
//    }
//  QMessageBox::information(0, "", str);

  return true;
}
예제 #9
0
bool parseReportDetailSection(const QDomElement & elemSource, ORDetailSectionData & sectionTarget)
{
  if(elemSource.tagName() != "section")
    return FALSE;

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

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

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

      ORSectionData * sd = new ORSectionData();
      if(parseReportSection(elemThis, *sd) == TRUE)
      {
        sectionTarget.detail = sd;
        sectionTarget.trackTotal += sd->trackTotal;
        have_detail = TRUE;
      }
      else
        delete sd;
    }
    else
      qDebug("While parsing detail section encountered an unknown element: %s",(const char*)elemThis.tagName());
  }
  if(old_head || old_foot)
  {
    ORDetailGroupSectionData * gsec = new ORDetailGroupSectionData();
    gsec->name = sectionTarget.name;
    gsec->column = sectionTarget.key.column;
    gsec->head = old_head;
    gsec->foot = old_foot;
    sectionTarget.groupList.append(gsec);
  }
  return (have_name && have_detail && have_key);
}
예제 #10
0
void QgsEditFormConfig::readXml( const QDomNode& node )
{
  QDomNode editFormNode = node.namedItem( "editform" );
  if ( !editFormNode.isNull() )
  {
    QDomElement e = editFormNode.toElement();
    mUiFormPath = QgsProject::instance()->readPath( e.text() );
  }

  QDomNode editFormInitNode = node.namedItem( "editforminit" );
  if ( !editFormInitNode.isNull() )
  {
    mInitFunction = editFormInitNode.toElement().text();
  }

  QDomNode editFormInitCodeSourceNode = node.namedItem( "editforminitcodesource" );
  if ( !editFormInitCodeSourceNode.isNull() || ( !editFormInitCodeSourceNode.isNull() && !editFormInitCodeSourceNode.toElement().text().isEmpty() ) )
  {
    setInitCodeSource( static_cast< QgsEditFormConfig::PythonInitCodeSource >( editFormInitCodeSourceNode.toElement().text().toInt() ) );
  }

  QDomNode editFormInitCodeNode = node.namedItem( "editforminitcode" );
  if ( !editFormInitCodeNode.isNull() )
  {
    setInitCode( editFormInitCodeNode.toElement().text() );
  }

  // Temporary < 2.12 b/w compatibility "dot" support patch
  // @see: https://github.com/qgis/QGIS/pull/2498
  // For b/w compatibility, check if there's a dot in the function name
  // and if yes, transform it in an import statement for the module
  // and set the PythonInitCodeSource to CodeSourceDialog
  int dotPos = mInitFunction.lastIndexOf( '.' );
  if ( dotPos >= 0 ) // It's a module
  {
    setInitCodeSource( QgsEditFormConfig::CodeSourceDialog );
    setInitCode( QString( "from %1 import %2\n" ).arg( mInitFunction.left( dotPos ), mInitFunction.mid( dotPos + 1 ) ) );
    setInitFunction( mInitFunction.mid( dotPos + 1 ) );
  }

  QDomNode editFormInitFilePathNode = node.namedItem( "editforminitfilepath" );
  if ( !editFormInitFilePathNode.isNull() || ( !editFormInitFilePathNode.isNull() && !editFormInitFilePathNode.toElement().text().isEmpty() ) )
  {
    setInitFilePath( QgsProject::instance()->readPath( editFormInitFilePathNode.toElement().text() ) );
  }

  QDomNode fFSuppNode = node.namedItem( "featformsuppress" );
  if ( fFSuppNode.isNull() )
  {
    mSuppressForm = QgsEditFormConfig::SuppressDefault;
  }
  else
  {
    QDomElement e = fFSuppNode.toElement();
    mSuppressForm = static_cast< QgsEditFormConfig::FeatureFormSuppress >( e.text().toInt() );
  }

  // tab display
  QDomNode editorLayoutNode = node.namedItem( "editorlayout" );
  if ( editorLayoutNode.isNull() )
  {
    mEditorLayout = QgsEditFormConfig::GeneratedLayout;
  }
  else
  {
    if ( editorLayoutNode.toElement().text() == "uifilelayout" )
    {
      mEditorLayout = QgsEditFormConfig::UiFileLayout;
    }
    else if ( editorLayoutNode.toElement().text() == "tablayout" )
    {
      mEditorLayout = QgsEditFormConfig::TabLayout;
    }
    else
    {
      mEditorLayout = QgsEditFormConfig::GeneratedLayout;
    }
  }

  // tabs and groups display info
  clearTabs();
  QDomNode attributeEditorFormNode = node.namedItem( "attributeEditorForm" );
  QDomNodeList attributeEditorFormNodeList = attributeEditorFormNode.toElement().childNodes();

  for ( int i = 0; i < attributeEditorFormNodeList.size(); i++ )
  {
    QDomElement elem = attributeEditorFormNodeList.at( i ).toElement();

    QgsAttributeEditorElement *attributeEditorWidget = attributeEditorElementFromDomElement( elem, this );
    addTab( attributeEditorWidget );
  }


  //// TODO: MAKE THIS MORE GENERIC, SO INDIVIDUALL WIDGETS CAN NOT ONLY SAVE STRINGS
  /// SEE QgsEditorWidgetFactory::writeConfig

  QDomElement widgetsElem = node.namedItem( "widgets" ).toElement();

  QDomNodeList widgetConfigsElems = widgetsElem.childNodes();

  for ( int i = 0; i < widgetConfigsElems.size(); ++i )
  {
    QgsEditorWidgetConfig cfg;

    QDomElement wdgElem = widgetConfigsElems.at( i ).toElement();

    QDomElement cfgElem = wdgElem.namedItem( "config" ).toElement();

    for ( int j = 0; j < cfgElem.attributes().size(); ++j )
    {
      QDomAttr attr = cfgElem.attributes().item( j ).toAttr();
      cfg.insert( attr.name(), attr.value() );
    }

    QDomNodeList optionElements = cfgElem.elementsByTagName( "option" );
    for ( int j = 0; j < optionElements.size(); ++j )
    {
      QString key = optionElements.at( j ).toElement().attribute( "key" );
      QString value = optionElements.at( j ).toElement().attribute( "value" );
      cfg.insert( key, value );
    }

    setWidgetConfig( wdgElem.attribute( "name" ), cfg );
  }
  //// END TODO
}
예제 #11
0
void
NetworkObject::getKey(QDomElement main)
{
  m_nodeAtt.clear();
  m_edgeAtt.clear();

  QDomNodeList dlist = main.childNodes();
  for(int i=0; i<dlist.count(); i++)
    {
      if (dlist.at(i).isElement())
	{
	  QDomElement ele = dlist.at(i).toElement();
	  QString str = ele.nodeName();
	  if (str == "key")
	    {
	      QDomNamedNodeMap attr = ele.attributes();
	      int nattr = attr.count();
	      bool isnode = false;
	      bool isedge = false;
	      for(int na=0; na<nattr; na++)
		{
		  QDomNode node = attr.item(na);
		  QString name = node.nodeName();
		  QString val = node.nodeValue();
		  if (val == "node") { isnode = true; break; }
		  if (val == "edge") { isedge = true; break; }
		}
	      for(int na=0; na<nattr; na++)
		{
		  QDomNode node = attr.item(na);
		  QString name = node.nodeName();
		  QString val = node.nodeValue();
		  if (isnode && name == "id")
		    {
		      if (val != "x" &&
			  val != "y" &&
			  val != "z")
			m_nodeAtt << val;
		    }
		  if (isedge && name == "id")
		    m_edgeAtt << val;
		}
	    }
	}
    }

  m_vertexRadiusAttribute = -1;
  m_edgeRadiusAttribute = -1;

  for(int i=0; i<m_nodeAtt.count(); i++)
    {
      if (m_nodeAtt[i].contains("radius", Qt::CaseInsensitive) ||
	  m_nodeAtt[i].contains("diameter", Qt::CaseInsensitive))
	{
	  m_vertexRadiusAttribute = i;
	  break;
	}
    }
  for(int i=0; i<m_edgeAtt.count(); i++)
    {
      if (m_edgeAtt[i].contains("radius", Qt::CaseInsensitive) ||
	  m_edgeAtt[i].contains("diameter", Qt::CaseInsensitive))
	{
	  m_edgeRadiusAttribute = i;
	  break;
	}
    }
}
예제 #12
0
KReportDetailSectionData::KReportDetailSectionData(const QDomElement &elemSource, KReportDocument *report)
 : QObject(report)
{
    m_pageBreak = BreakNone;
    m_detailSection = 0;
    m_valid = false;
    //kreportDebug() << elemSource.tagName();
    if (elemSource.tagName() != QLatin1String("report:detail")) {
        return;
    }

    QDomNodeList sections = elemSource.childNodes();

    for (int nodeCounter = 0; nodeCounter < sections.count(); nodeCounter++) {
        QDomElement elemThis = sections.item(nodeCounter).toElement();

        if (elemThis.tagName() == QLatin1String("report:group")) {
            KReportDetailGroupSectionData * dgsd = new KReportDetailGroupSectionData();

            if ( elemThis.hasAttribute( QLatin1String("report:group-column") ) ) {
                dgsd->m_column = elemThis.attribute( QLatin1String("report:group-column") );
            }

            if ( elemThis.hasAttribute( QLatin1String("report:group-page-break") ) ) {
                QString s = elemThis.attribute( QLatin1String("report:group-page-break") );
                if ( s == QLatin1String("after-footer") ) {
                    dgsd->m_pagebreak = KReportDetailGroupSectionData::BreakAfterGroupFooter;
                } else if ( s == QLatin1String("before-header") ) {
                    dgsd->m_pagebreak = KReportDetailGroupSectionData::BreakBeforeGroupHeader;
                } else {
                    dgsd->m_pagebreak = KReportDetailGroupSectionData::BreakNone;
                }
            }

            if (elemThis.attribute(QLatin1String("report:group-sort"), QLatin1String("ascending")) == QLatin1String("ascending")) {
                dgsd->m_sort = Qt::AscendingOrder;
            } else {
                dgsd->m_sort = Qt::DescendingOrder;
            }
            
            for ( QDomElement e = elemThis.firstChildElement( QLatin1String("report:section") ); ! e.isNull(); e = e.nextSiblingElement( QLatin1String("report:section") ) ) {
                QString s = e.attribute( QLatin1String("report:section-type") );
                if ( s == QLatin1String("group-header") ) {
                    KReportSectionData * sd = new KReportSectionData(e, report);
                    if (sd->isValid()) {
                        dgsd->m_groupHeader = sd;
                    } else {
                        delete sd;
                    }
                } else if ( s == QLatin1String("group-footer") ) {
                    KReportSectionData * sd = new KReportSectionData(e, report);
                    if (sd->isValid()) {
                        dgsd->m_groupFooter = sd;
                    } else {
                        delete sd;
                    }
                }
            }
            m_groupList.append(dgsd);
            KReportData::SortedField s;
            s.field = dgsd->m_column;
            s.order = dgsd->m_sort;
            m_sortedFields.append(s);
	    
        } else if (elemThis.tagName() == QLatin1String("report:section") && elemThis.attribute(QLatin1String("report:section-type")) == QLatin1String("detail")) {
            KReportSectionData * sd = new KReportSectionData(elemThis, report);
            if (sd->isValid()) {
                m_detailSection = sd;
            } else
                delete sd;
        } else {
            kreportWarning() << "While parsing detail section encountered an unknown element: " << elemThis.tagName();
        }
    }
    
    m_valid = true;
}
예제 #13
0
int XmlGspInterface::readFile(const QString &fileName)
{
	QFile* file = new QFile(fileName);
	QFileInfo fi(fileName);
	QString path = (fi.path().length() > 3) ? QString(fi.path() + "/") : fi.path();

	QFileInfo si(QString::fromStdString(_schemaName));
	QString schemaPath(si.absolutePath() + "/");

	if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
	{
		std::cout << "XmlGspInterface::readFile() - Can't open xml-file " <<
		fileName.toStdString() << "." << std::endl;
		delete file;
		return 0;
	}
	if (!checkHash(fileName))
	{
		delete file;
		return 0;
	}

	QDomDocument doc("OGS-PROJECT-DOM");
	doc.setContent(file);
	QDomElement docElement = doc.documentElement(); //OpenGeoSysProject
	if (docElement.nodeName().compare("OpenGeoSysProject"))
	{
		std::cout << "XmlGspInterface::readFile() - Unexpected XML root." << std::endl;
		delete file;
		return 0;
	}

	QDomNodeList fileList = docElement.childNodes();

	for(int i = 0; i < fileList.count(); i++)
	{
		const QString file_node(fileList.at(i).nodeName());
		if (file_node.compare("geo") == 0)
		{
			XmlGmlInterface gml(_project, schemaPath.toStdString() + "OpenGeoSysGLI.xsd");
			const QDomNodeList childList = fileList.at(i).childNodes();
			for(int j = 0; j < childList.count(); j++)
			{
				const QDomNode child_node (childList.at(j));
				if (child_node.nodeName().compare("file") == 0)
				{
					std::cout << "path: " << path.toStdString() << "#" << std::endl;
					std::cout << "file name: " << (child_node.toElement().text()).toStdString() << "#" << std::endl;
					gml.readFile(QString(path + child_node.toElement().text()));
				}
			}
		}
		else if (file_node.compare("stn") == 0)
		{
			XmlStnInterface stn(_project, schemaPath.toStdString() + "OpenGeoSysSTN.xsd");
			const QDomNodeList childList = fileList.at(i).childNodes();
			for(int j = 0; j < childList.count(); j++)
				if (childList.at(j).nodeName().compare("file") == 0)
					stn.readFile(QString(path + childList.at(j).toElement().text()));
		}
		else if (file_node.compare("msh") == 0)
		{
			const std::string msh_name = path.toStdString() +
			                       fileList.at(i).toElement().text().toStdString();
			FileIO::MeshIO meshIO;
			MeshLib::Mesh* msh = meshIO.loadMeshFromFile(msh_name);
			_project->addMesh(msh);
		}
	}

	return 1;
}
예제 #14
0
파일: converter.cpp 프로젝트: KDE/okular
bool Converter::convertTable( const QDomElement &element )
{
  /**
   * Find out dimension of the table
   */
  int rowCounter = 0;
  int columnCounter = 0;

  QQueue<QDomNode> nodeQueue;
  enqueueNodeList( nodeQueue, element.childNodes() );
  while ( !nodeQueue.isEmpty() ) {
    QDomElement el = nodeQueue.dequeue().toElement();
    if ( el.isNull() )
      continue;

    if ( el.tagName() == QLatin1String( "table-row" ) ) {
      rowCounter++;

      int counter = 0;
      QDomElement columnElement = el.firstChildElement();
      while ( !columnElement.isNull() ) {
        if ( columnElement.tagName() == QLatin1String( "table-cell" ) ) {
          counter++;
        }
        columnElement = columnElement.nextSiblingElement();
      }

      columnCounter = qMax( columnCounter, counter );
    } else if ( el.tagName() == QLatin1String( "table-header-rows" ) ) {
      enqueueNodeList( nodeQueue, el.childNodes() );
    }
  }

  /**
   * Create table
   */
  QTextTable *table = mCursor->insertTable( rowCounter, columnCounter );
  mCursor->movePosition( QTextCursor::End );

  /**
   * Fill table
   */
  nodeQueue.clear();
  enqueueNodeList( nodeQueue, element.childNodes() );

  QTextTableFormat tableFormat;

  rowCounter = 0;
  while ( !nodeQueue.isEmpty() ) {
    QDomElement el = nodeQueue.dequeue().toElement();
    if ( el.isNull() )
      continue;

    if ( el.tagName() == QLatin1String( "table-row" ) ) {

      int columnCounter = 0;
      QDomElement columnElement = el.firstChildElement();
      while ( !columnElement.isNull() ) {
        if ( columnElement.tagName() == QLatin1String( "table-cell" ) ) {
          const StyleFormatProperty property = mStyleInformation->styleProperty( columnElement.attribute( QStringLiteral("style-name") ) );

          QTextBlockFormat format;
          property.applyTableCell( &format );

          QDomElement paragraphElement = columnElement.firstChildElement();
          while ( !paragraphElement.isNull() ) {
            if ( paragraphElement.tagName() == QLatin1String( "p" ) ) {
              QTextTableCell cell = table->cellAt( rowCounter, columnCounter );
              // Insert a frame into the cell and work on that, so we can handle
              // different parts of the cell having different block formatting
              QTextCursor cellCursor = cell.lastCursorPosition();
              QTextFrameFormat frameFormat;
              frameFormat.setMargin( 1 ); // TODO: this shouldn't be hard coded
              QTextFrame *frame = cellCursor.insertFrame( frameFormat );
              QTextCursor frameCursor = frame->firstCursorPosition();
              frameCursor.setBlockFormat( format );

              if ( !convertParagraph( &frameCursor, paragraphElement, format ) )
                return false;
            } else if ( paragraphElement.tagName() == QLatin1String( "list" ) ) {
              QTextTableCell cell = table->cellAt( rowCounter, columnCounter );
              // insert a list into the cell
              QTextCursor cellCursor = cell.lastCursorPosition();
              if ( !convertList( &cellCursor, paragraphElement ) ) {
                return false;
              }
            }

            paragraphElement = paragraphElement.nextSiblingElement();
          }
          columnCounter++;
        }
        columnElement = columnElement.nextSiblingElement();
      }

      rowCounter++;
    } else if ( el.tagName() == QLatin1String( "table-column" ) ) {
      const StyleFormatProperty property = mStyleInformation->styleProperty( el.attribute( QStringLiteral("style-name") ) );
      const QString tableColumnNumColumnsRepeated = el.attribute( QStringLiteral("number-columns-repeated"), QStringLiteral("1") );
      int numColumnsToApplyTo = tableColumnNumColumnsRepeated.toInt();
      for (int i = 0; i < numColumnsToApplyTo; ++i) {
        property.applyTableColumn( &tableFormat );
      }
    }
  }

  table->setFormat( tableFormat );

  return true;
}
SimpleParameterEdit::SimpleParameterEdit(SimpleParameter::Type _type,
					 Miro::CFG::Parameter const& _parameter,
					 QDomNode& _parentNode, 
					 QDomNode& _node,
					 ItemXML * _parentItem, 
					 ItemXML * _item,
					 QWidget * _parent, 
					 const char * _name) :
  Super(_parameter, _parentNode, _node, 
	_parentItem, _item,
	_parent, _name),
  config_(ConfigFile::instance()),
  type_(_type),
  lineEdit_(NULL),
  textEdit_(NULL),
  typeBox_(NULL),
  listBox_(NULL),
  typeBoxModified_(false),
  listBoxModified_(false)
{
  if (parameter_.type_ == "Miro::Enumeration" || 
      parameter_.type_ == "Enumeration") {
    typeBox_ = new QComboBox(_parent, "type_box");
    editWidget_ = typeBox_;
  } else if (parameter_.type_ == "Miro::EnumerationMultiple" || 
	     parameter_.type_ == "EnumerationMultiple") {
    listBox_ = new Q3ListBox(_parent, "list_box");
    editWidget_ = listBox_;
  } else if (parameter_.type_ == "Miro::Text" ||
	     parameter_.type_ == "Text") {
    textEdit_ = new QTextEdit(_parent, "text_edit");
    textEdit_->setAcceptRichText(false);
    textEdit_->setAutoFormatting(false);
    editWidget_ = textEdit_;
  } else {
    lineEdit_ = new QLineEdit(_parent, "line_edit");
    editWidget_ = lineEdit_;
  }

  assert(!parentNode_.isNull());

  if (lineEdit_ != NULL) {
    // customize lineEdit for typesafe editing
    QValidator *  v = NULL;
    switch (_type) {
    case SimpleParameter::BOOL:
      v = new MyBoolValidator(this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::CHAR:
      lineEdit_->setMaxLength(1);
      break;
    case SimpleParameter::SHORT:
      v = new MyIntValidator(SHRT_MIN, SHRT_MAX, this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::USHORT:
      v = new MyIntValidator(0, USHRT_MAX, this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::INT:
      v = new MyIntValidator(INT_MIN + 1, INT_MAX - 1, this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::UINT:
      v = new MyIntValidator(0, INT_MAX - 1, this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::LONG:
      v = new MyIntValidator(INT_MIN + 1, INT_MAX - 1, this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::ULONG:
      v = new MyIntValidator(0, INT_MAX - 1, this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::FLOAT:
      v = new MyFloatValidator(this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::DOUBLE:
      v = new MyDoubleValidator(this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::ANGLE:
      v = new MyDoubleValidator(this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::MIRO_ANGLE:
      v = new MyDoubleValidator(-180., 180., 6, this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::STRING:
      break;
    case SimpleParameter::ACE_TIME_VALUE:
      v = new MyDoubleValidator(0, ULONG_MAX, 6, this);
      lineEdit_->setValidator(v);
      break;
    case SimpleParameter::ACE_INET_ADDR:
      break;
    default:
      break;
    }

    // connect validator, if we have one
    if (v) {
      QObject * p = _parent;
      while (p != NULL) {
	if (dynamic_cast<ParameterDialog *>(p) != NULL) {
	  connect(v, SIGNAL(acceptable(bool)), p, SLOT(accept(bool)));
	  break;
	}
	p = p->parent();
      }
    }

    // add default as tooltip
    if (!parameter_.default_.isEmpty()) {
      QToolTip::add(lineEdit_, QString("default: ") + parameter_.default_);
    }

    // set current value
    if (!node_.isNull()) {
      QDomElement e = node_.toElement();
      if (!e.isNull() && e.hasAttribute("value")) {
	lineEdit_->setText(e.attribute("value"));
      }
    }

    // set lineEdit to unedited
    lineEdit_->setEdited(false);
  }
  else if (textEdit_ != NULL) {
    QDomElement e = node_.toElement();
    if (!e.isNull()) {
      QDomNodeList l = e.childNodes();
      unsigned int i;
      for (i = 0; i < l.length(); ++i) {
	if (l.item(i).isText()) {
	  QDomText t = l.item(i).toText();
	  textEditText_ = t.data();
	  textEdit_->setPlainText(textEditText_);
	  break;
	}
      }
    }
  }
  else if (typeBox_ != NULL) {
    vector<string> stringvec;
    switch (_type) {

    case SimpleParameter::ENUMERATION:
      // init combo box
      typeBox_->setEditable(FALSE);
      stringvec = fullDef2StringVector(parameter_.fullDefault_);
      for (vector<string>::const_iterator i= stringvec.begin(); i!=stringvec.end(); ++i)
	typeBox_->insertItem(i->c_str());

      // set current value
      if (!node_.isNull()) {
	QDomElement e = node_.toElement();
	if (!e.isNull() && e.hasAttribute("value")) {
	  typeBox_->setCurrentText(e.attribute("value"));
	}
      } else {
	typeBox_->setCurrentText(parameter_.default_);
      }

      // connect to function, so we recognize, if value is changed
      connect(typeBox_, SIGNAL(activated(const QString&)), this, SLOT(typeBoxModified()));
      break;

    case SimpleParameter::ENUMERATIONMULTIPLE:
      // init list box
      listBox_->setSelectionMode(Q3ListBox::Multi);
      stringvec = fullDef2StringVector(parameter_.fullDefault_);
      for (vector<string>::const_iterator i= stringvec.begin(); i!=stringvec.end(); ++i)
	listBox_->insertItem(i->c_str());

      // set current value
      listBox_->clearSelection();
      if (!node_.isNull()) {
	QDomElement e = node_.toElement();
	if (!e.isNull() && e.hasAttribute("value")) {
	  QString tmp1 = e.attribute("value");
	  std::vector<std::string> tmp2 = tokenizer(std::string(tmp1.latin1()));
	  for (std::vector<std::string>::const_iterator i=tmp2.begin(); i!=tmp2.end(); ++i) {
	    for (unsigned int j=0; j!=listBox_->count(); ++j) {
	      if (listBox_->text(j) == QString(i->c_str()))
		listBox_->setSelected(j, TRUE);
	    }
	  }
	}
      } else {
	std::vector<std::string> tmp2 = tokenizer(std::string(parameter_.default_.latin1()));
	for (std::vector<std::string>::const_iterator i=tmp2.begin(); i!=tmp2.end(); ++i) {
	  for (unsigned int j=0; j!=listBox_->count(); ++j) {
	    if (listBox_->text(j) == QString(i->c_str()))
	      listBox_->setSelected(j, TRUE);
	  }
	}
      }

      // connect to function, so we recognize, if value is changed
      connect(listBox_, SIGNAL(selectionChanged()), this, SLOT(listBoxModified()));
      break;

    default:
      break;
    }
  }
예제 #16
0
bool parseReport(const QDomElement & elemSource, ORReportData & reportTarget)
{
  if(elemSource.tagName() != "report")
  {
    qDebug("QDomElement passed to parseReport() was not <report> tag");
    return FALSE;
  }

  double d = 0.0;
  bool valid = FALSE;

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

  return TRUE;
}
예제 #17
0
bool
TrisetObject::fromDomElement(QDomElement de)
{
  clear();

  bool ok = false;

  QString name;
  QDomNodeList dlist = de.childNodes();
  for(int i=0; i<dlist.count(); i++)
    {
      QDomElement dnode = dlist.at(i).toElement();
      QString str = dnode.toElement().text();
      if (dnode.tagName() == "name")
	ok = load(str);
      else if (dnode.tagName() == "position")
	{
	  QStringList xyz = str.split(" ");
	  float x = 0;
	  float y = 0;
	  float z = 0;
	  if (xyz.size() > 0) x = xyz[0].toFloat();
	  if (xyz.size() > 1) y  = xyz[1].toFloat();
	  if (xyz.size() > 2) z  = xyz[2].toFloat();
	  m_position = Vec(x,y,z);
	}
      else if (dnode.tagName() == "scale")
	{
	  QStringList xyz = str.split(" ");
	  float x = 0;
	  float y = 0;
	  float z = 0;
	  if (xyz.size() > 0) x = xyz[0].toFloat();
	  if (xyz.size() > 1) y  = xyz[1].toFloat();
	  if (xyz.size() > 2) z  = xyz[2].toFloat();
	  m_scale = Vec(x,y,z);
	}
      else if (dnode.tagName() == "opacity")
	m_opacity = str.toFloat();
      else if (dnode.tagName() == "color")
	{
	  QStringList xyz = str.split(" ");
	  float x = 0;
	  float y = 0;
	  float z = 0;
	  if (xyz.size() > 0) x = xyz[0].toFloat();
	  if (xyz.size() > 1) y  = xyz[1].toFloat();
	  if (xyz.size() > 2) z  = xyz[2].toFloat();
	  m_color = Vec(x,y,z);
	}
      else if (dnode.tagName() == "cropcolor")
	{
	  QStringList xyz = str.split(" ");
	  float x = 0;
	  float y = 0;
	  float z = 0;
	  if (xyz.size() > 0) x = xyz[0].toFloat();
	  if (xyz.size() > 1) y  = xyz[1].toFloat();
	  if (xyz.size() > 2) z  = xyz[2].toFloat();
	  m_cropcolor = Vec(x,y,z);
	}
      else if (dnode.tagName() == "ambient")
	m_ambient = str.toFloat();
      else if (dnode.tagName() == "diffuse")
	m_diffuse = str.toFloat();
      else if (dnode.tagName() == "specular")
	m_specular = str.toFloat();
      else if (dnode.tagName() == "pointmode")
	{
	  if (str == "yes" || str == "1") m_pointMode = true;
	  else m_pointMode = false;
	}
      else if (dnode.tagName() == "pointsize")
	m_pointSize = str.toFloat();
      else if (dnode.tagName() == "pointstep")
	m_pointStep = str.toFloat();
      else if (dnode.tagName() == "blendmode")
	{
	  if (str == "yes" || str == "1") m_pointMode = true;
	  else m_blendMode = false;
	}
      else if (dnode.tagName() == "screendoor")
	{
	  if (str == "yes" || str == "1") m_screenDoor = true;
	  else m_screenDoor = false;
	}
      else if (dnode.tagName() == "flipnormals")
	{
	  if (str == "yes" || str == "1") m_flipNormals = true;
	  else m_flipNormals = false;
	}
    }

  return ok;
}
예제 #18
0
bool parseReportGraphData(const QDomElement & elemSource, ORGraphData & graphTarget)
{
  if(elemSource.tagName() != "graph")
    return FALSE;

  bool have_data = FALSE;
  bool have_rect = FALSE;
  bool have_series = FALSE;

  graphTarget.title.string = QString::null;
  graphTarget.dataaxis.title.string = QString::null;
  graphTarget.dataaxis.title.font_defined = FALSE;
  graphTarget.dataaxis.column = QString::null;
  graphTarget.dataaxis.font_defined = FALSE;
  graphTarget.valueaxis.title.string = QString::null;
  graphTarget.valueaxis.min = 0;
  graphTarget.valueaxis.max = 100;
  graphTarget.valueaxis.autominmax = TRUE;
  graphTarget.valueaxis.font_defined = FALSE;

  graphTarget.series.setAutoDelete(TRUE);

  QDomNodeList nlist = elemSource.childNodes();
  for(int nodeCounter = 0; nodeCounter < nlist.count(); nodeCounter++)
  {
    QDomElement elemThis = nlist.item(nodeCounter).toElement();
    if(elemThis.tagName() == "data")
      have_data = parseReportData(elemThis, graphTarget.data);
    else if(elemThis.tagName() == "font")
      parseReportFont(elemThis, graphTarget.font);
    else if(elemThis.tagName() == "rect")
      have_rect = parseReportRect(elemThis, graphTarget.rect);
    else if(elemThis.tagName() == "title")
      parseReportTitleData(elemThis, graphTarget.title);
    else if(elemThis.tagName() == "dataaxis")
    {
      if(!parseReportDataAxisData(elemThis, graphTarget.dataaxis))
      {
        graphTarget.dataaxis.title.string = QString::null;
        graphTarget.dataaxis.title.font_defined = FALSE;
        graphTarget.dataaxis.column = QString::null;
        graphTarget.dataaxis.font_defined = FALSE;
      }
    }
    else if(elemThis.tagName() == "valueaxis")
    {
      if(!parseReportValueAxisData(elemThis, graphTarget.valueaxis))
      {
        graphTarget.valueaxis.title.string = QString::null;
        graphTarget.valueaxis.min = 0;
        graphTarget.valueaxis.max = 100;
        graphTarget.valueaxis.autominmax = TRUE;
        graphTarget.valueaxis.font_defined = FALSE;
      }
    }
    else if(elemThis.tagName() == "series")
    {
      ORSeriesData * orsd = new ORSeriesData();
      if(parseReportSeriesData(elemThis, *orsd))
      {
        graphTarget.series.append(orsd);
        have_series = TRUE;
      }
      else
        delete orsd;
      orsd = 0;
    }
    else
      qDebug("While parsing graph encountered an unknown element: %s",(const char*)elemThis.tagName());
  }

  if(have_data && have_rect && have_series)
    return TRUE;
  return FALSE;
}
예제 #19
0
void TrackContainer::loadSettings( const QDomElement & _this )
{
	bool journalRestore = _this.parentNode().nodeName() == "journaldata";
	if( journalRestore )
	{
		clearAllTracks();
	}

	static QProgressDialog * pd = NULL;
	bool was_null = ( pd == NULL );
	int start_val = 0;
	if( !journalRestore && engine::hasGUI() )
	{
		if( pd == NULL )
		{
			pd = new QProgressDialog( tr( "Loading project..." ),
						tr( "Cancel" ), 0,
						_this.childNodes().count(),
						engine::mainWindow() );
			pd->setWindowModality( Qt::ApplicationModal );
			pd->setWindowTitle( tr( "Please wait..." ) );
			pd->show();
		}
		else
		{
			start_val = pd->value();
			pd->setMaximum( pd->maximum() +
						_this.childNodes().count() );
		}
	}

	QDomNode node = _this.firstChild();
	while( !node.isNull() )
	{
		if( pd != NULL )
		{
			pd->setValue( pd->value() + 1 );
			QCoreApplication::instance()->processEvents(
						QEventLoop::AllEvents, 100 );
			if( pd->wasCanceled() )
			{
				break;
			}
		}

		if( node.isElement() &&
			!node.toElement().attribute( "metadata" ).toInt() )
		{
			track::create( node.toElement(), this );
		}
		node = node.nextSibling();
	}

	if( pd != NULL )
	{
		pd->setValue( start_val + _this.childNodes().count() );
		if( was_null )
		{
			delete pd;
			pd = NULL;
		}
	}
}
예제 #20
0
bool parseReportBackground(const QDomElement & elemSource, ORBackgroundData & bgTarget)
{
  if(elemSource.tagName() != "background")
    return FALSE;

  bgTarget.enabled = false;
  bgTarget.staticImage = true;
  bgTarget.image = QString::null;
  bgTarget.data.query = QString::null;
  bgTarget.data.column = QString::null;
  bgTarget.opacity = 25;
  bgTarget.mode = "clip";
  bgTarget.rect = QRect();

  int halign = Qt::AlignLeft;
  int valign = Qt::AlignTop;
  bool valid_rect = true;

  QDomNodeList nlist = elemSource.childNodes();
  for(int nodeCounter = 0; nodeCounter < nlist.count(); nodeCounter++)
  {
    QDomElement elemThis = nlist.item(nodeCounter).toElement();
    if(elemThis.tagName() == "image")
      bgTarget.image = elemThis.text();
    else if(elemThis.tagName() == "mode")
      bgTarget.mode = elemThis.text();
    else if(elemThis.tagName() == "data")
      bgTarget.staticImage = !parseReportData(elemThis, bgTarget.data);
    else if(elemThis.tagName() == "left")
      halign = Qt::AlignLeft;
    else if(elemThis.tagName() == "hcenter")
      halign = Qt::AlignHCenter;
    else if(elemThis.tagName() == "right")
      halign = Qt::AlignRight;
    else if(elemThis.tagName() == "top")
      valign = Qt::AlignTop;
    else if(elemThis.tagName() == "vcenter")
      valign = Qt::AlignVCenter;
    else if(elemThis.tagName() == "bottom")
      valign = Qt::AlignBottom;
    else if(elemThis.tagName() == "rect")
      valid_rect = parseReportRect(elemThis, bgTarget.rect);
    else if(elemThis.tagName() == "opacity")
    {
      bool valid = false;
      int i = elemThis.text().toInt(&valid);
      if(valid) {
        if(i < 0)
          i = 0;
        if(i > 255)
          i = 255;
        bgTarget.opacity = i;
      }
    }
    else
      qDebug("While parsing background encountered an unknown element: %s",(const char*)elemThis.tagName());
  }

  bgTarget.align = halign | valign;
  bgTarget.enabled = (valid_rect && ((bgTarget.staticImage && !bgTarget.image.isEmpty())
                       || (!bgTarget.staticImage && !bgTarget.data.query.isEmpty()
                                                 && !bgTarget.data.column.isEmpty())));
  return bgTarget.enabled;
}
예제 #21
0
bool ParameterEdit::setDocument(const QDomDocument & doc)
{
  QDomElement root = doc.documentElement();
  if(root.tagName() != "report")
  {
    QMessageBox::critical(this, tr("Not a Valid Report"),
      tr("The report definition does not appear to be a valid report."
         "\n\nThe root node is not 'report'."));
    return false;
  }

  _list->show();	
  _new->hide();	
  _delete->hide();	

  for(QDomNode n = root.firstChild(); !n.isNull(); n = n.nextSibling())
  {
    if(n.nodeName() == "parameter")
    {
      QDomElement elemSource = n.toElement();
      ORParameter param;

      param.name = elemSource.attribute("name");
      if(param.name.isEmpty())
        continue;
    
      param.type = elemSource.attribute("type");
      param.defaultValue  = elemSource.attribute("default");
      param.active = (elemSource.attribute("active") == "true");
      param.listtype = elemSource.attribute("listtype");
      
      QList<QPair<QString,QString> > pairs;
      if(param.listtype.isEmpty())
        param.description = elemSource.text();
      else
      {
        QDomNodeList section = elemSource.childNodes();
        for(int nodeCounter = 0; nodeCounter < section.count(); nodeCounter++)
        {
          QDomElement elemThis = section.item(nodeCounter).toElement();
          if(elemThis.tagName() == "description")
            param.description = elemThis.text();
          else if(elemThis.tagName() == "query")
            param.query = elemThis.text();
          else if(elemThis.tagName() == "item")
            param.values.append(qMakePair(elemThis.attribute("value"), elemThis.text()));
          else
            qDebug("While parsing parameter encountered an unknown element: %s",(const char*)elemThis.tagName().toLatin1().data());
        }
      }
      QVariant defaultVar;
      if(!param.defaultValue.isEmpty())
        defaultVar = QVariant(param.defaultValue);
      if("integer" == param.type)
        defaultVar = defaultVar.toInt();
      else if("double" == param.type)
        defaultVar = defaultVar.toDouble();
      else if("bool" == param.type)
        defaultVar = QVariant(defaultVar.toBool());
      else
        defaultVar = defaultVar.toString();
      updateParam(param.name, defaultVar, param.active);
      QList<QPair<QString, QString> > list;
      if("static" == param.listtype)
        list = param.values;
      else if("dynamic" == param.listtype && !param.query.isEmpty())
      {
        QSqlQuery qry(param.query);
        while(qry.next())
          list.append(qMakePair(qry.value(0).toString(), qry.value(1).toString()));
      }
      if(!list.isEmpty())
        _lists.insert(param.name, list);
    }
  }

  if(_lists.isEmpty())
    return false; // no defined parameters
  else 
    return true;
}
예제 #22
0
bool parseReportSection(const QDomElement & elemSource, ORSectionData & sectionTarget)
{
  sectionTarget.name = elemSource.tagName();

  if(sectionTarget.name != "rpthead" && sectionTarget.name != "rptfoot" &&
     sectionTarget.name != "pghead" && sectionTarget.name != "pgfoot" &&
     sectionTarget.name != "grouphead" && sectionTarget.name != "groupfoot" &&
     sectionTarget.name != "head" && sectionTarget.name != "foot" &&
     sectionTarget.name != "detail" )
    return false;

  sectionTarget.extra = QString::null;
  sectionTarget.height = -1;

  QDomNodeList section = elemSource.childNodes();
  for(int nodeCounter = 0; nodeCounter < section.count(); nodeCounter++)
  {
    QDomElement elemThis = section.item(nodeCounter).toElement();
    if(elemThis.tagName() == "height")
    {
      bool valid;
      int height = elemThis.text().toInt(&valid);
      if(valid)
        sectionTarget.height = height;
    }
    else if(elemThis.tagName() == "firstpage") {
      if(sectionTarget.name == "pghead" || sectionTarget.name == "pgfoot")
        sectionTarget.extra = elemThis.tagName();
    }
    else if(elemThis.tagName() == "odd")
    {
      if(sectionTarget.name == "pghead" || sectionTarget.name == "pgfoot")
        sectionTarget.extra = elemThis.tagName();
    }
    else if(elemThis.tagName() == "even")
    {
      if(sectionTarget.name == "pghead" || sectionTarget.name == "pgfoot")
        sectionTarget.extra = elemThis.tagName();
    }
    else if(elemThis.tagName() == "lastpage")
    {
      if(sectionTarget.name == "pghead" || sectionTarget.name == "pgfoot")
        sectionTarget.extra = elemThis.tagName();
    }
    else if(elemThis.tagName() == "label")
    {
      ORLabelData * label = new ORLabelData();
      if(parseReportLabel(elemThis, *label) == TRUE)
        sectionTarget.objects.append(label);
      else
        delete label;
    }
    else if(elemThis.tagName() == "field")
    {
      ORFieldData * field = new ORFieldData();
      if(parseReportField(elemThis, *field) == TRUE)
      {
        sectionTarget.objects.append(field);
        if(field->trackTotal)
          sectionTarget.trackTotal.append(field->data);
      }
      else
        delete field;
    }
    else if(elemThis.tagName() == "text")
    {
      ORTextData * text = new ORTextData();
      if(parseReportText(elemThis, *text) == TRUE)
        sectionTarget.objects.append(text);
      else
        delete text;
    }
    else if(elemThis.tagName() == "line")
    {
      ORLineData * line = new ORLineData();
      if(parseReportLine(elemThis, *line) == TRUE)
        sectionTarget.objects.append(line);
      else
        delete line;
    }
    else if(elemThis.tagName() == "barcode")
    {
      ORBarcodeData * bc = new ORBarcodeData();
      if(parseReportBarcode(elemThis, *bc) == TRUE)
        sectionTarget.objects.append(bc);
      else
        delete bc;
    }
    else if(elemThis.tagName() == "image")
    {
      ORImageData * img = new ORImageData();
      if(parseReportImage(elemThis, *img) == TRUE)
        sectionTarget.objects.append(img);
      else
        delete img;
    }
    else if(elemThis.tagName() == "graph")
    {
      ORGraphData * graph = new ORGraphData();
      if(parseReportGraphData(elemThis, *graph) == TRUE)
        sectionTarget.objects.append(graph);
      else
        delete graph;
    }
    else if(elemThis.tagName() == "key")
    {
      // we can ignore this as it will be handled elsewhere
      // we just catch this so we don't get an error
    }
    else
      qDebug("While parsing section encountered an unknown element: %s",(const char*)elemThis.tagName());
  }
  return TRUE;
}
예제 #23
0
void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillParam, QColor& defaultFill, bool& hasOutlineParam, QColor& defaultOutline,
                                      bool& hasOutlineWidthParam, double& defaultOutlineWidth ) const
{
  if ( elem.isNull() )
  {
    return;
  }

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

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

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

  //pass it further to child items
  QDomNodeList childList = elem.childNodes();
  int nChildren = childList.count();
  for ( int i = 0; i < nChildren; ++i )
  {
    QDomElement childElem = childList.at( i ).toElement();
    containsElemParams( childElem, hasFillParam, defaultFill, hasOutlineParam, defaultOutline, hasOutlineWidthParam, defaultOutlineWidth );
  }
}
void MainWindow::calculateEv(){

    currentInfo.clear();
    double standaardWaarde;
    int aantal = ui->aantalSpinBox->value();
    int lengte = ui->lengtSpinbox->value();
    int isolatie = ui->isolatieCombobox->currentIndex();
    int kleur = ui->kleurCombobox->currentIndex();
    if(kleur<=2)kleur = 0;
    else kleur = kleur - 2;
    qDebug()<< "lengte" << lengte;
    int index = ceil(lengte/(double)100) - 5;
    if(index <0) index =0;
    int raam = ui->raamCombobox->currentIndex();

    QDomDocument doc;
    //C:/Users/Gilles/Documents/QTProjects/DucoVentilatieRooster/
    QString temp = QCoreApplication::applicationDirPath() + "/LengteXML.xml";

    QFile file(temp);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << "Failed to open - 1";
    }else{
        if(!doc.setContent(&file)){
            qDebug() << "Failed to load - 2";
        }
        file.close();
    }
    QDomElement root = doc.firstChildElement();

    QDomNodeList items = root.elementsByTagName("LengteInterval");
    qDebug() << "index = " << index;
    QDomNode itemnode = items.at(index);
    if(itemnode.isElement()){

        QDomElement itemele = itemnode.toElement();
        qDebug() << itemele.attribute("ID");
        QDomNodeList inf = itemele.childNodes();
        qDebug() << kleur;
        QDomNode waarde = inf.at(raam);

        if(waarde.isElement()){
            qDebug() << "isel";
            QDomElement waardeElement = waarde.toElement();
            QString waardeString = waardeElement.attribute(kleurVe.at(kleur));
            standaardWaarde = waardeString.toDouble();
            qDebug() << standaardWaarde;

        }
    }

    if(ui->kleurCombobox->currentIndex()==1 || ui->kleurCombobox->currentIndex()==2){
        temp =QCoreApplication::applicationDirPath() + "/MeerPrijsPA.xml";
        file.setFileName(temp);

        if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
            qDebug() << "Failed to open - 1";
        }else{
            if(!doc.setContent(&file)){
                qDebug() << "Failed to load - 2";
            }
            file.close();
        }
        root = doc.firstChildElement();

        items = root.elementsByTagName("TypeIsolatie");

        qDebug() <<"grootte:"<< items.size();
        itemnode = items.at(ui->kleurCombobox->currentIndex()-1);
        if(itemnode.isElement()){
            QDomElement meerP = itemnode.toElement();
            standaardWaarde *= meerP.attribute("eerstepercentage").toDouble()/100 + 1;
            standaardWaarde *= meerP.attribute("tweedepercentage").toDouble()/100 + 1;

        }else qDebug() << "geen elementç lalal";
    }



    double debietWaarde;
    //C:/Users/Gilles/Documents/QTProjects/DucoVentilatieRooster/

    temp =QCoreApplication::applicationDirPath() + "/MeerPrijsXML.xml";
    file.setFileName(temp);
    //QFile file(temp);
    qDebug() << file.fileName();
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << "Failed to open - 1";
    }else{
        if(!doc.setContent(&file)){
            qDebug() << "Failed to load - 2";
        }
        file.close();
    }
    root = doc.firstChildElement();

    items = root.elementsByTagName("TypeIsolatie");
    qDebug() << "index = " << index;
    itemnode = items.at(isolatie);
    if(itemnode.isElement()){
        QDomElement itemeles = itemnode.toElement();
        standaardWaarde += ((double)lengte/1000)*itemeles.attribute(raamVe.at(raam)).toDouble();
        debietWaarde = itemeles.attribute("q").toDouble();
        qDebug() << "debietwaarde: " << debietWaarde;
    }else qDebug() << "geen elementç";



    if(lengte>4000)debietWaarde *=4.02;
    else {
        qDebug() << debietWaarde;
        debietWaarde *= ((double)lengte/1000 +.02);
    }





    currentInfo.push_back(ui->kamerComboBox->currentText());
    currentInfo.push_back(ui->topBoxCombobox->currentText());
    currentInfo.push_back(ui->raamCombobox->currentText());
    currentInfo.push_back(ui->isolatieCombobox->currentText());
    currentInfo.push_back(ui->kleurCombobox->currentText());
    currentInfo.push_back(QString::number(lengte) + " mm");
    currentInfo.push_back(QString::number((int)debietWaarde));
    currentInfo.push_back(QString::number(aantal));
    currentInfo.push_back(QString::number(standaardWaarde));
    currentInfo.push_back(QString::number(aantal*standaardWaarde));
    som.push_back(aantal*standaardWaarde);
    QString tekst = ui->kamerComboBox->currentText() + " / " + ui->topBoxCombobox->currentText() + " / " + ui->raamCombobox->currentText() + " / " + ui->kleurCombobox->currentText() + " / Lengte = " + QString::number(lengte) + "mm / Debiet = " + QString::number((int)debietWaarde) + "m^3/u / adviesprijs = " + QString::number(standaardWaarde) + " x " + QString::number(aantal);
    ui->pbLineEdit->setText(tekst);
}
예제 #25
0
ComplexUserAction *ComplexUserActionParser::parseAction(const QString &fileName, bool isScenario)
{
	QString mainTagName = (isScenario) ? "scenario" : "mainComplexUserAction";
	QDomDocument const document = loadDocument(fileName);
	QDomNodeList const actionList = document.elementsByTagName(mainTagName);
	if (actionList.length() != 1) {
		return nullptr;
	}
	QDomNode action = actionList.at(0);
	QDomElement const actionElement = action.toElement();

	QString const actionName = actionElement.attribute("name", "noName");
	QDomNodeList userActionList = actionElement.childNodes();

	QList<UserAction *> userActions;
	for (int i = 0; i < userActionList.length(); ++i) {
		QDomNode userAction = userActionList.at(i);
		QDomElement const userActionElement = userAction.toElement();
		if (userActionElement.tagName() == "baseUserAction") {
			BaseUserAction *baseAction = parseBaseUserAction(userActionElement);
			if (baseAction != nullptr) {
				userActions.append(baseAction);
			}
		}
		else if (userActionElement.tagName() == "complexUserAction") {
			ComplexUserAction *complexAction = parseComplexUserAction(userActionElement);
			if (complexAction != nullptr) {
				complexAction->setRepeatCount(userActionElement.attribute("repeatCount", "1").toInt());
				complexAction->setIsKeyAction(userActionElement.attribute("isKeyAction", "true") == "true");
				userActions.append(complexAction);
			}
		}
		else if (userActionElement.tagName() == "redTapeInstruction") {
			UserAction *redTapeInstruction = parseRedTapeInstruction(userActionElement);
			if (redTapeInstruction != nullptr) {
				userActions.append(redTapeInstruction);
			}
		}
	}
	QMap<QString, ActionStatus> actionStatus;
	if (isScenario) {
		QDomNodeList const actionStatusList = action.toElement().elementsByTagName("actionStatus");
		if (actionStatusList.length() == 1) {
			QDomElement actionStatusElement = actionStatusList.at(0).toElement();
			QDomNodeList const children = actionStatusElement.elementsByTagName("baseActionStatus");
			for (int i = 0; i < children.length(); ++i) {
				QDomElement child = children.at(i).toElement();
				QString const name = child.attribute("name", "");
				QString const value = child.attribute("value", "");
				ActionStatus status = ActionStatus::good;
				if (value == "bad") {
					status = ActionStatus::bad;
				}
				else if (value == "neutral") {
					status = ActionStatus::neutral;
				}
				actionStatus.insert(name, status);
			}
		}
	}
	ComplexUserAction *newComplexUserAction = new ComplexUserAction(actionName, userActions);
	newComplexUserAction->setUserActionsStatus(actionStatus);
	return newComplexUserAction;
}
예제 #26
0
bool QgsProject::createEmbeddedLayer( const QString& layerId, const QString& projectFilePath, QList<QDomNode>& brokenNodes,
                                      QList< QPair< QgsVectorLayer*, QDomElement > >& vectorLayerList, bool saveFlag )
{
  QFile projectFile( projectFilePath );
  if ( !projectFile.open( QIODevice::ReadOnly ) )
  {
    return false;
  }

  QDomDocument projectDocument;
  if ( !projectDocument.setContent( &projectFile ) )
  {
    return false;
  }

  //does project store pathes absolute or relative?
  bool useAbsolutePathes = true;
  QDomElement propertiesElem = projectDocument.documentElement().firstChildElement( "properties" );
  if ( !propertiesElem.isNull() )
  {
    QDomElement absElem = propertiesElem.firstChildElement( "Paths" ).firstChildElement( "Absolute" );
    if ( !absElem.isNull() )
    {
      useAbsolutePathes = absElem.text().compare( "true", Qt::CaseInsensitive ) == 0;
    }
  }

  QDomElement projectLayersElem = projectDocument.documentElement().firstChildElement( "projectlayers" );
  if ( projectLayersElem.isNull() )
  {
    return false;
  }

  QDomNodeList mapLayerNodes = projectLayersElem.elementsByTagName( "maplayer" );
  for ( int i = 0; i < mapLayerNodes.size(); ++i )
  {
    //get layer id
    QDomElement mapLayerElem = mapLayerNodes.at( i ).toElement();
    QString id = mapLayerElem.firstChildElement( "id" ).text();
    if ( id == layerId )
    {
      //layer can be embedded only once
      if ( mapLayerElem.attribute( "embedded" ) == "1" )
      {
        return false;
      }

      mEmbeddedLayers.insert( layerId, qMakePair( projectFilePath, saveFlag ) );

      //change datasource path from relative to absolute if necessary
      if ( !useAbsolutePathes )
      {
        QDomElement dsElem = mapLayerElem.firstChildElement( "datasource" );
        QString debug( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
        QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
        if ( absoluteDs.exists() )
        {
          dsElem.removeChild( dsElem.childNodes().at( 0 ) );
          dsElem.appendChild( projectDocument.createTextNode( absoluteDs.absoluteFilePath() ) );
        }
      }

      if ( addLayer( mapLayerElem, brokenNodes, vectorLayerList ) )
      {
        return true;
      }
      else
      {
        mEmbeddedLayers.remove( layerId );
        return false;
      }
    }
  }

  return false;
}
예제 #27
0
  QDomDocument createDescribeFeatureTypeDocument( QgsServerInterface *serverIface, const QgsProject *project, const QString &version,
      const QgsServerRequest &request )
  {
    Q_UNUSED( version );

    QDomDocument doc;

    QgsServerRequest::Parameters parameters = request.parameters();

    QgsAccessControl *accessControl = serverIface->accessControls();

    //xsd:schema
    QDomElement schemaElement = doc.createElement( QStringLiteral( "schema" )/*xsd:schema*/ );
    schemaElement.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) );
    schemaElement.setAttribute( QStringLiteral( "xmlns:xsd" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) );
    schemaElement.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    schemaElement.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE );
    schemaElement.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE );
    schemaElement.setAttribute( QStringLiteral( "targetNamespace" ), QGS_NAMESPACE );
    schemaElement.setAttribute( QStringLiteral( "elementFormDefault" ), QStringLiteral( "qualified" ) );
    schemaElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) );
    doc.appendChild( schemaElement );

    //xsd:import
    QDomElement importElement = doc.createElement( QStringLiteral( "import" )/*xsd:import*/ );
    importElement.setAttribute( QStringLiteral( "namespace" ),  GML_NAMESPACE );
    importElement.setAttribute( QStringLiteral( "schemaLocation" ), QStringLiteral( "http://schemas.opengis.net/gml/2.1.2/feature.xsd" ) );
    schemaElement.appendChild( importElement );

    QStringList typeNameList;
    QDomDocument queryDoc;
    QString errorMsg;
    if ( queryDoc.setContent( parameters.value( QStringLiteral( "REQUEST_BODY" ) ), true, &errorMsg ) )
    {
      //read doc
      QDomElement queryDocElem = queryDoc.documentElement();
      QDomNodeList docChildNodes = queryDocElem.childNodes();
      if ( docChildNodes.size() )
      {
        for ( int i = 0; i < docChildNodes.size(); i++ )
        {
          QDomElement docChildElem = docChildNodes.at( i ).toElement();
          if ( docChildElem.tagName() == QLatin1String( "TypeName" ) )
          {
            QString typeName = docChildElem.text().trimmed();
            if ( typeName.contains( ':' ) )
              typeNameList << typeName.section( ':', 1, 1 );
            else
              typeNameList << typeName;
          }
        }
      }
    }
    else
    {
      QString typeNames = request.parameter( QStringLiteral( "TYPENAME" ) );
      if ( !typeNames.isEmpty() )
      {
        QStringList typeNameSplit = typeNames.split( ',' );
        for ( int i = 0; i < typeNameSplit.size(); ++i )
        {
          QString typeName = typeNameSplit.at( i ).trimmed();
          if ( typeName.contains( ':' ) )
            typeNameList << typeName.section( ':', 1, 1 );
          else
            typeNameList << typeName;
        }
      }
    }

    QStringList wfsLayerIds = QgsServerProjectUtils::wfsLayerIds( *project );
    for ( int i = 0; i < wfsLayerIds.size(); ++i )
    {
      QgsMapLayer *layer = project->mapLayer( wfsLayerIds.at( i ) );
      if ( layer->type() != QgsMapLayer::LayerType::VectorLayer )
      {
        continue;
      }

      QString name = layer->name();
      if ( !layer->shortName().isEmpty() )
        name = layer->shortName();
      name = name.replace( ' ', '_' );

      if ( !typeNameList.isEmpty() && !typeNameList.contains( name ) )
      {
        continue;
      }

      if ( accessControl && !accessControl->layerReadPermission( layer ) )
      {
        if ( !typeNameList.isEmpty() )
        {
          throw QgsSecurityAccessException( QStringLiteral( "Feature access permission denied" ) );
        }
        else
        {
          continue;
        }
      }

      QgsVectorLayer *vLayer = qobject_cast<QgsVectorLayer *>( layer );
      QgsVectorDataProvider *provider = vLayer->dataProvider();
      if ( !provider )
      {
        continue;
      }
      setSchemaLayer( schemaElement, doc, const_cast<QgsVectorLayer *>( vLayer ) );
    }
    return doc;
  }
예제 #28
0
bool
VolumeInformation::volInfo(QString volfile,
			   VolumeInformation& pvlInfo)
{  
  if (!xmlHeaderFile(volfile))
    {
      QMessageBox::information(0, "Error",
	QString("%1 is not a valid preprocessed volume file").arg(volfile));
      return false;
    }
      
  bool rgba = checkRGB(volfile) || checkRGBA(volfile);

  pvlInfo.pvlFile = volfile;


  std::vector<float> pvlmap;
  std::vector<float> rawmap;

  QDomDocument document;
  QFile f(volfile.toLatin1().data());
  if (f.open(QIODevice::ReadOnly))
    {
      document.setContent(&f);
      f.close();
    }
  
  QDomElement main = document.documentElement();
  QDomNodeList dlist = main.childNodes();
  for(int i=0; i<dlist.count(); i++)
    {
      if (dlist.at(i).nodeName() == "rawfile")
	{
	  pvlInfo.rawFile = dlist.at(i).toElement().text();
	}
      else if (dlist.at(i).nodeName() == "description")
	{
	  pvlInfo.description = dlist.at(i).toElement().text();
	}
      else if (dlist.at(i).nodeName() == "voxeltype")
	{
	  QString pvalue = dlist.at(i).toElement().text();
	  if (pvalue == "unsigned char")
	    pvlInfo.voxelType = VolumeInformation::_UChar;
	  else if (pvalue == "char")
	    pvlInfo.voxelType = VolumeInformation::_Char;
	  else if (pvalue == "unsigned short")
	    pvlInfo.voxelType = VolumeInformation::_UShort;
	  else if (pvalue == "short")
	    pvlInfo.voxelType = VolumeInformation::_Short;
	  else if (pvalue == "int")
	    pvlInfo.voxelType = VolumeInformation::_Int;
	  else if (pvalue == "float")
	    pvlInfo.voxelType = VolumeInformation::_Float;
	}
      else if (dlist.at(i).nodeName() == "voxelunit")
	{
	  QString pvalue = dlist.at(i).toElement().text();
	  pvlInfo.voxelUnit = VolumeInformation::Nounit;
	  if (pvalue == "angstrom")
	    pvlInfo.voxelUnit = VolumeInformation::Angstrom;
	  else if (pvalue == "nanometer")
	    pvlInfo.voxelUnit = VolumeInformation::Nanometer;
	  else if (pvalue == "micron")
	    pvlInfo.voxelUnit = VolumeInformation::Micron;
	  else if (pvalue == "millimeter")
	    pvlInfo.voxelUnit = VolumeInformation::Millimeter;
	  else if (pvalue == "centimeter")
	    pvlInfo.voxelUnit = VolumeInformation::Centimeter;
	  else if (pvalue == "meter")
	    pvlInfo.voxelUnit = VolumeInformation::Meter;
	  else if (pvalue == "kilometer")
	    pvlInfo.voxelUnit = VolumeInformation::Kilometer;
	  else if (pvalue == "parsec")
	    pvlInfo.voxelUnit = VolumeInformation::Parsec;
	  else if (pvalue == "kiloparsec")
	    pvlInfo.voxelUnit = VolumeInformation::Kiloparsec;
	}
      else if (dlist.at(i).nodeName() == "voxelsize")
	{
	  QStringList str = (dlist.at(i).toElement().text()).split(" ", QString::SkipEmptyParts);
	  float vx = str[0].toFloat();
	  float vy = str[1].toFloat();
	  float vz = str[2].toFloat();
	  pvlInfo.voxelSize = Vec(vx, vy, vz);
	}
      else if (dlist.at(i).nodeName() == "gridsize")
	{
	  QStringList str = (dlist.at(i).toElement().text()).split(" ", QString::SkipEmptyParts);
	  int d = str[0].toInt();
	  int w = str[1].toInt();
	  int h = str[2].toInt();
	  pvlInfo.dimensions = Vec(d,w,h);
	}
      else if (dlist.at(i).nodeName() == "slabsize")
	{
	  pvlInfo.slabSize = (dlist.at(i).toElement().text()).toInt();
	}
      else if (dlist.at(i).nodeName() == "rawmap")
	{
	  QStringList str = (dlist.at(i).toElement().text()).split(" ", QString::SkipEmptyParts);
	  for(int im=0; im<str.count(); im++)
	    rawmap.push_back(str[im].toFloat());
	}
      else if (dlist.at(i).nodeName() == "pvlmap")
	{
	  QStringList str = (dlist.at(i).toElement().text()).split(" ", QString::SkipEmptyParts);
	  for(int im=0; im<str.count(); im++)
	    pvlmap.push_back(str[im].toInt());
	}
    }

  for(int i=0; i<(int)qMin(rawmap.size(), pvlmap.size()); i++)
    pvlInfo.mapping << QPointF(rawmap[i], pvlmap[i]);
  
  rawmap.clear();
  pvlmap.clear();

  return true;
}
예제 #29
0
void DocumentReader::_readElement(QDomElement element, Node* node)
{
    for (int i = 0; i < element.childNodes().count(); i++)
    {
        // The QDomDocument class creates a node named "#text" which contains
        // the node value (content).
        if (element.childNodes().at(i).nodeName().toLower() == "#text")
            node->setContent(element.childNodes().at(i).nodeValue());
        else
        {
            Node* new_node = new Node(node,
                                      element.childNodes().at(i).nodeName().toLower(),
                                      node->getLayer() + 1);
            node->addChild(new_node);
            QDomNamedNodeMap attributes = element.childNodes().at(i).attributes();
            DocumentReaderData documentreference = _translationMapper->getDocumentReference();
            if (element.childNodes().at(i).nodeName().toLower() == documentreference.getTagName())
            {
                if (Settings::DEBUG)
                {
                    std::cerr << tr("#\tReadElement - '").toStdString()
                            << documentreference.getTagName().toStdString()
                            << tr("': \n#\t\tindexFileInfo.absPath: ").toStdString()
                            << _indexFileInfo.absolutePath().toStdString()
                            << std::endl << tr("#\t\thref: ").toStdString()
                            << new_node->getAttributes()["href"].toStdString() << std::endl;
                }
                QString urlattribute = documentreference.getUrlContainingAttributeName();
                new_node->addAttribute(urlattribute, attributes.namedItem(urlattribute).nodeValue());
                // compose absolute file path
                QFileInfo myfileinfo;
                if (QFileInfo(_indexFileInfo.absolutePath() + new_node->getAttributes()["href"]).exists())
                    // unix
                    myfileinfo = QFileInfo(_indexFileInfo.absolutePath()
                                           + new_node->getAttributes()["href"]);
                else
                    // windows
                    myfileinfo = QFileInfo(_indexFileInfo.absolutePath()
                                           + QDir::separator() + new_node->getAttributes()["href"]);
                if (_includeSubDocuments)
                    _documentStack.push(new DocumentData(myfileinfo, new_node, _fileType));
                if(Settings::DEBUG)
                {
                    std::cerr << tr("# CDocumentReader::readElement()").toStdString()
                           << std::endl << tr("#\tat \"if (element.childNodes()").toStdString()
                           << tr(".at(i).nodeName().toLower() == \"a\")\" returned true").toStdString()
                           << std::endl << tr("#\tfound subdocument href=").toStdString()
                           << new_node->getAttributes()["href"].toStdString() << std::endl;
                }
            }
            else
            {
                QDomNode attribute;
                for (int i = 0; i < attributes.count(); i++)
                {
                    attribute = attributes.item(i);
                    new_node->addAttribute(attribute.nodeName(), attribute.nodeValue());
                }
            }
            QDomElement new_element = element.childNodes().at(i).toElement();
            _readElement(new_element, new_node);
        }
    }
};
예제 #30
0
파일: main.cpp 프로젝트: treevg/reportcard
int main(int argc, char *argv[]) {

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

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

    QSvgWidget* mySvg = new QSvgWidget();

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


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

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

    mainWin.setCentralWidget(centralWidget);


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

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

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

                element.appendChild(newTextNode);
            }
        }
    }

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

    file.close();
    return app.exec();
}