Example #1
0
Node* Scene::findNode(const char* id, bool recursive, bool exactMatch) const
{
    assert(id);

    // Search immediate children first.
    for (Node* child = getFirstNode(); child != NULL; child = child->getNextSibling())
    {
        // Does this child's ID match?
        if ((exactMatch && child->_id == id) || (!exactMatch && child->_id.find(id) == 0))
        {
            return child;
        }
    }

    // Recurse.
    if (recursive)
    {
        for (Node* child = getFirstNode(); child != NULL; child = child->getNextSibling())
        {
            Node* match = child->findNode(id, true, exactMatch);
            if (match)
            {
                return match;
            }
        }
    }

    return NULL;
}
Example #2
0
unsigned int Scene::findNodes(const char* id, std::vector<Node*>& nodes, bool recursive, bool exactMatch) const
{
    assert(id);

    unsigned int count = 0;

    // Search immediate children first.
    for (Node* child = getFirstNode(); child != NULL; child = child->getNextSibling())
    {
        // Does this child's ID match?
        if ((exactMatch && child->_id == id) || (!exactMatch && child->_id.find(id) == 0))
        {
            nodes.push_back(child);
            ++count;
        }
    }

    // Recurse.
    if (recursive)
    {
        for (Node* child = getFirstNode(); child != NULL; child = child->getNextSibling())
        {
            count += child->findNodes(id, nodes, true, exactMatch);
        }
    }

    return count;
}
void GameObjectManager::addUnit(const char* filename, const char* name, GameObjectConstructorProc constructor)
{
    if (filename != NULL)
    {
        AutoRef<Scene> scene = Scene::load(filename)->Auto();
        Node* root = Node::create("root");
        root->setTag("dynamic");
        Node* child = scene->getFirstNode();
        Node* childNext;
        while (child != NULL)
        {
            childNext = child->getNextSibling();
            root->addChild(child);
            child = childNext;
        }
        root->setScale(CHARACTER_SCALE, CHARACTER_SCALE, CHARACTER_SCALE);
        scene->addNode(root);

        root = root->clone();
        Node* node = root->getFirstChild();
        while (node)
        {
            Animation* animation = node->getAnimation("animations");
            if (!animation)
            {
                animation = node->getAnimation(NULL);
            }
            if (animation)
            {
                std::string scenePath = Scene::getGPBPath(filename);
                int pos = scenePath.find_last_of('.');
                if (pos > 2)
                {
                    std::string animationPath = scenePath.substr(0, pos);
                    animationPath.append(".animation");
                    animation->createClips(animationPath.c_str());
                }
            }
            node = node->getNextSibling();
        }
        if (!_store)
        {
            _store = Scene::create("store")->Auto();
        }
        _store->addNode(root);
        _units[name] = GameUnit(root, constructor);
    }
    else
    {
        _units[name] = GameUnit(NULL, constructor);
    }
}
Example #4
0
void ConsoleTools::setLinkSource(const String &str){
  InputSource *linkSource = null;
  DocumentBuilder docbuilder;
  Document *linkSourceTree = null;
  try{
    linkSource = InputSource::newInstance(&str);
    linkSourceTree = docbuilder.parse(linkSource);
  }catch(Exception &e){
    docbuilder.free(linkSourceTree);
    throw e;
  }

  Node *elem = linkSourceTree->getDocumentElement();

  if (*elem->getNodeName() != "doclinks"){
    throw Exception(DString("Bad doclinks data file structure"));
  }

  elem = elem->getFirstChild();
  while(elem != null){
    if (elem->getNodeType() == Node::ELEMENT_NODE && *elem->getNodeName() == "links"){
      const String *url = ((Element*)elem)->getAttribute(DString("url"));
      const String *scheme = ((Element*)elem)->getAttribute(DString("scheme"));
      Node *eachLink = elem->getFirstChild();
      while(eachLink != null){
        if (*eachLink->getNodeName() == "link"){
          const String *l_url = ((Element*)eachLink)->getAttribute(DString("url"));
          const String *l_scheme = ((Element*)eachLink)->getAttribute(DString("scheme"));
          const String *token = ((Element*)eachLink)->getAttribute(DString("token"));
          StringBuffer fullURL;
          if (url != null) fullURL.append(url);
          if (l_url != null) fullURL.append(l_url);
          if (l_scheme == null) l_scheme = scheme;
          if (token == null) continue;
          StringBuffer hkey(token);
          if (l_scheme != null && l_scheme->length() > 0){
            hkey.append(DString("--")).append(l_scheme);
          }
          docLinkHash->put(&hkey, new SString(&fullURL));
        }
        eachLink = eachLink->getNextSibling();
      }
    }
    elem = elem->getNextSibling();
  }
  delete linkSource;
  docbuilder.free(linkSourceTree);
}
Example #5
0
void Scene::visitNode(Node* node, const char* visitMethod)
{
    ScriptController* sc = Game::getInstance()->getScriptController();

    // Invoke the visit method for this node.
    bool result;
    if (!sc->executeFunction<bool>(visitMethod, "<Node>", &result, (void*)node) || !result)
        return;

    // If this node has a model with a mesh skin, visit the joint hierarchy within it
    // since we don't add joint hierarcies directly to the scene. If joints are never
    // visited, it's possible that nodes embedded within the joint hierarchy that contain
    // models will never get visited (and therefore never get drawn).
    Model* model = dynamic_cast<Model*>(node->getDrawable());
    if (model && model->_skin && model->_skin->_rootNode)
    {
        visitNode(model->_skin->_rootNode, visitMethod);
    }

    // Recurse for all children.
    for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
    {
        visitNode(child, visitMethod);
    }
}
/**
 * Parses the XML Stylesheet PIs associated with the
 * given XML document. If a stylesheet PIs is found with type="text/xsl",
 * type="text/xml" or type="application/xml" the href pseudo attribute
 * value will be appended to the given href argument. If multiple XSLT
 * stylesheet PIs are found, the first one is used.
 */
void txStandaloneXSLTProcessor::getHrefFromStylesheetPI(Document& xmlDocument,
                                                        nsAString& href)
{
    Node* node = xmlDocument.getFirstChild();
    nsAutoString type;
    nsAutoString tmpHref;
    while (node) {
        if (node->getNodeType() == Node::PROCESSING_INSTRUCTION_NODE) {
            nsAutoString target;
            node->getNodeName(target);
            if (target.EqualsLiteral("xml-stylesheet")) {
                nsAutoString data;
                node->getNodeValue(data);
                type.Truncate();
                tmpHref.Truncate();
                parseStylesheetPI(data, type, tmpHref);
                if (type.EqualsLiteral("text/xsl") ||
                    type.EqualsLiteral("text/xml") ||
                    type.EqualsLiteral("application/xml")) {
                    href = tmpHref;
                    return;
                }
            }
        }
        node = node->getNextSibling();
    }
}
 /**
  * Gets the spelling alternatives to the specified query terms.
  * Returns a map with term as key and an Alternative object as value for each query term
  */
 std::map<std::string, Alternative> getAlternatives() {
     if (!_alternatives.empty())
         return _alternatives;
     _alternatives.clear();
     NodeSet alternatives = doc->FindFast("cps:reply/cps:content/alternatives_list/alternatives", true);
     for (unsigned int i = 0; i < alternatives.size(); i++) {
         Node *el = alternatives[i]->getFirstChild();
         Alternative alt;
         while (el != NULL) {
         	std::string name = el->getName();
             if (name == "to")
                 alt.to = el->getContent();
             else if (name == "count")
                 alt.count = atoi(el->getContentPtr());
             else if (name == "word") {
                 Alternative::Word w;
                 w.count = atoi(el->getAttribute("count")->getContentPtr());
                 w.h = atof(el->getAttribute("h")->getContentPtr());
                 w.idif = atof(el->getAttribute("idif")->getContentPtr());
                 w.cr = atof(el->getAttribute("cr")->getContentPtr());
                 w.content = el->getContent();
                 alt.words.push_back(w);
             }
             el = el->getNextSibling();
         }
         _alternatives[alt.to] = alt;
     }
     return _alternatives;
 }
Example #8
0
static void drawDebugNode(MeshBatch* batch, Node* node, unsigned int debugFlags)
{
    GP_ASSERT(node);
    Model* model = node->getModel();

    if ((debugFlags & Scene::DEBUG_BOXES) && model)
    {
        GP_ASSERT(model->getMesh());

        MeshSkin* skin = model->getSkin();
        if (skin && skin->getRootJoint() && skin->getRootJoint()->getParent())
        {
            // For skinned meshes that have a parent node to the skin's root joint,
            // we need to transform the bounding volume by that parent node's transform
            // as well to get the full skinned bounding volume.
            drawDebugBox(batch, model->getMesh()->getBoundingBox(), node->getWorldMatrix() * skin->getRootJoint()->getParent()->getWorldMatrix());
        }
        else
        {
            drawDebugBox(batch, model->getMesh()->getBoundingBox(), node->getWorldMatrix());
        }
    }

    if ((debugFlags & Scene::DEBUG_SPHERES) && model)
    {
        drawDebugSphere(batch, node->getBoundingSphere());
    }

    for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
    {
        drawDebugNode(batch, child, debugFlags);
    }
}
Example #9
0
void GPBFile::moveAnimationChannels(Node* node, Animation* dstAnimation)
{
    // Loop through the animations and channels backwards because they will be removed when found.
    int animationCount = _animations.getAnimationCount();
    for (int i = animationCount - 1; i >= 0; --i)
    {
        Animation* animation = _animations.getAnimation(i);
        int channelCount = animation->getAnimationChannelCount();
        for (int j = channelCount - 1; j >= 0; --j)
        {
            AnimationChannel* channel = animation->getAnimationChannel(j);
            if (equals(channel->getTargetId(), node->getId()))
            {
                animation->remove(channel);
                dstAnimation->add(channel);
            }
        }
        if (animation->getAnimationChannelCount() == 0)
        {
            _animations.removeAnimation(i);
        }
    }
    for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
    {
        moveAnimationChannels(child, dstAnimation);
    }
}
Example #10
0
void StyledHRDMapper::loadRegionMappings(InputSource *is)
{
  DocumentBuilder docbuilder;
  Document *hrdbase = docbuilder.parse(is);
  Element *hbase = hrdbase->getDocumentElement();
  if (*hbase->getNodeName() != "hrd"){
    docbuilder.free(hrdbase);
    throw Exception(DString("Error loading HRD file"));
  };

  for(Node *curel = hbase->getFirstChild(); curel; curel = curel->getNextSibling()){
    if (curel->getNodeType() == Node::ELEMENT_NODE && *curel->getNodeName() == "assign"){
      const String *name = ((Element*)curel)->getAttribute(DString("name"));
      if (name == null) continue;

      if (regionDefines.get(name) != null){
        delete regionDefines.get(name);
      }
      int val = 0;
      bool bfore = UnicodeTools::getNumber(((Element*)curel)->getAttribute(DString("fore")), &val);
      int fore = val;
      bool bback = UnicodeTools::getNumber(((Element*)curel)->getAttribute(DString("back")), &val);
      int back = val;
      int style = 0;
      if (UnicodeTools::getNumber(((Element*)curel)->getAttribute(DString("style")), &val)){
        style = val;
      }
      RegionDefine *rdef = new StyledRegion(bfore, bback, fore, back, style);
      regionDefines.put(name, rdef);
    };
  };
  docbuilder.free(hrdbase);
};
   /*
    * Runs the test case.
    */
   void runTest()
   {
      Document doc;
      NodeList elementList;
      Element testEmployee;
      Node firstC;
      String childName;
      int nodeType;
      CharacterData employeeIDNode;
      String employeeID;
      doc = (Document) baseT::load("hc_staff", false);
      elementList = doc.getElementsByTagName(SA::construct_from_utf8("p"));
      testEmployee = (Element) elementList.item(3);
      firstC = testEmployee.getFirstChild();
      nodeType = (int) firstC.getNodeType();
      
    while (baseT::equals(3, nodeType)) {
    firstC = firstC.getNextSibling();
      nodeType = (int) firstC.getNodeType();
      
    }
childName = firstC.getNodeName();
      baseT::assertEquals("em", childName, __LINE__, __FILE__);
  employeeIDNode = (CharacterData) firstC.getFirstChild();
      employeeID = employeeIDNode.getNodeValue();
      baseT::assertEquals("EMP0004", employeeID, __LINE__, __FILE__);
  
   }
Example #12
0
void HTMLStyleElementImp::handleMutation(EventListenerImp* listener, events::Event event)
{
    // TODO: update type, media, and scoped. Then check type.

    events::MutationEvent mutation(interface_cast<events::MutationEvent>(event));

    DocumentImp* document = getOwnerDocumentImp();
    if (!document)
        return;

    if (mutation.getType() == u"DOMNodeRemoved" && event.getTarget().self() == this)
        styleSheet = 0;
    else {
        std::u16string content;
        for (Node node = getFirstChild(); node; node = node.getNextSibling()) {
            if (TextImp* text = dynamic_cast<TextImp*>(node.self()))  // TODO better to avoid imp call?
                content += text->getData();
        }
        CSSParser parser;
        styleSheet = parser.parse(document, content);
        if (auto imp = dynamic_cast<CSSStyleSheetImp*>(styleSheet.self())) {
            imp->setOwnerNode(this);
            if (4 <= getLogLevel())
                dumpStyleSheet(std::cerr, imp);
        }
    }
    if (WindowImp* view = document->getDefaultWindow())
        view->setFlags(Box::NEED_SELECTOR_REMATCHING);
    document->resetStyleSheets();
}
void eval(Node node)
{
    while (node) {
        if (node.hasChildNodes())
            eval(node.getFirstChild());
        dynamic_cast<NodeImp*>(node.self())->eval();;
        node = node.getNextSibling();
    }
}
Example #14
0
void PhysicsVehicleWheel::findAncestorAndBind()
{
    GP_ASSERT(getNode());

    // Search for the first PhysicsVehicle that shares a common ancestor, and
    // bind with it. The following code performs a naive search; nothing more
    // sophisticated is deemed necessary because:
    // (a) The root of the scene is NOT a node
    // (b) Scene graphs tend to be relatively flat.
    //
    // The search ends when a vehicle is found or n is null:
    // 1: Let n = this node
    // 2: Visit each sibling of n and perform a breadth-first search of its descendants
    // 3: Let n = the parent of n
    // 4: Go to 2.
    PhysicsVehicle* host = NULL;
    Node* m;
    for (Node* n = getNode(); n && !host; n = n->getParent())
    {
        // Visit siblings before n
        for (m = n->getPreviousSibling(); m && !host; m = m->getPreviousSibling())
        {
            host = findVehicle(m);
        }

        // Visit siblings after n
        for (m = n->getNextSibling(); m && !host; m = m->getNextSibling())
        {
            host = findVehicle(m);
        }
    }

    // Note: Currently this method is silent on failure to find a host.
    if (host)
    {
        host->addWheel(this);
        _initialOffset = _node->getTranslation() - host->_node->getTranslation();
    }
}
Example #15
0
String *
Attr::getValue() const
{
  if (text == null)
    return null;
  if (text->getNextSibling() == text)
    return text->getData();

  unicode::StringBuffer buf;
  for (Node * n = text; n != null; n = n->getNextSibling()) {
    buf.append(n->getNodeValue());
  }
  return buf.createString();
}
void printComputedValues(Node node, ViewCSSImp* view, std::string indent)
{
    while (node) {
        if (node.getNodeType() == Node::ELEMENT_NODE) {
            Element element = interface_cast<Element>(node);
            std::cout << indent << '<' << element.getLocalName() << '>';
            if (css::CSSStyleDeclaration decl = view->getComputedStyle(element, Nullable<std::u16string>()))
                std::cout << ' ' << decl.getCssText();
            std::cout << '\n';
        }
        if (node.hasChildNodes())
            printComputedValues(node.getFirstChild(), view, indent + "  ");
        node = node.getNextSibling();
    }
}
Example #17
0
PhysicsVehicle* PhysicsVehicleWheel::findVehicle(Node* node)
{
    PhysicsCollisionObject* collisionObject = node->getCollisionObject();
    if (collisionObject && collisionObject->getType() == PhysicsCollisionObject::VEHICLE)
    {
        return static_cast<PhysicsVehicle*>(collisionObject);
    }

    PhysicsVehicle* result = NULL;
    for (Node* p = node->getFirstChild(); p && !result; p = p->getNextSibling())
    {
        result = findVehicle(p);
    }
    return result;
}
  /*
   * Runs the test case.
   */
  void runTest()
  {
     Document doc;
     NodeList elementList;
     Node emNode;
     Node nsNode;
     String nsName;
     doc = (Document) baseT::load("hc_staff", false);
     elementList = doc.getElementsByTagName(SA::construct_from_utf8("em"));
     emNode = elementList.item(1);
     nsNode = emNode.getNextSibling();
     nsName = nsNode.getNodeName();
     baseT::assertEquals("#text", nsName, __LINE__, __FILE__);
 
  }
void HTMLElementImp::xblEnteredDocument(Node node)
{
    while (node) {
        if (auto element = dynamic_cast<HTMLElementImp*>(node.self())) {
            if (element->shadowTarget && !element->shadowImplementation) {
                DocumentImp* document = element->getOwnerDocumentImp();
                DocumentWindowPtr window = document->activate();
                ECMAScriptContext* context = window->getContext();
                element->shadowImplementation = context->xblCreateImplementation(element->shadowTarget, element->bindingImplementation, element, element->shadowTree);
                element->shadowImplementation.xblEnteredDocument();
            }
        }
        if (node.hasChildNodes())
            xblEnteredDocument(node.getFirstChild());
        node = node.getNextSibling();
    }
}
void dumpTree(std::ostream& result, Node node, std::string indent)
{
    while (node) {
        result << indent << node << '\n';
        Element element = interface_cast<Element>(node);
        if (element.getNodeType() == Node::ELEMENT_NODE) {
            ObjectArray<Attr> attrArray = element.getAttributes();
            assert(attrArray);
            for (unsigned int i = 0; i < attrArray.getLength(); ++i) {
                Attr attr = attrArray.getElement(i);
                assert(attr);
                result << indent << "  " << attr.getName() << "=\"" << attr.getValue() << "\"\n";
            }
        }
        if (node.hasChildNodes())
            dumpTree(result, node.getFirstChild(), indent + ((node.getNodeType() == Node::DOCUMENT_NODE) ? "| " : "  "));
        node = node.getNextSibling();
    }
}
Example #21
0
void GPBFile::computeBounds(Node* node)
{
    assert(node);
    if (Model* model = node->getModel())
    {
        if (Mesh* mesh = model->getMesh())
        {
            mesh->computeBounds();
        }
        if (MeshSkin* skin = model->getSkin())
        {
            skin->computeBounds();
        }
    }
    for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
    {
        computeBounds(child);
    }
}
Example #22
0
/** Loads region definitions from HRD file.
    Multiple files could be loaded.
*/
void TextHRDMapper::loadRegionMappings(InputSource *is)
{
  DocumentBuilder docbuilder;

  Document *hrdbase = docbuilder.parse(is);
  Element *hbase = hrdbase->getDocumentElement();
  if (*hbase->getNodeName() != "hrd"){
    docbuilder.free(hrdbase);
    throw Exception(DString("Error loading HRD file"));
  };

  for(Node *curel = hbase->getFirstChild(); curel; curel = curel->getNextSibling()){
    if (curel->getNodeType() == Node::ELEMENT_NODE && *curel->getNodeName() == "assign"){
      const String *name = ((Element*)curel)->getAttribute(DString("name"));
      if (name == null) continue;

      if (regionDefines.get(name) != null){
        const TextRegion *rd = TextRegion::cast(regionDefines.get(name));
        delete rd->stext; delete rd->etext;
        delete rd->sback; delete rd->eback;
        delete rd;
      };
      const String *stext = null;
      const String *etext = null;
      const String *sback = null;
      const String *eback = null;
      const String *sval;
      sval = ((Element*)curel)->getAttribute(DString("stext"));
      if (sval != null) stext = new SString(sval);
      sval = ((Element*)curel)->getAttribute(DString("etext"));
      if (sval != null) etext = new SString(sval);
      sval = ((Element*)curel)->getAttribute(DString("sback"));
      if (sval != null) sback = new SString(sval);
      sval = ((Element*)curel)->getAttribute(DString("eback"));
      if (sval != null) eback = new SString(sval);

      RegionDefine *rdef = new TextRegion(stext, etext, sback, eback);
      regionDefines.put(name, rdef);
    };
  };
  docbuilder.free(hrdbase);
};
Example #23
0
void FarHrcSettings::readXML(String *file, bool userValue)
{
  DocumentBuilder docbuilder;
  InputSource *dfis = InputSource::newInstance(file);
  Document *xmlDocument = docbuilder.parse(dfis);
  Element *types = xmlDocument->getDocumentElement();

  if (*types->getNodeName() != "hrc-settings"){
    docbuilder.free(xmlDocument);
    throw FarHrcSettingsException(DString("main '<hrc-settings>' block not found"));
  }
  for (Node *elem = types->getFirstChild(); elem; elem = elem->getNextSibling()){
    if (*elem->getNodeName() == "prototype"){
      UpdatePrototype((Element*)elem, userValue);
      continue;
    }
  };
  docbuilder.free(xmlDocument);
  delete dfis;
}
Example #24
0
void Scene::calcAmbientColor(const Node* node, float* values) const
{
    if (!node)
    {
        return;
    }
    if (node->hasLight())
    {
        Light* light = node->getLight();
        if (light->isAmbient())
        {
            values[0] += light->getRed();
            values[1] += light->getGreen();
            values[2] += light->getBlue();
        }
    }
    for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
    {
        calcAmbientColor(child, values);
    }
}
Example #25
0
void FarHrcSettings::UpdatePrototype(Element *elem, bool userValue)
{
  const String *typeName = elem->getAttribute(DString("name"));
  if (typeName == null){
    return;
  }
  HRCParser *hrcParser = parserFactory->getHRCParser();
  FileTypeImpl *type = (FileTypeImpl *)hrcParser->getFileType(typeName);
  if (type== null){
    return;
  };
  for(Node *content = elem->getFirstChild(); content != null; content = content->getNextSibling()){
    if (*content->getNodeName() == "param"){
      const String *name = ((Element*)content)->getAttribute(DString("name"));
      const String *value = ((Element*)content)->getAttribute(DString("value"));
      const String *descr = ((Element*)content)->getAttribute(DString("description"));
      if (name == null || value == null){
        continue;
      };

      if (type->getParamValue(SString(name))==null){
        type->addParam(name);
      }
      if (descr != null){
        type->setParamDescription(SString(name), descr);
      }
      if (userValue){
        delete type->getParamNotDefaultValue(DString(name));
        type->setParamValue(SString(name), value);
      }
      else{
        delete type->getParamDefaultValue(DString(name));
        type->setParamDefaultValue(SString(name), value);
      }
    };
  };
}
Example #26
0
void DocumentBuilder::free(Document *doc)
{
  bool skip_childred = false;

  Node *rmnext = doc->getFirstChild();
  while(rmnext != doc && rmnext != null)
  {
    if (!skip_childred){
      while(rmnext->getFirstChild() != null){
        rmnext = rmnext->getFirstChild();
      }
    };
    skip_childred = false;

    Node *el = rmnext->getNextSibling();
    if(el == null){
      el = rmnext->getParent();
      skip_childred = true;
    }
    delete rmnext;
    rmnext = el;
  }
  delete doc;
}
Example #27
0
void XPathDataModel::assign(const Element<std::string>& assignElem,
                            const Node<std::string>& node,
                            const std::string& content) {
    std::string location;
    if (HAS_ATTR(assignElem, "id")) {
        location = ATTR(assignElem, "id");
    } else if (HAS_ATTR(assignElem, "location")) {
        location = ATTR(assignElem, "location");
    }

    // test 326ff
    XPathValue<std::string> key = _xpath.evaluate_expr(location, _doc);
#ifdef VERBOSE
    LOG(INFO) << "Key XPath : " << key.asString();
#endif
#if 0
    if (key.type() == NODE_SET) {
        try {
            for (size_t i = 0; i < key.asNodeSet().size(); i++) {
                Node<std::string> node = key.asNodeSet()[i];
                if (node == _varResolver.resolveVariable("", "_ioprocessors").asNodeSet()[0])
                    ERROR_EXECUTION_THROW("Cannot assign _ioProcessors");
                if (node == _varResolver.resolveVariable("", "_sessionid").asNodeSet()[0])
                    ERROR_EXECUTION_THROW("Cannot assign _sessionid");
                if (node == _varResolver.resolveVariable("", "_name").asNodeSet()[0])
                    ERROR_EXECUTION_THROW("Cannot assign _name");
                if (node == _varResolver.resolveVariable("", "_event").asNodeSet()[0])
                    ERROR_EXECUTION_THROW("Cannot assign _event");
            }
        } catch (Event e) {}
    }
#endif
    NodeSet<std::string> nodeSet;
    if (node) {
        Node<std::string> data = node;
        while (data) {
            // do not add empty text as a node
            if (data.getNodeType() == Node_base::TEXT_NODE) {
                std::string trimmed = data.getNodeValue();
                boost::trim(trimmed);
                if (trimmed.length() == 0) {
                    data = data.getNextSibling();
                    continue;
                }
            }
            nodeSet.push_back(data);
            data = data.getNextSibling();
        }
        assign(key, nodeSet, assignElem);
    } else if (content.length() > 0) {
        Text<std::string> textNode = _doc.createTextNode(spaceNormalize(content));
        nodeSet.push_back(textNode);
        assign(key, nodeSet, assignElem);
    } else if (HAS_ATTR(assignElem, "expr")) {
        XPathValue<std::string> value = _xpath.evaluate_expr(ATTR(assignElem, "expr"), _doc);
#ifdef VERBOSE
        LOG(INFO) << "Value XPath : " << value.asString();
#endif
        assign(key, value, assignElem);
    } else {
        LOG(ERROR) << "assign element has no content";
    }

//	std::cout << _datamodel << std::endl;
}
Example #28
0
void XPathDataModel::setEvent(const Event& event) {
    Element<std::string> eventElem = _doc.createElement("data");
    eventElem.setAttribute("id", "_event");

    Element<std::string> eventDataElem = _doc.createElement("data");
    NodeSet<std::string> eventNodeSet;

    {
        // -- name
        Element<std::string> eventNameElem = _doc.createElement("name");
        Text<std::string> eventName = _doc.createTextNode(event.name.c_str());
        eventNameElem.appendChild(eventName);
        eventElem.appendChild(eventNameElem);
    }
    {
        // -- origin
        Element<std::string> eventOriginElem = _doc.createElement("origin");
        Text<std::string> eventOrigin = _doc.createTextNode(event.origin.c_str());
        eventOriginElem.appendChild(eventOrigin);
        eventElem.appendChild(eventOriginElem);
    }
    {
        // -- type
        Element<std::string> eventTypeElem = _doc.createElement("type");
        Text<std::string> eventType;
        switch (event.eventType) {
        case Event::INTERNAL:
            eventType = _doc.createTextNode("internal");
            break;
        case Event::EXTERNAL:
            eventType = _doc.createTextNode("external");
            break;
        case Event::PLATFORM:
            eventType = _doc.createTextNode("platform");
            break;
        }
        eventTypeElem.appendChild(eventType);
        eventElem.appendChild(eventTypeElem);
    }

    if (event.params.size() > 0) {
        std::multimap<std::string, Data>::const_iterator paramIter = event.params.begin();
        while(paramIter != event.params.end()) {
            Element<std::string> eventParamElem = _doc.createElement("data");
            // this is simplified - Data might be more elaborate than a simple string atom
            Text<std::string> eventParamText = _doc.createTextNode(paramIter->second.atom);

            eventParamElem.setAttribute("id", paramIter->first);
            eventParamElem.appendChild(eventParamText);
            eventDataElem.appendChild(eventParamElem);
            paramIter++;
        }
    }
    if (event.namelist.size() > 0) {
        std::map<std::string, Data>::const_iterator namelistIter = event.namelist.begin();
        while(namelistIter != event.namelist.end()) {
            Element<std::string> eventNamelistElem = _doc.createElement("data");
            // this is simplified - Data might be more elaborate than a simple string atom
            Text<std::string> eventNamelistText = _doc.createTextNode(namelistIter->second.atom);

            eventNamelistElem.setAttribute("id", namelistIter->first);
            eventNamelistElem.appendChild(eventNamelistText);
            eventDataElem.appendChild(eventNamelistElem);
            namelistIter++;
        }
    }
    if (event.raw.size() > 0) {
        Element<std::string> eventRawElem = _doc.createElement("raw");
        Text<std::string> textNode = _doc.createTextNode(event.raw.c_str());
        eventRawElem.appendChild(textNode);
        eventElem.appendChild(eventRawElem);
    }

    if (event.content.size() > 0) {
        Text<std::string> textNode = _doc.createTextNode(spaceNormalize(event.content).c_str());
        eventDataElem.appendChild(textNode);
    }
    if (event.dom) {
        Node<std::string> importedNode = _doc.importNode(event.dom, true);
        eventDataElem.appendChild(importedNode);
    }
    if (event.data.array.size() == 1) {
        Text<std::string> textNode = _doc.createTextNode(event.data.array.front().atom.c_str());
        eventDataElem.appendChild(textNode);
    } else if (event.data.array.size() > 1) {
        std::list<uscxml::Data>::const_iterator ptr;
        unsigned int i;

        for( i = 0 , ptr = event.data.array.begin() ;
                ((i < event.data.array.size()) && (ptr != event.data.array.end()));
                i++ , ptr++ ) {
            Element<std::string> eventMESElem = _doc.createElement("data");
            Text<std::string> textNode = _doc.createTextNode(ptr->atom.c_str());
            std::stringstream ss;
            ss << i;
            eventMESElem.setAttribute("id", ss.str());
            eventMESElem.appendChild(textNode);
            eventDataElem.appendChild(eventMESElem);
        }
    }

    eventElem.appendChild(eventDataElem);
    eventNodeSet.push_back(eventElem);

    // do we need to replace an existing event?
    Node<std::string> oldEventElem = _datamodel.getFirstChild();
    while(oldEventElem) {
        if (oldEventElem.getNodeType() == Node_base::ELEMENT_NODE) {
            if (HAS_ATTR_CAST(oldEventElem, "id") && iequals(ATTR_CAST(oldEventElem, "id"), "_event"))
                break;
        }
        oldEventElem = oldEventElem.getNextSibling();
    }

    if (oldEventElem) {
        _datamodel.replaceChild(eventElem, oldEventElem);
    } else {
        _datamodel.appendChild(eventElem);
    }
    _varResolver.setVariable("_event", eventNodeSet);
}