Esempio n. 1
0
void
NetworkObject::loadNodeInfo(QDomNodeList nnodes)
{
  m_vertexAttribute.clear();
  m_vertexCenters.clear();
  m_nodeId.clear();

  QVector<float> *vat; // not expecting more than 20 attributes
  int nvat = m_nodeAtt.count();
  vat = new QVector<float> [nvat];

  int nn = nnodes.count();
  for(int n=0; n<nn; n++)
    {
      QDomElement ele = nnodes.item(n).toElement();
      QString id = ele.attributeNode("id").value();
      m_nodeId << id;

      Vec pos;

      QDomNodeList nlist = nnodes.item(n).childNodes();
      int nc = nlist.count();
      for(int c=0; c<nc; c++)
	{
	  QDomNode node = nlist.item(c);
	  QDomElement ele = node.toElement();
	  QString et = ele.text();

	  QDomNamedNodeMap attr = ele.attributes();
	  QString name = attr.item(0).nodeName();
	  QString val = attr.item(0).nodeValue();
	  if (val == "x") pos.x = et.toFloat();
	  else if (val == "y") pos.y = et.toFloat();
	  else if (val == "z") pos.z = et.toFloat();
	  else 
	    {
	      int vi = m_nodeAtt.indexOf(val);
	      if (vi >= 0)
		vat[vi] << et.toFloat();
	    }
	}
      m_vertexCenters << pos;

      int nv = m_vertexCenters.count();
      for(int c=0; c<m_nodeAtt.count(); c++)
	{
	  if (vat[c].count() < nv)
	    vat[c] << 0.0;
	}
    }

  for(int e=0; e<m_nodeAtt.count(); e++)
    {
      if (m_nodeAtt[e].contains("diameter", Qt::CaseInsensitive))
	{
	  for(int vi=0; vi<vat[e].count(); vi++)
	    vat[e][vi] /= 2;
	}
    }


  for(int vi=0; vi<m_nodeAtt.count(); vi++)
    m_vertexAttribute << qMakePair(m_nodeAtt[vi], vat[vi]);      

  if (m_vertexRadiusAttribute == -1)
    {
      m_vertexRadiusAttribute = m_nodeAtt.count();
      QVector<float> rad;
      rad.resize(m_vertexCenters.count());
      rad.fill(2);
      m_nodeAtt << "vertex_radius";
      m_vertexAttribute << qMakePair(QString("vertex_radius"), rad);
    }

  for(int i=0; i<nvat; i++)
    vat[i].clear();
  delete [] vat;
}
Esempio n. 2
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;
}
Esempio n. 3
0
void Parser::parse( const QString &xml )
{
  QDomDocument doc( "kwscl" );
  QString errorMsg;
  int errorLine, errorColumn;
  bool ok = doc.setContent( xml, true, &errorMsg, &errorLine, &errorColumn );
  if ( !ok ) {
    qDebug( "Error parsing wscl (%d:%d) %s", errorLine, errorColumn, errorMsg.latin1() );
    return;
  }

  QDomNodeList nodes = doc.elementsByTagName( "Conversation" );
  if ( nodes.count() <= 0 ) {
    qDebug( "No conversation tag found in wscl data" );
    return;
  }

  QDomElement conversationElement = nodes.item( 0 ).toElement();

  mConversation.setName( conversationElement.attribute( "name" ) );
  mConversation.setVersion( conversationElement.attribute( "version" ) );
  mConversation.setDescription( conversationElement.attribute( "description" ) );
  mConversation.setNameSpace( conversationElement.attribute( "targetNamespace" ) );
  mConversation.setSchema( conversationElement.attribute( "hrefSchema" ) );
  mConversation.setInitialInteraction( conversationElement.attribute( "initialInteraction" ) );
  mConversation.setFinalInteraction( conversationElement.attribute( "finalInteraction" ) );

  QDomNode node = conversationElement.firstChild();
  while ( !node.isNull() ) {
    QDomElement element = node.toElement();
    if ( !element.isNull() ) {
      if ( element.tagName() == "ConversationInteractions" ) {
        Interaction::List interactions;

        QDomNode interactionNode = element.firstChild();
        while ( !interactionNode.isNull() ) {
          QDomElement interactionElement = interactionNode.toElement();
          if ( !interactionElement.isNull() ) {
            if ( interactionElement.tagName() != "Interaction" ) {
              qDebug( "Expected tag name 'Interaction', got '%s'", interactionElement.tagName().latin1() );
              continue;
            }

            Interaction interaction;
            interaction.setId( interactionElement.attribute( "id" ) );
            const QString type = interactionElement.attribute( "interactionType" );
            if ( type == "ReceiveSend" )
              interaction.setType( Interaction::ReceiveSend );
            else if ( type == "SendReceive" )
              interaction.setType( Interaction::SendReceive );
            else if ( type == "Receive" )
              interaction.setType( Interaction::Receive );
            else if ( type == "Send" )
              interaction.setType( Interaction::Send );
            else if ( type == "Empty" )
              interaction.setType( Interaction::Empty );
            else
              qDebug( "Unknown interaction type '%s'", type.latin1() );

            XMLDocument::List inputDocuments;
            XMLDocument::List outputDocuments;
            XMLDocument inputDocument;
            XMLDocument outputDocument;

            QDomNode contentNode = interactionElement.firstChild();
            while ( !contentNode.isNull() ) {
              QDomElement contentElement = contentNode.toElement();
              if ( !contentElement.isNull() ) {
                const QString tagName = contentElement.tagName();
                if ( tagName == "InboundXMLDocument" ) {
                  XMLDocument document;
                  document.setId( contentElement.attribute( "id" ) );
                  document.setSchema( contentElement.attribute( "hrefSchema" ) );

                  inputDocuments.append( document );
                  inputDocument = document;
                } else if ( tagName == "OutboundXMLDocument" ) {
                  XMLDocument document;
                  document.setId( contentElement.attribute( "id" ) );
                  document.setSchema( contentElement.attribute( "hrefSchema" ) );

                  outputDocuments.append( document );
                  outputDocument = document;
                }
              }


              contentNode = contentNode.nextSibling();
            }

            switch ( interaction.type() ) {
              case Interaction::ReceiveSend:
                {
                  ReceiveSendDocument document;
                  document.setInputDocument( inputDocument );
                  document.setOutputDocuments( outputDocuments );
                  interaction.setReceiveSendDocument( document );
                }
                break;
              case Interaction::SendReceive:
                {
                  SendReceiveDocument document;
                  document.setInputDocuments( inputDocuments );
                  document.setOutputDocument( outputDocument );
                  interaction.setSendReceiveDocument( document );
                }
                break;
              case Interaction::Receive:
                {
                  ReceiveDocument document;
                  document.setInputDocument( inputDocument );
                  interaction.setReceiveDocument( document );
                }
                break;
              case Interaction::Send:
                {
                  SendDocument document;
                  document.setOutputDocument( outputDocument );
                  interaction.setSendDocument( document );
                }
                break;
              case Interaction::Empty:
              default:
                break;
            }

            interactions.append( interaction );
          }

          interactionNode = interactionNode.nextSibling();
        }

        mConversation.setInteractions( interactions );

      } else if ( element.tagName() == "ConversationTransitions" ) {
        Transition::List transitions;

        QDomNode transitionNode = element.firstChild();
        while ( !transitionNode.isNull() ) {
          QDomElement transitionElement = transitionNode.toElement();
          if ( !transitionElement.isNull() ) {
            if ( transitionElement.tagName() != "Transition" ) {
              qDebug( "Expected tag name 'Transition', got '%s'", transitionElement.tagName().latin1() );
              continue;
            }

            Transition transition;

            QDomNode contentNode = transitionElement.firstChild();
            while ( !contentNode.isNull() ) {
              QDomElement contentElement = contentNode.toElement();
              if ( !contentElement.isNull() ) {
                const QString tagName = contentElement.tagName();
                if ( tagName == "SourceInteraction" )
                  transition.setSourceInteraction( contentElement.attribute( "href" ) );
                else if ( tagName == "DestinationInteraction" )
                  transition.setDestinationInteraction( contentElement.attribute( "href" ) );
                else if ( tagName == "SourceInteractionCondition" )
                  transition.setSourceInteractionCondition( contentElement.attribute( "href" ) );
                else
                  qDebug( "Unknown transition element %s", tagName.latin1() );
              }

              contentNode = contentNode.nextSibling();
            }

            transitions.append( transition );
          }

          transitionNode = transitionNode.nextSibling();
        }

        mConversation.setTransitions( transitions );
      }
    }

    node = node.nextSibling();
  }
}
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;
    }
  }
Esempio n. 5
0
bool DomConvenience::elementToVariant(const QDomElement& e, QVariant& v)
{
	bool ok = false;

	if (e.tagName() == "string")
	{
		if (e.hasAttribute("value"))
		{
			v = QVariant(e.attribute("value"));
			ok = true;
		}
		else
			qWarning("%s element without value!", (const char*)e.tagName());
	}
	else if (e.tagName() == "int")
	{
		int base = getBase(e);

		if (e.hasAttribute("value"))
			v = QVariant(e.attribute("value").toInt(&ok, base));
		else
			qWarning("%s element without value!", (const char*)e.tagName());
	}
	else if (e.tagName() == "uint")
	{
		int base = getBase(e);

		if (e.hasAttribute("value"))
			v = QVariant(e.attribute("value").toUInt(&ok, base));
		else
			qWarning("%s element without value!", (const char*)e.tagName());
	}
	else if (e.tagName() == "double")
	{
		if (e.hasAttribute("value"))
			v = QVariant(e.attribute("value").toDouble(&ok));
		else
			qWarning("%s element without value!", (const char*)e.tagName());
	}
	else if (e.tagName() == "bool")
	{
		if (e.hasAttribute("value"))
		{
			QString val = e.attribute("value");
			v = QVariant(getBoolFromString(val, ok), 0);

			if (!ok)
				qWarning("%s element with bogus value '%s'!", (const char*)e.tagName(), (const char*)val);
		}
		else
			qWarning("%s element without value!", (const char*)e.tagName());
	}
	else if (e.tagName() == "color")
	{
		QColor color = getColor(e);
		ok = color.isValid();
		v = color;

		if (!ok)
			qWarning("%s element without valid value!", (const char*)e.tagName());
	}
	else if (e.tagName() == "pen")
	{
		int base = getBase(e);
		uint w = 0;
		Qt::PenStyle s = Qt::SolidLine;
		Qt::PenCapStyle c = Qt::SquareCap;
		Qt::PenJoinStyle j = Qt::BevelJoin;
		QColor color = getColor(e);

		if (e.hasAttribute("style"))
			s = (Qt::PenStyle)e.attribute("style").toInt(0, base);
		if (e.hasAttribute("cap"))
			c = (Qt::PenCapStyle)e.attribute("cap").toInt(0, base);
		if (e.hasAttribute("join"))
			j = (Qt::PenJoinStyle)e.attribute("join").toInt(0, base);

		ok = color.isValid();

		v = QPen(color, w, s, c, j);

		if (!ok)
			qWarning("%s element without valid value!", (const char*)e.tagName());
	}
	else if (e.tagName() == "brush")
	{
		int base = getBase(e);
		QColor color = getColor(e);
		Qt::BrushStyle s = Qt::SolidPattern;
		if (e.hasAttribute("style"))
			s = (Qt::BrushStyle)e.attribute("style").toInt(0, base);

		ok = color.isValid();

		v = QBrush(color, s);

		if (!ok)
			qWarning("%s element without valid value!", (const char*)e.tagName());
	}
	else if (e.tagName() == "point")
	{
		int base = getBase(e);
		bool coordOk;

		int x = 0, y = 0;
		if (e.hasAttribute("x"))
			x = e.attribute("x").toInt(&coordOk, base);

		if (e.hasAttribute("y"))
			y = e.attribute("y").toInt(&coordOk, base);

		v = QVariant(QPoint(x, y));
		ok = true;
	}
	else if (e.tagName() == "rect")
	{
		int base = getBase(e);
		bool coordOk;

		int x = 0, y = 0, width = 0, height = 0;
		if (e.hasAttribute("x"))
			x = e.attribute("x").toInt(&coordOk, base);

		if (e.hasAttribute("y"))
			y = e.attribute("y").toInt(&coordOk, base);

		if (e.hasAttribute("width"))
			width = e.attribute("width").toInt(&coordOk, base);

		if (e.hasAttribute("height"))
			height = e.attribute("height").toInt(&coordOk, base);

		v = QVariant(QRect(x, y, width, height));
		ok = true;
	}
	else if (e.tagName() == "size")
	{
		int base = getBase(e);
		bool coordOk;

		int width = 0, height = 0;
		if (e.hasAttribute("width"))
			width = e.attribute("width").toInt(&coordOk, base);

		if (e.hasAttribute("height"))
			height = e.attribute("height").toInt(&coordOk, base);

		v = QVariant(QSize(width, height));
		ok = true;
	}
	else if (e.tagName() == "key")
	{
		QKeySequence key;
		if (e.hasAttribute("sequence"))
		{
			key = (QKeySequence)e.attribute("sequence");

			// fix the key code (deal with Qt brain death)
			v = key & ~Qt::UNICODE_ACCEL;
			ok = true;
		}
	}
	else if (e.tagName() == "font")
	{
		QFont f;
		bool boolOk;

		if (e.hasAttribute("family"))
			f.setFamily(e.attribute("family"));
		if (e.hasAttribute("pointsize"))
			f.setPointSize(e.attribute("pointsize").toInt());
		if (e.hasAttribute("bold"))
			f.setBold(getBoolFromString(e.attribute("bold"), boolOk));
		if (e.hasAttribute("italic"))
			f.setItalic(getBoolFromString(e.attribute("italic"), boolOk));
		if (e.hasAttribute("strikeout"))
			f.setStrikeOut(getBoolFromString(e.attribute("strikeout"), boolOk));

		v = QVariant(f);
		ok = true;
	}
	else if (e.tagName() == "sizepolicy")
	{
		QSizePolicy sp;

		if (e.hasAttribute("hsizetype"))
			sp.setHorData((QSizePolicy::SizeType)e.attribute("hsizetype").toInt());
		if (e.hasAttribute("vsizetype"))
			sp.setVerData((QSizePolicy::SizeType)e.attribute("vsizetype").toInt());
		if (e.hasAttribute("horstretch"))
			sp.setHorStretch(e.attribute("horstretch").toInt());
		if (e.hasAttribute("verstretch"))
			sp.setHorStretch(e.attribute("verstretch").toInt());
		v = QVariant(sp);
		ok = true;
	}
	else if (e.tagName() == "cursor")
	{
		if (e.hasAttribute("shape")) {
			v = QVariant(QCursor((Qt::CursorShape)e.attribute("shape").toInt(&ok, 10)));
		} else
			qWarning("%s element without value!", (const char*)e.tagName());
	}
	else if (e.tagName() == "stringlist")
	{
		QDomNodeList stringNodeList = e.elementsByTagName("string");
		QStringList stringList;
		QDomElement stringElement;

		for (uint i = 0; i < stringNodeList.length(); i++)
		{
			stringElement = stringNodeList.item(i).toElement();
			if (!stringElement.hasAttribute("value"))
			{
				qWarning("%s element in %s without value! Ignoring!",
						 (const char*)stringElement.tagName(),
						 (const char*)e.tagName());
				continue;
			}

			stringList.append(e.attribute("value"));
		}

		v = stringList;

		ok = true;
	}
	else if (e.tagName() == "uint64")
	{
		QString value = e.attribute("value");

		// borrowed more or less from Qt 3.2 (since we have to support older)
		uint64_t val = 0;
		const QChar* p = value.unicode();
		int l = value.length();
		const uint64_t max_mult = 0x0fffffffffffffffull/* UINT64_MAX / 16 */;

		if (!p)
		{
			qWarning("Invalid value for tag: %s", (const char*)e.tagName());
			return false;
		}

		while ( l && p->isSpace() )                 // skip leading space
			l--,p++;
		if ( !l )
			return false;
		if ( *p == '+' )
			l--,p++;

		if ( !l || !ok_in_hex(*p) )
			return false;
		while ( l && ok_in_hex(*p) )
		{
			l--;
			uint dv;
			if ( p->isDigit() )
				dv = p->digitValue();
			else
			{
				if ( *p >= 'a' && *p <= 'f' )
					dv = p->toAscii() - 'a' + 10;
				else
					dv = p->toAscii() - 'A' + 10;
			}
			if ( val > max_mult || (val == max_mult && dv > 0xf /*UINT64_MAX % 16*/) )
				return false;
			val = 16 * val + dv;
			p++;
		}

		QByteArray ba;
		ba.duplicate((const char*)&val, sizeof(uint64_t));

		v = ba;
		ok = true;
	}
	else if (e.tagName() == "data")
	{
		v = getByteArrayFromString(e.attribute("value"));
		ok = true;
	}
	else if (e.tagName() == "list")
	{
		qWarning("Unimplemented tag: %s", (const char*)e.tagName());
	}
	else if (e.tagName() == "map")
	{
		qWarning("Unimplemented tag: %s", (const char*)e.tagName());
	}
	else
	{
		qWarning("Unknown tag: %s", (const char*)e.tagName());
	}

	return ok;
}
Esempio n. 6
0
void KWDWriter::finishTable(int tableno, QRect rect)
{
    int ncols = 0;
    int nrows = 0;
    insidetable = false;

    int x = rect.x();
    int y = rect.y();
    int w = rect.width();
    int h = rect.height();

    QDomNodeList nl = docroot().elementsByTagName("FRAMESET");
    //FIXME calculate nrows and stuff.
    //and add empty cells for missing ones.

    // first, see how big the table is (cols & rows)
    for (int i = 0;i < nl.count();i++) {
        QDomElement k = nl.item(i).toElement();
        if (k.attribute("grpMgr") == QString("Table %1").arg(tableno)) {
            ncols = MAX(ncols, k.attribute("col").toInt() + 1);
            nrows = MAX(nrows, k.attribute("row").toInt() + 1);
        }
    }
    int curcol = 0;
    int currow = 0;
    int currow_inc = 0;
    if (ncols == 0) ncols = 1; // FIXME (floating point division by zero)
    if (nrows == 0) nrows = 1;

    int step_x = (w - x) / ncols;
    int step_y = (h - y) / nrows;


    // then, let's create the missing cells and resize them if needed.
    bool must_resize = false;
    if (x > 0) must_resize = true;
    while (currow < nrows) {
        curcol = 0;
        while (curcol < ncols) {
            QDomElement e = fetchTableCell(tableno, currow, curcol);
            if (e.isNull()) {
                // a missing cell !
                kDebug(30503) << QString("creating %1 %2").arg(currow).arg(curcol).toLatin1();
                createTableCell(tableno, currow, curcol, 1,
                                QRect(x + step_x*curcol, y + step_y*currow, step_x, step_y)
                               );
                // fixme: what to do if we don't have to resize ?
            }

            // resize this one FIXME optimize this routine
            if (must_resize == true) {
                QDomElement ee = e.firstChild().toElement(); // the frame in the frameset
                int cs = e.attribute("cols").toInt();
                int rs = e.attribute("rows").toInt();
                kDebug(30503) << "resizing";
                addRect(ee, QRect(x + step_x*curcol, 0, step_x*cs, step_y*rs));
            }
            if (curcol == 0) currow_inc = e.attribute("rows").toInt();
            curcol += e.attribute("cols").toInt();


        }
        currow += currow_inc;
    }


}
/**
\param periodo1finicial
\param periodo1ffinal
\param periodo2finicial
\param periodo2ffinal
**/
void BcCuentasAnualesImprimirView::imprimir ( QString periodo1finicial, QString periodo1ffinal, QString periodo2finicial, QString periodo2ffinal )
{
    BL_FUNC_DEBUG

    /// Copiamos el archivo.
    QString archivo = g_confpr->value( CONF_DIR_OPENREPORTS ) + "canuales.rml";
    QString archivod = g_confpr->value( CONF_DIR_USER ) + "canuales.rml";
    blCopyFile(archivo, archivod);

    /// Copiamos el logo.
    QString archivologo = g_confpr->value( CONF_DIR_OPENREPORTS ) + "logo.jpg";
    QString logousuario = g_confpr->value( CONF_DIR_USER ) + "logo.jpg";
    blCopyFile(archivologo, logousuario);

    QFile file;
    file.setFileName ( archivod );
    file.open ( QIODevice::ReadOnly );
    QTextStream stream ( &file );
    QString buff = stream.readAll();
    file.close();
    QString fitxersortidatxt;
    fitxersortidatxt = "";

    /// Iteramos para cada componente del listado.
    QDomNodeList componentes = m_doc.elementsByTagName ( "COMPONENTE" );
    for ( int j = 0; j < componentes.count(); j++ ) {
        QDomElement comp = componentes.item ( j ).toElement();
        /// Escribimos el titulo del componente
        QString debeohaber = comp.namedItem ( "SUBTITULO" ).toElement().text();
        fitxersortidatxt += "" + debeohaber + "\n";
        /// Cogemos los elementos del componente y los ponemos en forma de tabla.
        fitxersortidatxt += "<blockTable style=\"tabla\" repeatRows=\"1\" colWidths=\"12cm,3cm,3cm\">\n";
        fitxersortidatxt += "<tr><td><para style=\"debeohaber\">" + debeohaber + "</para></td>\n";
        fitxersortidatxt += "<td><para style=\"periodo\">Periodo:</para><para style=\"periodo\">" + periodo1finicial + " ~ " + periodo1ffinal + "</para></td>\n";
        fitxersortidatxt += "<td><para style=\"periodo\">Periodo:</para><para style=\"periodo\">" + periodo2finicial + " ~ " + periodo2ffinal + "</para></td></tr>\n";

        QDomNodeList litems = comp.elementsByTagName ( "LBALANCE" );
        QLocale::setDefault ( QLocale ( QLocale::Spanish, QLocale::Spain ) );
        QLocale spanish;
        for ( int i = 0; i < litems.count(); i++ ) {
            QDomNode item = litems.item ( i );
            QDomElement e1 = item.toElement(); /// Try to convert the node to an element.
            if ( !e1.isNull() ) { /// The node was really an element.
                QDomNode formul = item.firstChildElement ( "FORMULA" );
                QString vact = formul.firstChildElement ( "VALORACT" ).toElement().text();
                vact = spanish.toString ( vact.toDouble(), 'f', 2 );
                QString vant = formul.firstChildElement ( "VALORANT" ).toElement().text();
                vant = spanish.toString ( vant.toDouble(), 'f', 2 );
                QString texto = item.firstChildElement ( "CONCEPTO" ).toElement().text();
                fitxersortidatxt += "<tr>\n";
                fitxersortidatxt += "<td>" + texto + "</td>\n";
                fitxersortidatxt += "<td>" + vact + "</td>\n";
                fitxersortidatxt += "<td>" + vant + "</td>\n";
                fitxersortidatxt += "</tr>\n";
            } // end if
        } // end for
        QLocale::setDefault ( QLocale::C );
        fitxersortidatxt += "</blockTable>\n";
        fitxersortidatxt += "<nextFrame/>\n";
    } // end for

    buff.replace ( "[story]", fitxersortidatxt );
    QDomElement nodo = m_doc.namedItem ( "BALANCE" ).namedItem ( "TITULO" ).toElement();
    buff.replace ( "[titulo]", nodo.text() );

    if ( file.open ( QIODevice::WriteOnly ) ) {
        QTextStream stream ( &file );
        stream << buff;
        file.close();
    } // end if

    blCreateAndLoadPDF ( "canuales" );
    
}
Esempio n. 8
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;
}
Esempio n. 9
0
void QgsGrassNewMapset::loadRegions()
{

  QString path = QgsApplication::pkgDataPath() + "/grass/locations.gml";
  QgsDebugMsg( QString( "load:%1" ).arg( path.toLocal8Bit().constData() ) );

  QFile file( path );

  if ( !file.exists() )
  {
    QgsGrass::warning( tr( "Regions file (%1) not found." ).arg( path ) );
    return;
  }
  if ( ! file.open( QIODevice::ReadOnly ) )
  {
    QgsGrass::warning( tr( "Cannot open locations file (%1)" ).arg( path ) );
    return;
  }

  QDomDocument doc( "gml:FeatureCollection" );
  QString err;
  int line, column;

  if ( !doc.setContent( &file,  &err, &line, &column ) )
  {
    QString errmsg = tr( "Cannot read locations file (%1):" ).arg( path )
                     + tr( "\n%1\nat line %2 column %3" ).arg( err ).arg( line ).arg( column );
    QgsDebugMsg( errmsg );
    QgsGrass::warning( errmsg );
    file.close();
    return;
  }

  QDomElement docElem = doc.documentElement();
  QDomNodeList nodes = docElem.elementsByTagName( "gml:featureMember" );

  for ( int i = 0; i < nodes.count(); i++ )
  {
    QDomNode node = nodes.item( i );

    if ( node.isNull() )
    {
      continue;
    }

    QDomElement elem = node.toElement();
    QDomNodeList nameNodes = elem.elementsByTagName( "gml:name" );
    if ( nameNodes.count() == 0 )
      continue;
    if ( nameNodes.item( 0 ).isNull() )
      continue;

    QDomElement nameElem = nameNodes.item( 0 ).toElement();
    if ( nameElem.text().isNull() )
      continue;

    QDomNodeList envNodes = elem.elementsByTagName( "gml:Envelope" );
    if ( envNodes.count() == 0 )
      continue;
    if ( envNodes.item( 0 ).isNull() )
      continue;
    QDomElement envElem = envNodes.item( 0 ).toElement();

    QDomNodeList coorNodes = envElem.elementsByTagName( "gml:coordinates" );
    if ( coorNodes.count() == 0 )
      continue;
    if ( coorNodes.item( 0 ).isNull() )
      continue;
    QDomElement coorElem = coorNodes.item( 0 ).toElement();
    if ( coorElem.text().isNull() )
      continue;

    QStringList coor = coorElem.text().split( " ", QString::SkipEmptyParts );
    if ( coor.size() != 2 )
    {
      QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) );
      continue;
    }

    QStringList ll = coor[0].split( ",", QString::SkipEmptyParts );
    QStringList ur = coor[1].split( ",", QString::SkipEmptyParts );
    if ( ll.size() != 2 || ur.size() != 2 )
    {
      QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) );
      continue;
    }

    // Add region
    mRegionsComboBox->addItem( nameElem.text() );

    QgsPoint llp( ll[0].toDouble(), ll[1].toDouble() );
    mRegionsPoints.push_back( llp );
    QgsPoint urp( ur[0].toDouble(), ur[1].toDouble() );
    mRegionsPoints.push_back( urp );
  }
  mRegionsComboBox->setCurrentIndex( -1 );

  file.close();
}
Esempio n. 10
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;
}
Esempio n. 11
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;
}
Esempio n. 12
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;
}
Esempio n. 13
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);
}
Esempio n. 14
0
void
NetworkObject::loadEdgeInfo(QDomNodeList nnodes)
{
  m_edgeAttribute.clear();
  m_edgeNeighbours.clear();

  QVector<float> *vat; // not expecting more than 20 attributes
  int nvat = m_edgeAtt.count();
  vat = new QVector<float> [nvat];

  int nn = nnodes.count();
  for(int n=0; n<nn; n++)
    {
      QDomElement ele = nnodes.item(n).toElement();
      QString id = ele.attributeNode("id").value();
      QString src = ele.attributeNode("source").value();
      QString tar = ele.attributeNode("target").value();
      int a,b;
      a = m_nodeId.indexOf(src);
      b = m_nodeId.indexOf(tar);
      if (a >= 0 && b >= 0)
	m_edgeNeighbours << qMakePair(a,b);

      QDomNodeList nlist = nnodes.item(n).childNodes();
      int nc = nlist.count();
      for(int c=0; c<nc; c++)
	{
	  QDomNode node = nlist.item(c);
	  QDomElement ele = node.toElement();
	  QString et = ele.text();
	  QDomNamedNodeMap attr = ele.attributes();
	  QString name = attr.item(0).nodeName();
	  QString val = attr.item(0).nodeValue();

	  int vi = m_edgeAtt.indexOf(val);
	  if (vi >= 0)
	    vat[vi] << et.toFloat();
	}

      int nv = m_edgeNeighbours.count();
      for(int c=0; c<m_edgeAtt.count(); c++)
	{
	  if (vat[c].count() < nv)
	    vat[c] << 0.0;
	}
    }

  for(int e=0; e<m_edgeAtt.count(); e++)
    {
      if (m_edgeAtt[e].contains("diameter", Qt::CaseInsensitive))
	{
	  for(int vi=0; vi<vat[e].count(); vi++)
	    vat[e][vi] /= 2;
	}
    }

  for(int vi=0; vi<m_edgeAtt.count(); vi++)
    m_edgeAttribute << qMakePair(m_edgeAtt[vi], vat[vi]);      

  if (m_edgeRadiusAttribute == -1)
    {
      m_edgeRadiusAttribute = m_edgeAtt.count();
      QVector<float> rad;
      rad.resize(m_edgeNeighbours.count());
      rad.fill(2);
      m_edgeAtt << "edge_radius";
      m_edgeAttribute << qMakePair(QString("edge_radius"), rad);
    }

  for(int i=0; i<nvat; i++)
    vat[i].clear();
  delete [] vat;
}
Esempio n. 15
0
static bool loadDetailsFromXML(const QString &filename, FileDetails *details)
{
    QDomDocument doc("mydocument");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return false;

    if (!doc.setContent(&file))
    {
        file.close();
        return false;
    }
    file.close();

    QString docType = doc.doctype().name();

    if (docType == "MYTHARCHIVEITEM")
    {
        QDomNodeList itemNodeList = doc.elementsByTagName("item");
        QString type, dbVersion;

        if (itemNodeList.count() < 1)
        {
            LOG(VB_GENERAL, LOG_ERR,
                "Couldn't find an 'item' element in XML file");
            return false;
        }

        QDomNode n = itemNodeList.item(0);
        QDomElement e = n.toElement();
        type = e.attribute("type");
        dbVersion = e.attribute("databaseversion");
        if (type == "recording")
        {
            QDomNodeList nodeList = e.elementsByTagName("recorded");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'recorded' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                        details->title = e.text();

                    if (e.tagName() == "subtitle")
                        details->subtitle = e.text();

                    if (e.tagName() == "starttime")
                        details->startTime = MythDate::fromString(e.text());

                    if (e.tagName() == "description")
                        details->description = e.text();
                }
                n = n.nextSibling();
            }

            // get channel info
            n = itemNodeList.item(0);
            e = n.toElement();
            nodeList = e.elementsByTagName("channel");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'channel' element in XML file");
                details->chanID = "";
                details->chanNo = "";
                details->chanName = "";
                details->callsign =  "";
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            details->chanID = e.attribute("chanid");
            details->chanNo = e.attribute("channum");
            details->chanName = e.attribute("name");
            details->callsign =  e.attribute("callsign");
            return true;
        }
        else if (type == "video")
        {
            QDomNodeList nodeList = e.elementsByTagName("videometadata");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'videometadata' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                    {
                        details->title = e.text();
                        details->subtitle = "";
                        details->startTime = QDateTime();
                    }

                    if (e.tagName() == "plot")
                    {
                        details->description = e.text();
                    }
                }
                n = n.nextSibling();
            }

            details->chanID = "N/A";
            details->chanNo = "N/A";
            details->chanName = "N/A";
            details->callsign = "N/A";

            return true;
        }
    }

    return false;
}
Esempio n. 16
0
QDomNode drawInterface::getParameterNode(QString pname, QDomNode& node) {
    if(node.isNull())
        return node;
    QDomNodeList n = node.toElement().elementsByTagName(pname);
    return n.item(0);
}
Esempio n. 17
0
void ReportSectionDetail::initFromXML(QDomNode & section) {
    QDomNodeList nl = section.childNodes();
    QDomNode node;
    QString n;

    // some code to handle old style defs
    QString o_name = "unnamed";
    QString o_column = QString::null;
    bool old_head = FALSE;
    QDomNode o_head;
    bool old_foot = FALSE;
    QDomNode o_foot;

    for(unsigned int i = 0; i < nl.count(); i++) {
        node = nl.item(i);
        n = node.nodeName();
        if(n == "name") {
            o_name = node.firstChild().nodeValue();
            setTitle(o_name);
        } else if(n == "group") {
            ReportSectionDetailGroup * rsdg = new ReportSectionDetailGroup("unnamed", this, this);
            QDomNodeList gnl = node.childNodes();
            QDomNode gnode;
            bool show_head = FALSE;
            bool show_foot = FALSE;
            for(unsigned int gi = 0; gi < gnl.count(); gi++) {
                gnode = gnl.item(gi);
                if(gnode.nodeName() == "name") {
                    rsdg->setTitle(gnode.firstChild().nodeValue());
                } else if(gnode.nodeName() == "column") {
                    rsdg->setColumn(gnode.firstChild().nodeValue());
                } else if(gnode.nodeName() == "head") {
                    rsdg->getGroupHead()->initFromXML(gnode);
                    rsdg->showGroupHead(TRUE);
                    show_head = TRUE;
                } else if(gnode.nodeName() == "foot") {
                    rsdg->getGroupFoot()->initFromXML(gnode);
                    rsdg->showGroupFoot(TRUE);
                    show_foot = TRUE;
                } else {
                    qDebug("encountered unknown element while parsing group element: %s", gnode.nodeName().latin1());
                }
            }
            insertSection(groupSectionCount(), rsdg);
            rsdg->showGroupHead(show_head);
            rsdg->showGroupFoot(show_foot);
        } else if(n == "grouphead") {
            o_head = node;
            old_head = TRUE;
        } else if(n == "groupfoot") {
            o_foot = node;
            old_foot = TRUE;
        } else if(n == "detail") {
            // need to pull out the query key values
            QDomNode key = node.namedItem("key");
            if(key.isNull()) {
                qDebug("Did not find a key element while parsing detail section");
            } else {
                QDomNodeList knl = key.childNodes();
                QDomNode knode;
                for(unsigned int ki = 0; ki < knl.count(); ki++) {
                    knode = knl.item(ki);
                    if(knode.nodeName() == "query") {
                        setQuery(knode.firstChild().nodeValue());
                    } else if(knode.nodeName() == "column") {
                        o_column = knode.firstChild().nodeValue();
                    } else {
                        qDebug("encountered unknown element while parsing key element: %s", knode.nodeName().latin1());
                    }
                }
            }
            _detail->initFromXML(node);
        } else {
            // unknown element
            qDebug("while parsing section encountered and unknown element: %s", n.latin1());
        }
    }

    if(old_head || old_foot) {
        ReportSectionDetailGroup * rsdg = new ReportSectionDetailGroup(o_name, this, this);

        rsdg->setColumn(o_column);
        if(old_head)
            rsdg->getGroupHead()->initFromXML(o_head);
        if(old_foot)
            rsdg->getGroupFoot()->initFromXML(o_foot);

        // if we encountered this situation then we shouldn't have
        // any other sections but to be sure we will just tack this one
        // onto the end
        insertSection(groupSectionCount(), rsdg);

        rsdg->showGroupHead(old_head);
        rsdg->showGroupFoot(old_foot);
    }
}
Esempio n. 18
0
QDomNode drawInterface::getParameterNode(QString pname, QDomElement& elem) {
    QDomNodeList n = elem.elementsByTagName(pname);
    return n.item(0);
}
/**
\param nodo
\param valoract
\param valorant
**/
void BcCuentasAnualesImprimirView::agregaValores ( const QDomNode &nodo, const QString &valoract, const QString &valorant )
{
    BL_FUNC_DEBUG
    QDomElement enodo = nodo.toElement();
    BlFixed fvaloract ( valoract );
    BlFixed fvalorant ( valorant );
    /// Miramos las opciones pasadas
    if ( nodo.nodeName() == QString ( "OPERADOR" ) ) {
        QDomNodeList opcs = enodo.elementsByTagName ( "OPCIONES" );
        for ( int i = 0; i < opcs.count(); i++ ) {
            QDomElement op = opcs.item ( i ).toElement();
            QString opciones = op.text();
            if ( opciones == "POSITIVO" ) {
                if ( fvaloract < 0 )
                    fvaloract = fvaloract * -1;
                if ( fvalorant < 0 )
                    fvalorant = fvalorant * -1;
            } // end if
            if ( opciones == "NEGATIVO" ) {
                if ( fvaloract > 0 )
                    fvaloract = fvaloract * -1;
                if ( fvalorant > 0 )
                    fvalorant = fvalorant * -1;
            } // end if
            if ( opciones == "RESTAR" ) {
                fvaloract = fvaloract * -1;
                fvalorant = fvalorant * -1;
            } // end if
        } // end for
    } else {
        QDomNodeList opcs = nodo.parentNode().toElement().elementsByTagName ( "OPCIONES" );
        for ( int i = 0; i < opcs.count(); i++ ) {
            QDomElement op = opcs.item ( i ).toElement();
            QString opciones = op.text();
            if ( opciones == "MAYORCERO" ) {
                if ( fvaloract < 0 )
                    fvaloract = 0;
                if ( fvalorant < 0 )
                    fvalorant = 0;
            } // end if
            if ( opciones == "MENORCERO" ) {
                if ( fvaloract > 0 )
                    fvaloract = 0;
                if ( fvalorant > 0 )
                    fvalorant = 0;
            } // end if
        } // end for
    } // end if
    QDomElement valoract1 = m_doc.createElement ( "VALORACT" );
    valoract1.setTagName ( "VALORACT" );
    QDomText etx = m_doc.createTextNode ( fvaloract.toQString() );
    valoract1.appendChild ( etx );
    QDomElement valorant1 = m_doc.createElement ( "VALORANT" );
    valorant1.setTagName ( "VALORANT" );
    QDomText etc = m_doc.createTextNode ( fvalorant.toQString() );
    valorant1.appendChild ( etc );
    QDomNode n = nodo;
    enodo.appendChild ( valoract1 );
    enodo.appendChild ( valorant1 );
    
}
Esempio n. 20
0
QDBusIntrospection::Interfaces
QDBusXmlParser::interfaces() const
{
    QDBusIntrospection::Interfaces retval;

    if (m_node.isNull())
        return retval;

    QDomNodeList interfaceList = m_node.elementsByTagName(QLatin1String("interface"));
    for (int i = 0; i < interfaceList.count(); ++i)
    {
        QDomElement iface = interfaceList.item(i).toElement();
        QString ifaceName = iface.attribute(QLatin1String("name"));
        if (iface.isNull())
            continue;           // for whatever reason
        if (!QDBusUtil::isValidInterfaceName(ifaceName)) {
            qDBusParserError("Invalid D-BUS interface name '%s' found while parsing introspection",
                             qPrintable(ifaceName));
            continue;
        }

        QDBusIntrospection::Interface *ifaceData = new QDBusIntrospection::Interface;
        ifaceData->name = ifaceName;
        {
            // save the data
            QTextStream ts(&ifaceData->introspection);
            iface.save(ts,2);
        }

        // parse annotations
        ifaceData->annotations = parseAnnotations(iface);

        // parse methods
        QDomNodeList list = iface.elementsByTagName(QLatin1String("method"));
        for (int j = 0; j < list.count(); ++j)
        {
            QDomElement method = list.item(j).toElement();
            QString methodName = method.attribute(QLatin1String("name"));
            if (method.isNull())
                continue;
            if (!QDBusUtil::isValidMemberName(methodName)) {
                qDBusParserError("Invalid D-BUS member name '%s' found in interface '%s' while parsing introspection",
                                 qPrintable(methodName), qPrintable(ifaceName));
                continue;
            }

            QDBusIntrospection::Method methodData;
            methodData.name = methodName;

            // parse arguments
            methodData.inputArgs = parseArgs(method, QLatin1String("in"), true);
            methodData.outputArgs = parseArgs(method, QLatin1String("out"), false);
            methodData.annotations = parseAnnotations(method);

            // add it
            ifaceData->methods.insert(methodName, methodData);
        }

        // parse signals
        list = iface.elementsByTagName(QLatin1String("signal"));
        for (int j = 0; j < list.count(); ++j)
        {
            QDomElement signal = list.item(j).toElement();
            QString signalName = signal.attribute(QLatin1String("name"));
            if (signal.isNull())
                continue;
            if (!QDBusUtil::isValidMemberName(signalName)) {
                qDBusParserError("Invalid D-BUS member name '%s' found in interface '%s' while parsing introspection",
                                 qPrintable(signalName), qPrintable(ifaceName));
                continue;
            }

            QDBusIntrospection::Signal signalData;
            signalData.name = signalName;

            // parse data
            signalData.outputArgs = parseArgs(signal, QLatin1String("out"), true);
            signalData.annotations = parseAnnotations(signal);

            // add it
            ifaceData->signals_.insert(signalName, signalData);
        }

        // parse properties
        list = iface.elementsByTagName(QLatin1String("property"));
        for (int j = 0; j < list.count(); ++j)
        {
            QDomElement property = list.item(j).toElement();
            QString propertyName = property.attribute(QLatin1String("name"));
            if (property.isNull())
                continue;
            if (!QDBusUtil::isValidMemberName(propertyName)) {
                qDBusParserError("Invalid D-BUS member name '%s' found in interface '%s' while parsing introspection",
                                 qPrintable(propertyName), qPrintable(ifaceName));
                continue;
            }

            QDBusIntrospection::Property propertyData;

            // parse data
            propertyData.name = propertyName;
            propertyData.type = property.attribute(QLatin1String("type"));
            propertyData.annotations = parseAnnotations(property);

            if (!QDBusUtil::isValidSingleSignature(propertyData.type)) {
                // cannot be!
                qDBusParserError("Invalid D-BUS type signature '%s' found in property '%s.%s' while parsing introspection",
                                 qPrintable(propertyData.type), qPrintable(ifaceName),
                                 qPrintable(propertyName));
            }

            QString access = property.attribute(QLatin1String("access"));
            if (access == QLatin1String("read"))
                propertyData.access = QDBusIntrospection::Property::Read;
            else if (access == QLatin1String("write"))
                propertyData.access = QDBusIntrospection::Property::Write;
            else if (access == QLatin1String("readwrite"))
                propertyData.access = QDBusIntrospection::Property::ReadWrite;
            else {
                qDBusParserError("Invalid D-BUS property access '%s' found in property '%s.%s' while parsing introspection",
                                 qPrintable(access), qPrintable(ifaceName),
                                 qPrintable(propertyName));
                continue;       // invalid one!
            }

            // add it
            ifaceData->properties.insert(propertyName, propertyData);
        }

        // add it
        retval.insert(ifaceName, QSharedDataPointer<QDBusIntrospection::Interface>(ifaceData));
    }

    return retval;
}
/**
\return
**/
void BcCuentasAnualesImprimirView::on_mui_aceptar_clicked()
{
    BL_FUNC_DEBUG
    QString finicial = mui_fechainicial->text();
    QString ffinal = mui_fechafinal->text();
    QString finicial1 = mui_fechainicial1->text();
    QString ffinal1 = mui_fechafinal1->text();
    if ( finicial1 == "" ) {
        finicial1 = finicial;
    } // end if
    if ( ffinal1 == "" ) {
        ffinal1 = ffinal;
    }
    if ( finicial == "" || ffinal == "" ) {
        return;
    } // end if


    /** Version sin ARBOL

        /// Ponemos todos los valores de las cuentas. Hacemos la carga.
        QDomNodeList lcuentas = m_doc.elementsByTagName("CUENTA");
        for (int i = 0; i < lcuentas.count(); i++) {
            QDomNode cuenta = lcuentas.item(i);
            QDomElement e1 = cuenta.toElement(); /// try to convert the node to an element.
            if( !e1.isNull() ) { /// the node was really an element.
                /// Este es el c&aacute;lculo de los saldos para la cuenta.
                QString query = "SELECT saldototal('" + e1.text() + "','" + finicial + "','" + ffinal + "') AS valoract, saldototal('" + e1.text() + "','" + finicial1 + "','" + ffinal1 + "') AS valorant";
                BlDbRecordSet *cur = mainCompany()->loadQuery(query);
                if (!cur->eof()) {
                    QString valoract = cur->value("valoract");
                    QString valorant = cur->value("valorant");
                    QDomNode c = e1.parentNode();
                    agregaValores(c, valoract, valorant);
                } // end if
                delete cur;
            } // end if
        } // end for

    **/

    /** Version con ARBOL: mas rollo de codigo pero muuuucho mas eficiente **/
    /// Vamos a crear un arbol en la memoria dinamica con
    /// los distintos niveles de cuentas.


    /// Primero, averiguaremos la cantidad de ramas iniciales (tantos como
    /// numero de cuentas de nivel 2) y las vamos creando.
    mainCompany() ->begin();
    QString query = "SELECT *, nivel(codigo) AS nivel FROM cuenta ORDER BY codigo";
    BlDbRecordSet *ramas;
    ramas = mainCompany() ->loadQuery ( query, "Ramas" );
    BcPlanContableArbol *arbolP1, *arbolP2; /// un arbol por cada periodo
    arbolP1 = new BcPlanContableArbol;
    arbolP2 = new BcPlanContableArbol;
    while ( !ramas->eof() ) {
        if ( atoi ( ramas->value( "nivel" ).toLatin1().constData() ) == 2 ) { /// Cuenta ra&iacute;z.
            arbolP1->nuevaRama ( ramas );
            arbolP2->nuevaRama ( ramas );
        } // end if
        ramas->nextRecord();
    } // end while
    arbolP1->inicializa ( ramas );
    arbolP2->inicializa ( ramas );
    delete ramas;
    mainCompany() ->commit();

    QRegExp rx ( "^.*perdidas y ganancias.*$" ); /// filtro para saber si es el de perdidas y ganancias
    rx.setCaseSensitivity ( Qt::CaseInsensitive );
    QString asiento;
    /// Discernimos entre Balances y Cuenta de Resultados
    if ( rx.exactMatch ( m_doc.elementsByTagName ( "TITULO" ).item ( 0 ).toElement().text() ) )
        /// Hay que excluir el asiento de Regularizacion para el calculo de beneficios o perdidas si existe ya en el periodo
        asiento = "%Asiento de Regularizaci%";
    else
        asiento = "%Asiento de Cierre%"; /// No hay que tener en cuenta el asiento de cierre para obtener los saldos

    /// OJO!! Antes de nada, hay que calcular el asiento de REGULARIZACION que nos guarda el resultado en la 129
    BcAsientoView *asientoReg;

        int resur = g_plugins->run ( "SNewBcAsientoView", (BcCompany *) mainCompany() );
        if ( ! resur) {
            blMsgInfo("No se pudo crear instancia de asientos");
            return;
        } // end if
        asientoReg = (BcAsientoView *) g_plugParams;
//    ( ( BcCompany * ) mainCompany() ) ->regularizaempresa ( finicial, ffinal );
    asientoReg ->asientoRegularizacion ( finicial, ffinal );

    /// Ahora, recopilamos todos los apuntes agrupados por cuenta para poder
    /// establecer as&iacute; los valores de cada cuenta para el periodo 1.
    mainCompany() ->begin();
    query = "SELECT cuenta.idcuenta, numapuntes, cuenta.codigo, saldoant, debe, haber, saldo, debeej, haberej, saldoej FROM (SELECT idcuenta, codigo FROM cuenta) AS cuenta NATURAL JOIN (SELECT idcuenta, count(idcuenta) AS numapuntes,sum(debe) AS debeej, sum(haber) AS haberej, (sum(debe)-sum(haber)) AS saldoej FROM apunte WHERE EXTRACT(year FROM fecha) = EXTRACT(year FROM timestamp '" + finicial + "') GROUP BY idcuenta) AS ejercicio LEFT OUTER JOIN (SELECT idcuenta,sum(debe) AS debe, sum(haber) AS haber, (sum(debe)-sum(haber)) AS saldo FROM apunte WHERE fecha >= '" + finicial + "' AND fecha <= '" + ffinal + "' AND conceptocontable NOT SIMILAR TO '" + asiento + "' GROUP BY idcuenta) AS periodo ON periodo.idcuenta=ejercicio.idcuenta LEFT OUTER JOIN (SELECT idcuenta, (sum(debe)-sum(haber)) AS saldoant FROM apunte WHERE fecha < '" + finicial + "' GROUP BY idcuenta) AS anterior ON cuenta.idcuenta=anterior.idcuenta ORDER BY codigo";
    BlDbRecordSet *hojas;
    hojas = mainCompany() ->loadQuery ( query, "Periodo1" );
    /// Para cada cuenta con sus saldos calculados hay que actualizar hojas del &aacute;rbol.
    while ( !hojas->eof() ) {
        arbolP1->actualizaHojas ( hojas );
        hojas->nextRecord();
    } // end while
    mainCompany() ->commit();
    asientoReg->on_mui_borrar_clicked ( false ); /// borramos el asiento temporal creado indicando que no queremos confirmacion

    /// Para el segundo periodo, calculamos el asiento de REGULARIZACION que nos guarda el resultado en la 129
//    ( ( BcCompany * ) mainCompany() ) ->regularizaempresa ( finicial1, ffinal1 );
    asientoReg ->asientoRegularizacion ( finicial1, ffinal1 );
//    asientoReg = ( ( BcCompany * ) mainCompany() ) ->intapuntsempresa2();

    /// Ahora, recopilamos todos los apuntes agrupados por cuenta para poder
    /// establecer as&iacute; los valores de cada cuenta para el periodo 2.
    mainCompany() ->begin();
    query = "SELECT cuenta.idcuenta, numapuntes, cuenta.codigo, saldoant, debe, haber, saldo, debeej, haberej, saldoej FROM (SELECT idcuenta, codigo FROM cuenta) AS cuenta NATURAL JOIN (SELECT idcuenta, count(idcuenta) AS numapuntes,sum(debe) AS debeej, sum(haber) AS haberej, (sum(debe)-sum(haber)) AS saldoej FROM apunte WHERE EXTRACT(year FROM fecha) = EXTRACT(year FROM timestamp '" + finicial1 + "') GROUP BY idcuenta) AS ejercicio LEFT OUTER JOIN (SELECT idcuenta,sum(debe) AS debe, sum(haber) AS haber, (sum(debe)-sum(haber)) AS saldo FROM apunte WHERE fecha >= '" + finicial1 + "' AND fecha <= '" + ffinal1 + "' AND conceptocontable NOT SIMILAR TO '" + asiento + "' GROUP BY idcuenta) AS periodo ON periodo.idcuenta=ejercicio.idcuenta LEFT OUTER JOIN (SELECT idcuenta, (sum(debe)-sum(haber)) AS saldoant FROM apunte WHERE fecha < '" + finicial1 + "' GROUP BY idcuenta) AS anterior ON cuenta.idcuenta=anterior.idcuenta ORDER BY codigo";
    hojas = mainCompany() ->loadQuery ( query, "Periodo2" );
    /// Para cada cuenta con sus saldos calculados hay que actualizar hojas del &aacute;rbol.
    while ( !hojas->eof() ) {
        arbolP2->actualizaHojas ( hojas );
        hojas->nextRecord();
    } // end while
    delete hojas;
    mainCompany() ->commit();
    asientoReg->on_mui_borrar_clicked ( false ); /// borramos indicando que no queremos confirmacion

    QDomNodeList lcuentas = m_doc.elementsByTagName ( "CUENTA" );
    for ( int i = 0; i < lcuentas.count(); i++ ) {
        QDomNode cuenta = lcuentas.item ( i );
        QDomElement e1 = cuenta.toElement();
        QString valorP1, valorP2;
        BlFixed valor = BlFixed ( "0.00" );
        if ( !e1.isNull() ) {
            if ( arbolP1->irHoja ( e1.text() ) )
                valor = BlFixed ( arbolP1->hojaActual ( "saldo" ) );
            else
                valor = BlFixed ( "0.00" );
            valorP1 = valor.toQString();
            if ( arbolP2->irHoja ( e1.text() ) )
                valor = BlFixed ( arbolP2->hojaActual ( "saldo" ) );
            else
                valor = BlFixed ( "0.00" );
            valorP2 = valor.toQString();
            QDomNode c = e1.parentNode();
            agregaValores ( c, valorP1, valorP2 );
        } // end if
    } // end for

    /// Eliminamos el &aacute;rbol y cerramos la conexi&oacute;n con la BD.
    delete arbolP1;
    delete arbolP2;

    /** Fin de la version con ARBOL **/

    /// Hacemos el calculo recursivo del balance.
    bool terminado = false;
    while ( !terminado ) {
        terminado = true;
        /// Recogemos los valores de cuenta.
        QDomNodeList litems = m_doc.elementsByTagName ( "FORMULA" );
        for ( int i = 0; i < litems.count(); i++ ) {
            QDomNode item = litems.item ( i );
            QDomElement e1 = item.toElement(); /// Try to convert the node to an element.
            if ( !e1.isNull() ) { /// The node was really an element.
                terminado &= procesaFormula ( item );
            } // end if
        } // end for
    } // end while

    /// Una vez que tenemos el objeto bien generado y a punto pasamos a la generacion del PDF.
    imprimir ( finicial, ffinal, finicial1, ffinal1 );
    
}
bool Parser::process(int parsingMode)
{
  m_parsingMode = parsingMode;
  ngrt4n::clearCoreData(*m_cdata);

  m_dotContent.clear();
  QDomDocument xmlDoc;
  QDomElement xmlRoot;


  QFile file(m_descriptionFile);
  if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) {
    m_lastErrorMsg = QObject::tr("Unable to open the file %1").arg(m_descriptionFile);
    Q_EMIT errorOccurred(m_lastErrorMsg);
    file.close();
    return false;
  }

  if (!xmlDoc.setContent(&file)) {
    file.close();
    m_lastErrorMsg = QObject::tr("Error while parsing the file %1").arg(m_descriptionFile);
    Q_EMIT errorOccurred(m_lastErrorMsg);
    return false;
  }
  file.close(); // The content of the file is already in memory

  xmlRoot = xmlDoc.documentElement();
  m_cdata->monitor = xmlRoot.attribute("monitor").toInt();
  m_cdata->format_version = xmlRoot.attribute("compat").toDouble();
  QDomNodeList services = xmlRoot.elementsByTagName("Service");

  NodeT node;
  qint32 serviceCount = services.length();
  for (qint32 srv = 0; srv < serviceCount; ++srv) {
    QDomElement service = services.item(srv).toElement();
    node.parent.clear();
    node.monitored = false;
    node.id = service.attribute("id").trimmed();
    node.type = service.attribute("type").toInt();
    node.sev = node.sev_prop = ngrt4n::Unknown;
    node.sev_crule = service.attribute("statusCalcRule").toInt();
    node.sev_prule = service.attribute("statusPropRule").toInt();
    node.icon = service.firstChildElement("Icon").text().trimmed();
    node.name = service.firstChildElement("Name").text().trimmed();
    node.description = service.firstChildElement("Description").text().trimmed();
    node.alarm_msg = service.firstChildElement("AlarmMsg").text().trimmed();
    node.notification_msg = service.firstChildElement("NotificationMsg").text().trimmed();
    node.child_nodes = service.firstChildElement("SubServices").text().trimmed();
    node.weight = (m_cdata->format_version >= 3.1) ? service.attribute("weight").toDouble() : ngrt4n::WEIGHT_UNIT;

    if (node.sev_crule == CalcRules::WeightedAverageWithThresholds) {
      QString thdata = service.firstChildElement("Thresholds").text().trimmed();
      node.thresholdLimits = ThresholdHelper::dataToList(thdata);
      qSort(node.thresholdLimits.begin(), node.thresholdLimits.end(), ThresholdLessthanFnt());
    }

    node.check.status = -1;
    if (node.icon.isEmpty()) node.icon = ngrt4n::DEFAULT_ICON;

    switch(node.type) {
      case NodeType::BusinessService:
        insertBusinessServiceNode(node);
        break;
      case NodeType::ITService:
        insertITServiceNode(node);
        break;
      case NodeType::ExternalService:
        insertExternalServiceNode(node);
        break;
      default:
        break;
    }
  }

  updateNodeHierachy();
  saveCoordinatesFile();

  if (m_parsingMode == ParsingModeDashboard)
    return parseDotResult();

  return true;
}
Esempio n. 23
0
int processTables(QDomNode tableNodeToProcess, QDomNode dataNodeToProcess) {
    QString tableName;
    QDomNodeList recordsNodesList;
    QDomNode recordNode;
    QDomNode tableNode;
    QString fieldsStatement;
    QDomNode childTableNode;
    QString fieldName;
    bool processedData = false;

    //Get the table name and set how deep the node is in the tree
    tableName = tableNodeToProcess.toElement().attribute("mysqlcode", "None");
    nodeDepth = nodeDepth + 1;

    //Get the records from the data using the table name
    //First check if the main table has been processed and pick its name correctly
    //This is caused by the fact that the main table in the manifest and the data might not have the same name
    if (tableName == vManifestMainTable) {
        recordsNodesList = dataDoc.elementsByTagName(vDatafileBaseNode);
    }
    else {
        if (tableName.startsWith(vManifestMainTable)) {
            recordsNodesList = dataNodeToProcess.toElement().elementsByTagName(tableName.mid(vManifestMainTable.length() + 1));
        }
        else {
            recordsNodesList = dataNodeToProcess.toElement().elementsByTagName(tableName);
        }
    }

    if (recordsNodesList.count() > 0) {
        for (int recCount = 0; recCount <= recordsNodesList.count() - 1; recCount++) {
            processedData = false;
            recordNode  = recordsNodesList.item(recCount);

            //Get the current table node from manifest
            for(int tcount = 0; tableNodesList.count(); tcount++) {
                if(tableNodesList.item(tcount).toElement().attribute("mysqlcode", "None") == tableName) {
                    tableNode = tableNodesList.item(tcount);
                    break;
                }
            }

            //Pass through the table child nodes to get the field names
            fieldsStatement = "";

            childTableNode = tableNode.firstChild();

            while (!childTableNode.isNull()) {
                if (childTableNode.toElement().tagName() == "field") {
                    //Get the field name and use in creating the fields statement
                    fieldName = childTableNode.toElement().attribute("mysqlcode", "None");
                    fieldsStatement = fieldsStatement + fieldName + ", ";
                }
                else {
                    //Encountered a table get the record values under this parent record and do process again
                    if (processedData == false) {
                        processTableData(tableNode, recordNode, tableName, fieldsStatement, QString::number(recCount + 1));
                        processedData = true;
                    }

                    processTables(childTableNode, recordNode);
                }

                //Get the next child table node
                childTableNode = childTableNode.nextSibling();
            }

            //If no table was encountered within the table being processed
            if (processedData == false) {
                processTableData(tableNode, recordNode, tableName, fieldsStatement, QString::number(recCount + 1));
            }
        }
    }

    //Current table finished reduce nodeDepth
    nodeDepth = nodeDepth - 1;

    return 0;
}
Esempio n. 24
0
/**

Restore any optional properties found in "doc" to "properties".

properties tags for all optional properties.  Within that there will be scope
tags.  In the following example there exist one property in the "fsplugin"
scope.  "layers" is a list containing three string values.

\verbatim
<properties>
  <fsplugin>
    <foo type="int" >42</foo>
    <baz type="int" >1</baz>
    <layers type="QStringList" >
      <value>railroad</value>
      <value>airport</value>
    </layers>
    <xyqzzy type="int" >1</xyqzzy>
    <bar type="double" >123.456</bar>
    <feature_types type="QStringList" >
       <value>type</value>
    </feature_types>
  </fsplugin>
</properties>
\endverbatim

@param doc xml document
@param project_properties should be the top QgsPropertyKey node.

*/
static
void
_getProperties( QDomDocument const &doc, QgsPropertyKey & project_properties )
{
  QDomNodeList properties = doc.elementsByTagName( "properties" );

  if ( properties.count() > 1 )
  {
    QgsDebugMsg( "there appears to be more than one ``properties'' XML tag ... bailing" );
    return;
  }
  else if ( properties.count() < 1 )  // no properties found, so we're done
  {
    return;
  }

  // item(0) because there should only be ONE
  // "properties" node
  QDomNodeList scopes = properties.item( 0 ).childNodes();

  if ( scopes.count() < 1 )
  {
    QgsDebugMsg( "empty ``properties'' XML tag ... bailing" );
    return;
  }

  QDomNode propertyNode = properties.item( 0 );

  if ( ! project_properties.readXML( propertyNode ) )
  {
    QgsDebugMsg( "Project_properties.readXML() failed" );
  }

#if 0
// DEPRECATED as functionality has been shoved down to QgsProperyKey::readXML()
  size_t i = 0;
  while ( i < scopes.count() )
  {
    QDomNode curr_scope_node = scopes.item( i );

    qDebug( "found %d property node(s) for scope %s",
            curr_scope_node.childNodes().count(),
            curr_scope_node.nodeName().utf8().constData() );

    QString key( curr_scope_node.nodeName() );

    QgsPropertyKey * currentKey =
      dynamic_cast<QgsPropertyKey*>( project_properties.find( key ) );

    if ( ! currentKey )
    {
      // if the property key doesn't yet exist, create an empty instance
      // of that key

      currentKey = project_properties.addKey( key );

      if ( ! currentKey )
      {
        qDebug( "%s:%d unable to add key", __FILE__, __LINE__ );
      }
    }

    if ( ! currentKey->readXML( curr_scope_node ) )
    {
      qDebug( "%s:%d unable to read XML for property %s", __FILE__, __LINE__,
              curr_scope_node.nodeName().utf8().constData() );
    }

    ++i;
  }
#endif
} // _getProperties
Esempio n. 25
0
bool DomConvenience::variantToElement(const QVariant& v, QDomElement& e)
{
	bool ok = true;

	clearAttributes(e);

	switch (v.type())
	{
		case QVariant::String:
			e.setTagName("string");
			e.setAttribute("value", v.toString());
			break;
#if 0
		case QVariant::CString:
			e.setTagName("string");
			e.setAttribute("value", v.toString());
			break;
#endif
		case QVariant::Int:
			e.setTagName("int");
			e.setAttribute("value", v.toInt());
			break;
		case QVariant::UInt:
			e.setTagName("uint");
			e.setAttribute("value", v.toUInt());
			break;
		case QVariant::Double:
			e.setTagName("double");
			e.setAttribute("value", v.toDouble());
			break;
		case QVariant::Bool:
			e.setTagName("bool");
			e.setAttribute("value", boolString(v.toBool()));
			break;
		case QVariant::Color:
		{
			e.setTagName("color");
			QColor color = v.value<QColor>();
			e.setAttribute("red", color.red());
			e.setAttribute("green", color.green());
			e.setAttribute("blue", color.blue());
		}
			break;
		case QVariant::Pen:
		{
			e.setTagName("pen");
			QPen pen = v.value<QPen>();
			e.setAttribute("red", pen.color().red());
			e.setAttribute("green", pen.color().green());
			e.setAttribute("blue", pen.color().blue());
			e.setAttribute("style", pen.style());
			e.setAttribute("cap", pen.capStyle());
			e.setAttribute("join", pen.joinStyle());
		}
			break;
		case QVariant::Brush:
		{
			e.setTagName("brush");
			QBrush brush = v.value<QBrush>();
			e.setAttribute("red", brush.color().red());
			e.setAttribute("green", brush.color().green());
			e.setAttribute("blue", brush.color().blue());
			e.setAttribute("style", brush.style());
		}
			break;
		case QVariant::Point:
		{
			e.setTagName("point");
			QPoint point = v.toPoint();
			e.setAttribute("x", point.x());
			e.setAttribute("y", point.y());
		}
			break;
		case QVariant::Rect:
		{
			e.setTagName("rect");
			QRect rect = v.toRect();
			e.setAttribute("x", rect.x());
			e.setAttribute("y", rect.y());
			e.setAttribute("width", rect.width());
			e.setAttribute("height", rect.height());
		}
			break;
		case QVariant::Size:
		{
			e.setTagName("size");
			QSize qsize = v.toSize();
			e.setAttribute("width", qsize.width());
			e.setAttribute("height", qsize.height());
		}
			break;
		case QVariant::Font:
		{
			e.setTagName("font");
			QFont f(v.value<QFont>());
			e.setAttribute("family", f.family());
			e.setAttribute("pointsize", f.pointSize());
			e.setAttribute("bold", boolString(f.bold()));
			e.setAttribute("italic", boolString(f.italic()));
			e.setAttribute("underline", boolString(f.underline()));
			e.setAttribute("strikeout", boolString(f.strikeOut()));
		}
			break;
		case QVariant::SizePolicy:
		{
			e.setTagName("sizepolicy");
			QSizePolicy sp(v.value<QSizePolicy>());
			e.setAttribute("hsizetype", sp.horData());
			e.setAttribute("vsizetype", sp.verData());
			e.setAttribute("horstretch", sp.horStretch());
			e.setAttribute("verstretch", sp.verStretch());
		}
			break;
		case QVariant::Cursor:
			e.setTagName("cursor");
			e.setAttribute("shape", v.value<QCursor>().shape());
			break;

		case QVariant::StringList:
		{
			e.setTagName("stringlist");
			int32_t j;

			QDomNode n;
			QDomNodeList stringNodeList = e.elementsByTagName("string");
			QDomElement stringElem;
			QStringList stringList = v.toStringList();
			QStringList::Iterator it = stringList.begin();

			for (j = 0;
				 ((j < (int32_t)stringNodeList.length()) && (it != stringList.end()));
				 j++)
			{
				// get the current string element
				stringElem = stringNodeList.item(j).toElement();

				// set it to the current string
				variantToElement(QVariant(*it), stringElem);

				// iterate to the next string
				++it;
			}

			// more nodes in previous stringlist then current, remove excess nodes
			if (stringNodeList.count() > stringList.count())
			{
				while (j < (int32_t)stringNodeList.count())
					e.removeChild(stringNodeList.item(j).toElement());
			}
			else if (j < (int32_t)stringList.count())
			{
				while (it != stringList.end())
				{
					// create a new element
					stringElem = m_doc.createElement("string");

					// set it to the currentstring
					variantToElement(QVariant(*it), stringElem);

					// append it to the current element
					e.appendChild(stringElem);

					// iterate to the next string
					++it;
				}
			}
		}
			break;

		case QVariant::KeySequence:
			e.setTagName("key");
			e.setAttribute("sequence", (QString)v.value<QKeySequence>().toString());
			break;

		case QVariant::ByteArray: // this is only for [u]int64_t
		{
			e.setTagName("data");

			// set the value
			e.setAttribute("value", getStringFromByteArray(v.toByteArray()));
		}
			break;

		default:
			qWarning("Don't know how to persist variant of type: %s (%d)!",
					 v.typeName(), v.type());
			ok = false;
			break;
	}

	return ok;
}
Esempio n. 26
0
/**
   Read map layers from project file


   @returns \code QPair< bool, QList<QDomNode> > \endcode
        bool is true if function worked; else is false.
     list contains nodes corresponding to layers that couldn't be loaded

   @note XML of form:

\verbatim
   <maplayer type="vector">
      <layername>Hydrop</layername>
      <datasource>/data/usgs/city_shp/hydrop.shp</datasource>
      <zorder>0</zorder>
      <provider>ogr</provider>
      <singlesymbol>
         <renderitem>
            <value>blabla</value>
            <symbol>
               <outlinecolor red="85" green="0" blue="255" />
               <outlinestyle>SolidLine</outlinestyle>
               <outlinewidth>1</outlinewidth>
               <fillcolor red="0" green="170" blue="255" />
               <fillpattern>SolidPattern</fillpattern>
            </symbol>
            <label>blabla</label>
         </renderitem>
      </singlesymbol>
      <label>0</label>
      <labelattributes>
         <label text="Label" field="" />
         <family name="Sans Serif" field="" />
         <size value="12" units="pt" field="" />
         <bold on="0" field="" />
         <italic on="0" field="" />
         <underline on="0" field="" />
         <color red="0" green="0" blue="0" field="" />
         <x field="" />
         <y field="" />
         <offset  units="pt" x="0" xfield="" y="0" yfield="" />
         <angle value="0" field="" />
         <alignment value="center" field="" />
      </labelattributes>
   </maplayer>
\endverbatim
*/
QPair< bool, QList<QDomNode> > QgsProject::_getMapLayers( QDomDocument const &doc )
{
  // Layer order is set by the restoring the legend settings from project file.
  // This is done on the 'readProject( ... )' signal

  QDomNodeList nl = doc.elementsByTagName( "maplayer" );

  // XXX what is this used for? QString layerCount( QString::number(nl.count()) );

  QString wk;

  QList<QDomNode> brokenNodes; // a list of Dom nodes corresponding to layers
  // that we were unable to load; this could be
  // because the layers were removed or
  // re-located after the project was last saved

  // process the map layer nodes

  if ( 0 == nl.count() )      // if we have no layers to process, bail
  {
    return qMakePair( true, brokenNodes ); // Decided to return "true" since it's
    // possible for there to be a project with no
    // layers; but also, more imporantly, this
    // would cause the tests/qgsproject to fail
    // since the test suite doesn't currently
    // support test layers
  }

  bool returnStatus = true;

  emit layerLoaded( 0, nl.count() );

  //Collect vector layers with joins.
  //They need to refresh join caches and symbology infos after all layers are loaded
  QList< QPair< QgsVectorLayer*, QDomElement > > vLayerList;

  for ( int i = 0; i < nl.count(); i++ )
  {
    QDomNode node = nl.item( i );
    QDomElement element = node.toElement();

    if ( element.attribute( "embedded" ) == "1" )
    {
      createEmbeddedLayer( element.attribute( "id" ), readPath( element.attribute( "project" ) ), brokenNodes, vLayerList );
      continue;
    }
    else
    {
      if ( !addLayer( element, brokenNodes, vLayerList ) )
      {
        returnStatus = false;
      }
    }
    emit layerLoaded( i + 1, nl.count() );
  }

  //Update field map of layers with joins and create join caches if necessary
  //Needs to be done here once all dependent layers are loaded
  QString errorMessage;
  QList< QPair< QgsVectorLayer*, QDomElement > >::iterator vIt = vLayerList.begin();
  for ( ; vIt != vLayerList.end(); ++vIt )
  {
    vIt->first->createJoinCaches();
    vIt->first->updateFieldMap();
    //for old symbology, it is necessary to read the symbology again after having the complete field map
    if ( !vIt->first->isUsingRendererV2() )
    {
      vIt->first->readSymbology( vIt->second, errorMessage );
    }
  }

  return qMakePair( returnStatus, brokenNodes );

} // _getMapLayers
void TabbedMainWindow::findUsers(QString hostname, QString usernamepassword, int condition1, QString condition2, QString argument, QListWidget * list, QListWidget * list2) {
    //First maybe we clear the dang list?!
    QString condition1String, condition2String;

    if (condition1 == 0) {
        condition1String = "enduser.firstname";
    } else if (condition1 == 1) {
        condition1String = "enduser.middlename";
    } else if (condition1 == 2) {
        condition1String = "enduser.lastname";
    } else if (condition1 == 3) {
        condition1String = "enduser.userid";
    } else if (condition1 == 4) {
        condition1String = "enduser.islocaluser";
    } else if (condition1 == 5) {
        condition1String = "enduser.telephonenumber";
    }

    if (condition2 == "Equals") {
        condition2String = "= '" + argument.toLower() + "'";
    } else if (condition2 == "Contains") {
        condition2String = "LIKE '%" + argument.toLower() + "%'";
    } else if (condition2 == "Begins with") {
        condition2String = "LIKE '" + argument.toLower() + "%'";
    } else if (condition2 == "Ends with") {
        condition2String = "LIKE '%" + argument.toLower() + "'";
    } else if (condition2 == "Is Empty") {
        condition2String = "IS NULL";
    } else if (condition2 == "Is not Empty") {
        condition2String = "IS NOT NULL";
    } else if (condition2 == "True") {
        condition2String = "= 't'";
    } else if (condition2 == "False") {
        condition2String = "= 'f'";
    }

    ProgressDialog progbar("CMClusters - Connecting...", "Please wait while a connection to the selected clusters are established!");
    progbar.show();
    QByteArray jsonString = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://www.cisco.com/AXL/API/8.5\">";
    if (condition1 == 4) {
        jsonString += "<soapenv:Body><ns:executeSQLQuery><sql>SELECT enduser.userid,enduser.firstname,enduser.middlename,enduser.lastname,enduser.islocaluser,enduser.telephonenumber from enduser where "
                + condition1String + condition2String + "</sql></ns:executeSQLQuery></SOAP-ENV:Envelope>";
    } else {
    jsonString += "<soapenv:Body><ns:executeSQLQuery><sql>SELECT enduser.userid,enduser.firstname,enduser.middlename,enduser.lastname,enduser.islocaluser,enduser.telephonenumber from enduser where lower("
            + condition1String + ") " + condition2String + "</sql></ns:executeSQLQuery></SOAP-ENV:Envelope>";
    }
    QByteArray postDataSize = QByteArray::number(jsonString.size());
    QUrl req("https://" + hostname.toLocal8Bit() + ":8443/axl/");
    QNetworkRequest request(req);

    request.setRawHeader("SOAPAction", "\"CUCM:DB ver=8.5 executeSQLQuery\"");
    request.setRawHeader("Authorization", "Basic " + usernamepassword.toLocal8Bit());
    request.setRawHeader("Content-Type", "text/xml");
    request.setRawHeader("Content-Length", postDataSize);

    QNetworkAccessManager test;
    QEventLoop loop;
    connect(&test, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
    QNetworkReply * reply = test.post(request, jsonString);
    reply->ignoreSslErrors(); // Ignore only unsigned later on
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
    loop.exec();

    QByteArray response = reply->readAll();
    QVariant statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute );

    if ( !statusCode.isValid() ) {
        qDebug() << "Failed...";
        qDebug() << statusCode.data();
    }

    int status = statusCode.toInt();

    if ( status != 200 ) {
        QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
        qDebug() << reason;
    } else {
        qDebug() << "Good reply";
        //qDebug() << response;
        QDomDocument doc;
        doc.setContent(response);
            QDomNodeList rates = doc.elementsByTagName("row");
            for (int i = 0; i < rates.size(); i++) {
                QString finalString;
                QDomNode n = rates.item(i);
                QDomElement firstname = n.firstChildElement("firstname");
                if (firstname.text() != "")
                    finalString = firstname.text() + " ";
                QDomElement middlename = n.firstChildElement("middlename");
                if (middlename.text() != "")
                    finalString += middlename.text() + " ";
                QDomElement lastname = n.firstChildElement("lastname");
                if (lastname.text() != " ")
                    finalString += lastname.text();
                QDomElement userid = n.firstChildElement("userid");
                finalString += " (" + userid.text() + ") ";
                QDomElement islocaluser = n.firstChildElement("islocaluser");
                QDomElement telephonenumber = n.firstChildElement("telephonenumber");
                    if (telephonenumber.text() != "") {
                        finalString += " [" + telephonenumber.text() + "]";
                    } else {
                        finalString += " [No Telephone Number]";
                    }
                QListWidgetItem* user = new QListWidgetItem(finalString);
                if (islocaluser.text() == "t") {
                    user->setBackground(QColor(0, 170, 255));
                    list2->addItem(user);
                } else {
                    user->setBackground(QColor(170, 0, 0));
                    list->addItem(user);
                }
            }
    }
}
Esempio n. 28
0
void MythBurn::loadEncoderProfiles()
{
    EncoderProfile *item = new EncoderProfile;
    item->name = "NONE";
    item->description = "";
    item->bitrate = 0.0f;
    m_profileList.append(item);

    // find the encoding profiles
    // first look in the ConfDir (~/.mythtv)
    QString filename = GetConfDir() +
            "/MythArchive/ffmpeg_dvd_" +
            ((gCoreContext->GetSetting("MythArchiveVideoFormat", "pal")
                .toLower() == "ntsc") ? "ntsc" : "pal") + ".xml";

    if (!QFile::exists(filename))
    {
        // not found yet so use the default profiles
        filename = GetShareDir() +
            "mytharchive/encoder_profiles/ffmpeg_dvd_" +
            ((gCoreContext->GetSetting("MythArchiveVideoFormat", "pal")
                .toLower() == "ntsc") ? "ntsc" : "pal") + ".xml";
    }

    LOG(VB_GENERAL, LOG_NOTICE,
        "MythArchive: Loading encoding profiles from " + filename);

    QDomDocument doc("mydocument");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return;

    if (!doc.setContent( &file ))
    {
        file.close();
        return;
    }
    file.close();

    QDomElement docElem = doc.documentElement();
    QDomNodeList profileNodeList = doc.elementsByTagName("profile");
    QString name, desc, bitrate;

    for (int x = 0; x < (int) profileNodeList.count(); x++)
    {
        QDomNode n = profileNodeList.item(x);
        QDomElement e = n.toElement();
        QDomNode n2 = e.firstChild();
        while (!n2.isNull())
        {
            QDomElement e2 = n2.toElement();
            if(!e2.isNull())
            {
                if (e2.tagName() == "name")
                    name = e2.text();
                if (e2.tagName() == "description")
                    desc = e2.text();
                if (e2.tagName() == "bitrate")
                    bitrate = e2.text();

            }
            n2 = n2.nextSibling();

        }

        EncoderProfile *item = new EncoderProfile;
        item->name = name;
        item->description = desc;
        item->bitrate = bitrate.toFloat();
        m_profileList.append(item);
    }
}
Esempio n. 29
0
/** Actually sends the sMethod action to the command URL specified
 *  in the constructor (url+[/]+sControlPath).
 *
 * \param sMethod method to be invoked. e.g. "SetChannel",
 *                "GetConnectionInfoResult"
 *
 * \param list Parsed as a series of key value pairs for the input params
 *             and then cleared and used for the output params.
 *
 * \param nErrCode set to zero on success, non-zero in case of error.
 *
 * \param sErrCode returns error description from device, when applicable.
 *
 * \param bInQtThread May be set to true if this is run from within
 *                    a QThread with a running an event loop.
 *
 * \return Returns a QDomDocument containing output parameters on success.
 */
QDomDocument SOAPClient::SendSOAPRequest(const QString &sMethod,
                                         QStringMap    &list,
                                         int           &nErrCode,
                                         QString       &sErrDesc,
                                         bool           bInQtThread)
{
    QUrl url(m_url);

    url.setPath(m_sControlPath);

    nErrCode = UPnPResult_Success;
    sErrDesc = "";

    QDomDocument xmlResult;
    if (m_sNamespace.isEmpty())
    {
        nErrCode = UPnPResult_MythTV_NoNamespaceGiven;
        sErrDesc = "No namespace given";
        return xmlResult;
    }

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------

    QHttpRequestHeader header("POST", sMethod, 1, 0);

    header.setValue("CONTENT-TYPE", "text/xml; charset=\"utf-8\"" );
    header.setValue("SOAPACTION",
                    QString("\"%1#%2\"").arg(m_sNamespace).arg(sMethod));

    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os.setCodec("UTF-8");

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope "
        " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\""
        " xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for (QStringMap::iterator it = list.begin(); it != list.end(); ++it)
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    QBuffer buff(&aBuffer);

    LOG(VB_UPNP, LOG_DEBUG,
        QString("SOAPClient(%1) sending:\n").arg(url.toString()) +
        header.toString() + QString("\n%1\n").arg(aBuffer.constData()));

    QString sXml =
        HttpComms::postHttp(url,
                            &header,
                            &buff, // QIODevice*
                            10000, // ms -- Technically should be 30ms per spec
                            3,     // retries
                            0,     // redirects
                            false, // allow gzip
                            NULL,  // login
                            bInQtThread,
                            QString() // userAgent, UPnP/1.0 very strict on
                                      // format if set
        );

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG, "SOAPClient response:\n" +
                            QString("%1\n").arg(sXml));

    // TODO handle timeout without response correctly.

    list.clear();

    QDomDocument doc;

    if (!doc.setContent(sXml, true, &sErrDesc, &nErrCode))
    {
        LOG(VB_UPNP, LOG_ERR,
            QString("SendSOAPRequest( %1 ) - Invalid response from %2")
                .arg(sMethod).arg(url.toString()) + 
            QString("%1: %2").arg(nErrCode).arg(sErrDesc));

        return xmlResult;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     =
        doc.elementsByTagNameNS(m_sNamespace, sResponseName);

    if (oNodeList.count() == 0)
    {
        // --------------------------------------------------------------
        // Must be a fault... parse it to return reason
        // --------------------------------------------------------------

        nErrCode = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorCode", 500);
        sErrDesc = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorDescription", "");
        if (sErrDesc.isEmpty())
            sErrDesc = QString("Unknown #%1").arg(nErrCode);

        QDomNode oNode  = FindNode( "Envelope/Body/Fault", doc );

        oNode = xmlResult.importNode( oNode, true );
        xmlResult.appendChild( oNode );

        return xmlResult;
    }

    QDomNode oMethod = oNodeList.item(0);
    if (oMethod.isNull())
        return xmlResult;

    QDomNode oNode = oMethod.firstChild(); 
    for (; !oNode.isNull(); oNode = oNode.nextSibling())
    {
        QDomElement e = oNode.toElement();
        if (e.isNull())
            continue;

        QString sName  = e.tagName();
        QString sValue = "";
    
        QDomText  oText = oNode.firstChild().toText();
    
        if (!oText.isNull())
            sValue = oText.nodeValue();

        list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                    QUrl::fromPercentEncoding(sValue.toUtf8()));
    }

    // Create copy of oMethod that can be used with xmlResult.

    oMethod = xmlResult.importNode( oMethod.firstChild(), true  );

    // importNode does not attach the new nodes to the document,
    // do it here.

    xmlResult.appendChild( oMethod );

    return xmlResult;
}
Esempio n. 30
0
void Glossary::buildGlossaryTree()
{
	QFile cacheFile(m_cacheFile);
	if ( !cacheFile.open( IO_ReadOnly ) )
		return;

	QDomDocument doc;
	if ( !doc.setContent( &cacheFile ) )
		return;

	QDomNodeList sectionNodes = doc.documentElement().elementsByTagName( QString::fromLatin1( "section" ) );
	for ( unsigned int i = 0; i < sectionNodes.count(); i++ ) {
		QDomElement sectionElement = sectionNodes.item( i ).toElement();
		QString title = sectionElement.attribute( QString::fromLatin1( "title" ) );
		SectionItem *topicSection = new SectionItem( m_byTopicItem, title );

		QDomNodeList entryNodes = sectionElement.elementsByTagName( QString::fromLatin1( "entry" ) );
		for ( unsigned int j = 0; j < entryNodes.count(); j++ ) {
			QDomElement entryElement = entryNodes.item( j ).toElement();
			
			QString entryId = entryElement.attribute( QString::fromLatin1( "id" ) );
			if ( entryId.isNull() )
				continue;
				
			QDomElement termElement = childElement( entryElement, QString::fromLatin1( "term" ) );
			QString term = termElement.text().simplifyWhiteSpace();

			EntryItem *entry = new EntryItem(topicSection, term, entryId );
            m_idDict.insert( entryId, entry );

			SectionItem *alphabSection = 0L;
			for ( QListViewItemIterator it( m_alphabItem ); it.current(); it++ )
				if ( it.current()->text( 0 ) == term[ 0 ].upper() ) {
					alphabSection = static_cast<SectionItem *>( it.current() );
					break;
				}

			if ( !alphabSection )
				alphabSection = new SectionItem( m_alphabItem, term[ 0 ].upper() );

			new EntryItem( alphabSection, term, entryId );

			QDomElement definitionElement = childElement( entryElement, QString::fromLatin1( "definition" ) );
			QString definition = definitionElement.text().simplifyWhiteSpace();

			GlossaryEntryXRef::List seeAlso;

			QDomElement referencesElement = childElement( entryElement, QString::fromLatin1( "references" ) );
			QDomNodeList referenceNodes = referencesElement.elementsByTagName( QString::fromLatin1( "reference" ) );
			if ( referenceNodes.count() > 0 )
				for ( unsigned int k = 0; k < referenceNodes.count(); k++ ) {
					QDomElement referenceElement = referenceNodes.item( k ).toElement();

					QString term = referenceElement.attribute( QString::fromLatin1( "term" ) );
					QString id = referenceElement.attribute( QString::fromLatin1( "id" ) );
					
					seeAlso += GlossaryEntryXRef( term, id );
				}
			
			m_glossEntries.insert( entryId, new GlossaryEntry( term, definition, seeAlso ) );
		}
	}
}