Ejemplo n.º 1
0
        //--------------------------------------------------------------
        //--------------------------------------------------------------
		void AppDataStore::Save()
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            
			if(m_needsSynchonised == true)
            {
                // Convert to XML
                XML::Document doc;
                XML::Node* rootNode = doc.allocate_node(rapidxml::node_type::node_element);
                doc.append_node(rootNode);
                ParamDictionarySerialiser::ToXml(m_dictionary, rootNode);
                
                // Encrypt
                std::string strDocToBeEncrypted = XMLUtils::ToString(&doc);
                AESEncrypt::Data encryptedData = AESEncrypt::EncryptString(strDocToBeEncrypted, k_privateKey);

                // Write to disk
                FileSystem* pFileSystem = Application::Get()->GetFileSystem();
                FileStreamSPtr pFileStream = pFileSystem->CreateFileStream(StorageLocation::k_saveData, k_filename, FileMode::k_writeBinary);
                if(pFileStream != nullptr)
                {
                    pFileStream->Write(reinterpret_cast<const s8*>(encryptedData.m_data.get()), encryptedData.m_size);
                    pFileStream.reset();
                }
                
                m_needsSynchonised = false;
            }
		}
Ejemplo n.º 2
0
void MapDB::loadInfo(const std::string &fileName,
                     const SkipError skipError)
{
    XML::Document *doc = new XML::Document(fileName,
        UseResman_true,
        skipError);
    const XmlNodePtrConst root = doc->rootNode();
    if (!root)
    {
        delete doc;
        return;
    }

    for_each_xml_child_node(node, root)
    {
        if (xmlNameEqual(node, "map"))
        {
            readMap(node);
        }
        else if (xmlNameEqual(node, "atlas"))
        {
            readAtlas(node);
        }
        else if (xmlNameEqual(node, "include"))
        {
            const std::string name = XML::getProperty(node, "name", "");
            if (!name.empty())
                loadInfo(name, skipError);
            continue;
        }
    }
    delete doc;
}
Ejemplo n.º 3
0
	//----------------------------------------------------------------------
	//
	//----------------------------------------------------------------------
	void LNFXManager::_analyzeXML( const char* xml, size_t size )
	{
		XML::Document xmlDoc;
		xmlDoc.Parse( xml, size );

		// まずは Technique → Pass と作成して、コンパイルする。この中で Variable も作る
		XML::Element* xmlElement = xmlDoc.FirstChildElement();
		while ( xmlElement != NULL )
		{
			// <Technique>
			if ( strcmp( xmlElement->Name(), TechniqueElementName ) == 0 ) {
				_analyzeXMLTechniqueElement( xmlElement );
			}

			xmlElement = xmlElement->NextSiblingElement();
		}

		// 次に、作成済みの Variable にアノテーションを割り振る
		xmlElement = xmlDoc.FirstChildElement();
		while ( xmlElement != NULL )
		{
			// <Variable>
			if ( strcmp( xmlElement->Name(), VariableElementName ) == 0 ) {
				_analyzeXMLVariableElement( xmlElement );
			}

			xmlElement = xmlElement->NextSiblingElement();
		}
	}
Ejemplo n.º 4
0
        void TextureAtlasHandler::LoadAtlasFromFile(const String& Name, const String& Group)
        {
            /// @todo Update after we have refactored the resource system if needed.
            Resource::DataStreamPtr AtlasStream = Resource::ResourceManager::GetSingletonPtr()->OpenAssetStream(Name,Group);
            AtlasStream->SetStreamPosition(0);
            XML::Document AtlasDoc;
            AtlasDoc.Load( *AtlasStream.Get() );

            XML::Node RootNode = AtlasDoc.GetChild("Atlases");
            if( !RootNode.Empty() )
            {
                for( XML::NodeIterator AtlasIt = RootNode.begin() ; AtlasIt != RootNode.end() ; ++AtlasIt )
                {
                    // Parse the Atlas
                    TextureAtlas* NewAtlas = new TextureAtlas( (*AtlasIt) );
                    // Verify we don't already have one of the same name
                    AtlasIterator AtIt = this->Atlases.find( NewAtlas->GetName() );
                    if( AtIt != Atlases.end() )
                    {
                        MEZZ_EXCEPTION(ExceptionBase::II_DUPLICATE_IDENTITY_EXCEPTION,"Texture Atlas with the name \"" + NewAtlas->GetName() + "\" already exists.");
                    }
                    // Add the unique Atlas
                    this->Atlases[NewAtlas->GetName()] = NewAtlas;
                }
            }else{
                MEZZ_EXCEPTION(ExceptionBase::INVALID_STATE_EXCEPTION,"Mezzanine Texture Atlas file \"" + Name + "\"does not contain expected \"Atlases\" root node.  File is not valid and cannot be parsed.");
            }
        }
Ejemplo n.º 5
0
void CardSet::Validate(XML::Document& D)
{
    string name=(*D.Base())["name"];
    string abbrev=(*D.Base())["abbrev"];
    string dir=(*D.Base())["dir"];

    age[abbrev]=sets.size();
    if((*D.Base())["age"]!="")
    {
	age[abbrev]=atoi((*D.Base())["age"].c_str());
	for(list<string>::iterator i=sets.begin(); i!=sets.end(); i++)
	    if(age[*i]>=age[abbrev])
		age[*i]++;
    }
	
    sets.push_back(abbrev);
	
    set_name[abbrev]=name;
    directory[abbrev]=dir;
    list<XML::Element*>::iterator i;
    list<XML::Element*> cards=D("cards","card");
    first_card[abbrev]=nextcard;

    for(i=cards.begin(); i!=cards.end(); i++)
    {
	(**i).AddAttribute("set",abbrev);
	numbers[(**i)["name"]].push_back(nextcard);
	nextcard++;
    }
    last_card[abbrev]=nextcard-1;
}
Ejemplo n.º 6
0
void SoundDB::loadXmlFile(const std::string &fileName)
{
    XML::Document *doc = new XML::Document(fileName);
    const XmlNodePtrConst root = doc->rootNode();

    if (!root || !xmlNameEqual(root, "sounds"))
    {
        delete doc;
        return;
    }

    for_each_xml_child_node(node, root)
    {
        if (xmlNameEqual(node, "include"))
        {
            const std::string name = XML::getProperty(node, "name", "");
            if (!name.empty())
                loadXmlFile(name);
            continue;
        }
        else if (xmlNameEqual(node, "sound"))
        {
            const std::string name = XML::getProperty(node, "name", "");
            const int id = NotifyManager::getIndexBySound(name);
            if (id)
            {
                const std::string value = XML::getProperty(node, "value", "");
                mSounds[id] = value;
            }
        }
    }

    delete doc;
}
Ejemplo n.º 7
0
//
// XML 保存
//
void Linkfilter_Manager::save_xml()
{
    XML::Document document;
    XML::Dom* root = document.appendChild( XML::NODE_TYPE_ELEMENT, std::string( ROOT_NODE_NAME_LINKFILTER ) );
    if( ! root ) return;

    std::vector< LinkFilterItem >::iterator it = m_list_cmd.begin();
    while( it != m_list_cmd.end() ){

        const std::string url = ( *it ).url;
        const std::string cmd = ( *it ).cmd;

        if( ! url.empty() && ! cmd.empty() ){

            XML::Dom* node = root->appendChild( XML::NODE_TYPE_ELEMENT, XML::get_name( TYPE_LINKFILTER ) );
            node->setAttribute( "url", url );
            node->setAttribute( "data", cmd );
        }
        ++it;
    }

#ifdef _DEBUG
    std::cout << "Linkfilter_Manager::save_xml\n";
    std::cout << document.get_xml() << std::endl;
#endif

    CACHE::save_rawdata( CACHE::path_linkfilter(), document.get_xml() );
}
Ejemplo n.º 8
0
void EffectDB::load()
{
    if (!mLoaded)
        return;

    const XML::Document doc("effects.xml");
    const xmlNodePtr root = doc.rootNode();

    if (!root || !xmlStrEqual(root->name, BAD_CAST "being-effects"))
    {
        logger->log("Error loading being effects file: effects.xml");
        return;
    }
    else
        logger->log("Effects are now loading");

    for_each_xml_child_node(node, root)
    {
        if (xmlStrEqual(node->name, BAD_CAST "effect"))
        {
            EffectDescription ed;
            ed.id = XML::getProperty(node, "id", -1);
            ed.GFX = XML::getProperty(node, "particle", "");
            ed.SFX = XML::getProperty(node, "audio", "");
            mEffects.push_back(ed);
        }
    }

    mLoaded = true;
}
Ejemplo n.º 9
0
void EmoteDB::load()
{
    if (mLoaded)
        return;

    mLastEmote = 0;

    logger->log("Initializing emote database...");

    const XML::Document doc("emotes.xml");
    const xmlNodePtr rootNode = doc.rootNode();

    if (!rootNode || !xmlStrEqual(rootNode->name, BAD_CAST "emotes"))
    {
        logger->log("Emote Database: Error while loading emotes.xml!");
        return;
    }

    //iterate <emote>s
    for_each_xml_child_node(emoteNode, rootNode)
    {
        if (!xmlStrEqual(emoteNode->name, BAD_CAST "emote"))
            continue;

        const int id = XML::getProperty(emoteNode, "id", -1);

        if (id == -1)
        {
            logger->log("Emote Database: Emote with missing ID in emotes.xml!");
            continue;
        }

        EmoteInfo *currentInfo = new EmoteInfo();

        for_each_xml_child_node(spriteNode, emoteNode)
        {
            if (xmlStrEqual(spriteNode->name, BAD_CAST "sprite"))
            {
                EmoteSprite *currentSprite = new EmoteSprite();
                std::string file = "graphics/sprites/" + (std::string)
                            (const char*) spriteNode->xmlChildrenNode->content;
                currentSprite->sprite = AnimatedSprite::load(file,
                                XML::getProperty(spriteNode, "variant", 0));
                currentInfo->sprites.push_back(currentSprite);
            }
            else if (xmlStrEqual(spriteNode->name, BAD_CAST "particlefx"))
            {
                std::string particlefx = (const char*) spriteNode->xmlChildrenNode->content;
                currentInfo->particles.push_back(particlefx);
            }
        }
        mEmoteInfos[id] = currentInfo;

        if (id > mLastEmote)
            mLastEmote = id;
    }

    mLoaded = true;
}
Ejemplo n.º 10
0
void CharDB::load()
{
    if (mLoaded)
        unload();

    XML::Document *doc = new XML::Document(
        paths.getStringValue("charCreationFile"),
        true,
        false);
    const XmlNodePtrConst root = doc->rootNode();

    if (!root || !xmlNameEqual(root, "chars"))
    {
        logger->log("CharDB: Failed to parse %s.",
            paths.getStringValue("charCreationFile").c_str());
        delete doc;
        return;
    }

    for_each_xml_child_node(node, root)
    {
        if (xmlNameEqual(node, "haircolor"))
        {
            loadMinMax(node, &mMinHairColor, &mMaxHairColor);
        }
        else if (xmlNameEqual(node, "hairstyle"))
        {
            loadMinMax(node, &mMinHairStyle, &mMaxHairStyle);
        }
        else if (xmlNameEqual(node, "look"))
        {
            loadMinMax(node, &mMinLook, &mMaxLook);
        }
        else if (xmlNameEqual(node, "stat"))
        {
            loadMinMax(node, &mMinStat, &mMaxStat);
            mSumStat = XML::getProperty(node, "sum", 0);
        }
        else if (xmlNameEqual(node, "item"))
        {
            const int id = XML::getProperty(node, "id", 0);
            if (id > 0)
                mDefaultItems.push_back(id);
        }
        else if (xmlNameEqual(node, "race"))
        {
            loadMinMax(node, &mMinRace, &mMaxRace);
        }
    }

    delete doc;

    mLoaded = true;
}
Ejemplo n.º 11
0
void CardSet::AddCards(const string& filename)
{
    int old_nextcard=nextcard;
	
    if(db.Base()==0)
    {
	db.ReadFile(Localization::File(filename));
	Validate(db);
	db.Base()->DelAttribute("name");
    }
    else
    {
	XML::Document add;

	add.ReadFile(Localization::File(filename));
	Validate(add);
	db("cards").front()->AddSubelements(add("cards","card"));
    }

    list<XML::Element*>::const_iterator i;
    card=vector<XML::Element*>(nextcard);
    list<XML::Element*>& C=db("cards").front()->Subs();
    i=C.begin();
    for(int j=0; j<nextcard; j++)
	card[j]=*i++;

    for(int j=old_nextcard; j<nextcard; j++)
    {
	string rarity=AttrValue(j,"rarity");
	while(rarity!="")
	{
	    size_t k;
	    for(k=0; k<rarity.length(); k++)
	      if((rarity[k]>='0' && rarity[k]<='9') || (rarity[k]=='+' && (k+1<rarity.length())))
		    break;

	    rarities.insert(rarity.substr(0,k));
	    while(k<rarity.length() && rarity[k]!='+')
		k++;

	    if(k+1<rarity.length())
		rarity=rarity.substr(k+1,rarity.length());
	    else
		rarity="";
	}

	list<string> att=Attributes(j);
	for(list<string>::iterator n=att.begin(); n!=att.end(); n++)
	    attributes.insert(*n);
    }
}
Ejemplo n.º 12
0
void ColorDB::load()
{
    if (mLoaded)
        return;

    XML::Document *doc = new XML::Document(HAIR_COLOR_FILE);
    xmlNodePtr root = doc->rootNode();
    bool TMWHair = false;

    if (!root || !xmlStrEqual(root->name, BAD_CAST "colors"))
    {
        logger->log("Trying TMW's color file, %s.", TMW_COLOR_FILE);

        TMWHair = true;

        delete doc;

        doc = new XML::Document(TMW_COLOR_FILE);
        root = doc->rootNode();
        if (!root || !xmlStrEqual(root->name, BAD_CAST "colors"))
        {
            logger->log("ColorDB: Failed");
            mColors[0] = mFail;
            mLoaded = true;

            delete doc;

            return;
        }
    }
    for_each_xml_child_node(node, root)
    {
        if (xmlStrEqual(node->name, BAD_CAST "color"))
        {
            int id = XML::getProperty(node, "id", 0);

            if (mColors.find(id) != mColors.end())
                logger->log("ColorDB: Redefinition of dye ID %d", id);

            mColors[id] = TMWHair ? XML::getProperty(node, "value", mFail) :
                                    XML::getProperty(node, "dye", mFail);
        }
    }

    delete doc;

    mLoaded = true;
}
Ejemplo n.º 13
0
ActionResponse Service::onAction(const std::string& action, const xml::Document& doc)
{
    try
    {
        ActionResponse response(action, ServiceType::ConnectionManager);
        auto request = doc.getFirstChild();
    
        switch (actionFromString(action))
        {
        case Action::GetProtocolInfo:
            response.addArgument("Source",               getVariable(Variable::SourceProtocolInfo).getValue());
            response.addArgument("Sink",                 getVariable(Variable::SinkProtocolInfo).getValue());
            break;
        case Action::PrepareForConnection:
        {
            ConnectionInfo connInfo;
            connInfo.peerConnectionManager  = request.getChildNodeValue("PeerConnectionManager");
            connInfo.peerConnectionId       = std::stoi(request.getChildNodeValue("PeerConnectionID"));
            connInfo.direction              = directionFromString(request.getChildNodeValue("Direction"));
            
            ProtocolInfo protoInfo(request.getChildNodeValue("RemoteProtocolInfo"));;
            m_connectionManager.prepareForConnection(protoInfo, connInfo);
        
            response.addArgument("ConnectionID",         std::to_string(connInfo.connectionId));
            response.addArgument("AVTransportID",        std::to_string(connInfo.avTransportId));
            response.addArgument("RcsID",                std::to_string(connInfo.renderingControlServiceId));
            break;
        }
        case Action::ConnectionComplete:
            m_connectionManager.connectionComplete(std::stoi(request.getChildNodeValue("ConnectionID")));
            break;
        case Action::GetCurrentConnectionIDs:
            response.addArgument("ConnectionIDs",        getVariable(Variable::CurrentConnectionIds).getValue());
            break;
        case Action::GetCurrentConnectionInfo:
        {
            auto connInfo = m_connectionManager.getCurrentConnectionInfo(std::stoi(request.getChildNodeValue("ConnectionID")));
            response.addArgument("RcsID",                   std::to_string(connInfo.renderingControlServiceId));
            response.addArgument("AVTransportID",           std::to_string(connInfo.avTransportId));
            response.addArgument("ProtocolInfo",            connInfo.protocolInfo.toString());
            response.addArgument("PeerConnectionManager",   connInfo.peerConnectionManager);
            response.addArgument("PeerConnectionID",        std::to_string(connInfo.peerConnectionId));
            response.addArgument("Direction",               toString(connInfo.direction));
            response.addArgument("Status",                  toString(connInfo.connectionStatus));
            break;
        }
        default:
            throw InvalidActionException();
        }
        
        return response;
    }
    catch (std::exception& e)
    {
        log::error("Error processing ConnectionManager request: %s", e.what());
        throw InvalidActionException();
    }
}
Ejemplo n.º 14
0
        void CollisionShapeManager::SaveShapesToXMLFile(const String& FileName, ShapeVector& ShapesToSave)
        {
            XML::Document ShapesDoc;
            XML::Node DeclNode = ShapesDoc.AppendChild(XML::NodeDeclaration);
            XML::Attribute VerAttrib = DeclNode.AppendAttribute("version");

            if( DeclNode.SetName("xml") && VerAttrib.SetValue("1.0") ) {
                XML::Node ShapesRoot = ShapesDoc.AppendChild( "ShapesRoot" );
                for( ShapeVectorIterator ShapeIt = ShapesToSave.begin() ; ShapeIt != ShapesToSave.end() ; ++ShapeIt )
                {
                    (*ShapeIt)->ProtoSerialize( ShapesRoot );
                }

                /// @todo Replace this stack allocated stream for one initialized from the Resource Manager, after the system is ready.
                Resource::FileStream SettingsStream(FileName,".",Resource::SF_Truncate | Resource::SF_Write);
                ShapesDoc.Save(SettingsStream,"\t",XML::FormatIndent);
            }else{
                MEZZ_EXCEPTION(ExceptionBase::INVALID_STATE_EXCEPTION,"Failed to create XML document declaration for file \"" + FileName + "\".");
            }
        }
Ejemplo n.º 15
0
        void CollisionShapeManager::LoadAllShapesFromXMLFile(const String& FileName, const String& Group)
        {
            /// @todo Replace this stack allocated stream for one initialized from the Resource Manager, after the system is ready.
            Resource::FileStream ShapesStream( FileName, Resource::ResourceManager::GetSingletonPtr()->GetAssetPath(FileName,Group) );
            XML::Document ShapesDoc;
            XML::ParseResult DocResult = ShapesDoc.Load(ShapesStream);
            if( DocResult.Status != XML::StatusOk ) {
                MEZZ_EXCEPTION(ExceptionBase::SYNTAX_ERROR_EXCEPTION_XML,"Failed to parse XML file \"" + FileName + "\".");
            }
            XML::Node ShapesRoot = ShapesDoc.GetChild("InitializerRoot");
            if( ShapesRoot.Empty() ) {
                MEZZ_EXCEPTION(ExceptionBase::SYNTAX_ERROR_EXCEPTION_XML,"Failed to find expected Root node in \"" + FileName + "\".");
            }

            for( XML::NodeIterator ShapeIt = ShapesRoot.begin() ; ShapeIt != ShapesRoot.end() ; ++ShapeIt )
            {
                CollisionShape* DeSerializedShape = Physics::CreateShape( (*ShapeIt) );
                this->CollisionShapes.insert( std::pair<String,CollisionShape*>(DeSerializedShape->GetName(),DeSerializedShape) );
            }
        }
Ejemplo n.º 16
0
/***************************************************************
* Function: CodeParser::parseXMLFile()
* Purpose : Parse a an XML IR file
* Initial : Maxime Chevalier-Boisvert on November 18, 2008
****************************************************************
Revisions and bug fixes:
*/
CompUnits CodeParser::parseXMLFile(const std::string& filePath)
{
	// Log that we are parsing this file
	std::cout << "Parsing XML IR file: \"" << filePath << "\"" << std::endl;

	// Create an XML parser object
	XML::Parser parser;

	// Setup a try block to catch any errors
	try
	{
		// Parse the IR code string
		XML::Document xmlIR = parser.parseFile(filePath);

		// If the verbose output flag is set
		if (ConfigManager::s_verboseVar.getBoolValue() == true)
		{
			// Output the parsed XML
			std::cout << std::endl;
			std::cout << "Parsed XML: " << std::endl;
			std::cout << xmlIR.toString() << std::endl;
			std::cout << std::endl;
		}

		// Get a pointer to the XML tree root
		const XML::Element* pTreeRoot = xmlIR.getTree();

		// Parse the XML tree
		return parseXMLRoot(pTreeRoot);
	}

	// If XML parsing error occur
	catch (XML::ParseError error)
	{
		// Log the error
		std::cout << "ERROR: XML parsing failed " + error.toString() << std::endl;

		// Exit this function
		return CompUnits();
	}
}
Ejemplo n.º 17
0
void ColorDB::loadHair(const std::string &fileName,
                       std::map<ItemColor, ItemColorData> &colors)
{
    XML::Document *doc = new XML::Document(fileName,
                                           UseResman_true,
                                           SkipError_false);
    const XmlNodePtrConst root = doc->rootNode();

    if (!root || !xmlNameEqual(root, "colors"))
    {
        logger->log("ColorDB: Failed to find hair colors file.");
        if (colors.find(ItemColor_zero) == colors.end())
            colors[ItemColor_zero] = ItemColorData(ItemColor_zero, "", "");
        delete doc;
        return;
    }

    for_each_xml_child_node(node, root)
    {
        if (xmlNameEqual(node, "include"))
        {
            const std::string name = XML::getProperty(node, "name", "");
            if (!name.empty())
                loadHair(name, colors);
            continue;
        }
        else if (xmlNameEqual(node, "color"))
        {
            const ItemColor id = fromInt(XML::getProperty(
                                             node, "id", 0), ItemColor);

            if (colors.find(id) != colors.end())
            {
                logger->log("ColorDB: Redefinition of dye ID %d",
                            toInt(id, int));
            }

            colors[id] = ItemColorData(id, XML::langProperty(node, "name", ""),
                                       XML::getProperty(node, "value", "#FFFFFF"));
        }
    }
Ejemplo n.º 18
0
void EffectDB::load()
{
    if (!mLoaded)
        return;
    
    const XML::Document doc("effects.xml");
    const xmlNodePtr root = doc.rootNode();

    if (!root || !xmlStrEqual(root->name, BAD_CAST "being-effects"))
    {
        logger->log("Error loading being effects file: effects.xml");
        return;
    }
    else
        logger->log("Effects are now loading");

    for_each_xml_child_node(node, root)
    {
        if (xmlStrEqual(node->name, BAD_CAST "effect"))
        {
            EffectDescription ed;
            ed.id = XML::getProperty(node, "id", -1);
            ed.GFX = XML::getProperty(node, "particle", "");
            ed.SFX = XML::getProperty(node, "audio", "");
            ed.ambient.type = ""; // since we test this, ensure it's initialized
                                  // with something
            if (xmlStrEqual(node->name, BAD_CAST "ambient"))
            {
                ed.ambient.type = XML::getProperty(node, "type", "");
                ed.ambient.x = XML::getProperty(node, "x", 0.0f);
                ed.ambient.y = XML::getProperty(node, "y", 0.0f);
                ed.ambient.speedX = XML::getProperty(node, "speedx", 0.95f);
                ed.ambient.speedY = XML::getProperty(node, "speedy", 0.95f);
                ed.ambient.duration = XML::getProperty(node, "duration", 100);
            }
            mEffects.push_back(ed);
        }
    }

    mLoaded = true;
}
Ejemplo n.º 19
0
Bool BonkEnc::CDDBBatch::SaveEntries()
{
	// Save queued queries

	if (queries.Length() == 0)
	{
		// Delete queries file if no more saved queries exist
		File(String(config->configDir).Append("cddb\\queries.xml")).Delete();
	}
	else
	{
		Directory(String(config->configDir).Append("cddb")).Create();

		XML::Document	*document = new XML::Document();
		XML::Node	*root = new XML::Node("cddbQueries");

		document->SetRootNode(root);

		for (Int i = 0; i < queries.Length(); i++)
		{
			root->AddNode("query", queries.GetNth(i));
		}

		document->SaveFile(String(config->configDir).Append("cddb\\queries.xml"));

		delete document;
		delete root;
	}

	// Save queued submits

	if (submits.Length() == 0)
	{
		// Delete submits file if no more saved submits exist
		File(String(config->configDir).Append("cddb\\submits.xml")).Delete();
	}
	else
	{
		Directory(String(config->configDir).Append("cddb")).Create();

		XML::Document	*document = new XML::Document();
		XML::Node	*root = new XML::Node("cddbSubmits");

		document->SetRootNode(root);

		for (Int i = 0; i < submits.Length(); i++)
		{
			XML::Node	*node = root->AddNode("submit", submits.GetNth(i).DiscIDToString());

			node->SetAttribute("category", submits.GetNth(i).category);
		}

		document->SaveFile(String(config->configDir).Append("cddb\\submits.xml"));

		delete document;
		delete root;
	}

	return True;
}
Ejemplo n.º 20
0
void TextDb::loadXmlFile(const std::string &fileName,
                         const SkipError skipError)
{
    XML::Document *doc = new XML::Document(fileName,
        UseVirtFs_true,
        skipError);
    XmlNodeConstPtrConst root = doc->rootNode();

    if ((root == nullptr) || !xmlNameEqual(root, "texts"))
    {
        delete doc;
        return;
    }

    for_each_xml_child_node(node, root)
    {
        if (xmlNameEqual(node, "include"))
        {
            const std::string name = XML::getProperty(node, "name", "");
            if (!name.empty())
                loadXmlFile(name, skipError);
            continue;
        }
        else if (xmlNameEqual(node, "text"))
        {
            const bool show = XML::getBoolProperty(node, "show", false);
            if (show == true)
            {
                if (!XmlHaveChildContent(node))
                    continue;

                std::string text = XmlChildContent(node);
                mTexts.push_back(text);
            }
        }
    }

    delete doc;
}
            //-----------------------------------------------------------------
            //-----------------------------------------------------------------
            void ToXml(const ParamDictionary& in_dict, XML::Node* out_element)
            {
                XML::Document* doc = out_element->document();
                
                out_element->name(doc->allocate_string("Params"));
                
                for(auto it = in_dict.begin(); it != in_dict.end(); ++it)
                {
                    XML::Attribute* keyAttribute = out_element->document()->allocate_attribute();
                    keyAttribute->name(out_element->document()->allocate_string("key"));
                    keyAttribute->value(out_element->document()->allocate_string(it->first.c_str()));
                    
                    XML::Attribute* valueAttribute = out_element->document()->allocate_attribute();
                    valueAttribute->name(out_element->document()->allocate_string("value"));
                    valueAttribute->value(out_element->document()->allocate_string(it->second.c_str()));

                    XML::Node* node = out_element->document()->allocate_node(rapidxml::node_type::node_element);
                    node->name(doc->allocate_string("Param"));
                    node->append_attribute(keyAttribute);
                    node->append_attribute(valueAttribute);
                    out_element->append_node(node);
                }
            }
Ejemplo n.º 22
0
void testXmlFromScratch() {
    Xml::Document scratch;
    scratch.setRootTag("MyDoc");
    cout << scratch;

    Xml::Comment c("This is a comment.");
    Xml::Unknown u("!GODONLY knows what this is!!");
    Xml::Text t("This is some\ntext on two lines with trailing blanks   ");
    Xml::Element e("elementTag");

    // We're never going to use this one so its heap space will
    // leak if we don't explicitly call clearOrphan().
    Xml::Element neverMind("neverMind");

    cout << "initially e='" << e.getValue() << "'" << endl;
    e.updValue() += "AVALUE:";
    cout << "then e='" << e.getValue() << "'" << endl;

    e.setAttributeValue("attr1", String(Vec2(9,-9)));

    cout << "attr1 is " << e.getRequiredAttributeValueAs<Vec2>("attr1") << endl;

    cout << "isOrphan? " << String(c.isOrphan()) << ":" << c;
    cout << "isOrphan? " << String(u.isOrphan()) << ":" << u;
    cout << "isOrphan? " << String(t.isOrphan()) << ":" << t;
    cout << "isOrphan? " << String(e.isOrphan()) << ":" << e;

    e.setValue("this is the only value");
    e.updValue() += " (but then I added this)";
    cout << "e value=" << e.getValue() << endl;
    cout << "e = " << e << endl;
    e.setValue("9 10 -3.2e-4");
    cout << "e value=" << e.getValueAs< Array_<float> >() << endl;
    cout << "e = " << e << endl;

    scratch.insertTopLevelNodeAfter(scratch.node_begin(), c);
    cout << "isOrphan? " << String(c.isOrphan()) << ":" << c;
    cout << scratch;

    scratch.insertTopLevelNodeBefore(scratch.node_begin(Xml::ElementNode), u);
    cout << "isOrphan? " << String(u.isOrphan()) << ":" << u;
    cout << scratch;

    scratch.insertTopLevelNodeBefore(scratch.node_begin(), 
        Xml::Comment("This should be at the top of the file, except declaration."));
    cout << scratch;

    Xml::Document scratch2;
    scratch2 = scratch; // deep copy

    scratch.eraseTopLevelNode(scratch.node_begin());
    cout << "First node gone (scratch)?\n" << scratch;
    cout << "First node still there (scratch2)?\n" << scratch2;

    Xml::Element e2("anotherElt", Vec3(.1,.2,.3));
    cout << e2;
    e.insertNodeAfter(e.element_end(), e2);
    cout << "now owns anotherElt:\n" << e;

    Xml::Element root = scratch.getRootElement();
    root.insertNodeAfter(root.node_begin(), e);
    cout << scratch;

    scratch.setIndentString("..");
    cout << scratch;

    Xml::Element ecopy = e.clone();
    ecopy.setElementTag("elementTagCopy");
    cout << "COPY of e: " << ecopy;

    //scratch.writeToFile("scratch.xml");

    e.eraseNode(e.element_begin("anotherElt"));
    cout << "in-place removal of anotherElt from e: " << scratch;
    cout << "COPY of e: " << ecopy;

    root.insertNodeAfter(root.element_begin("elementTag"), ecopy);
    cout << "After copy insert, scratch=" << scratch;

    Xml::Node extract = root.removeNode(root.element_begin("elementTagCopy"));
    cout << "Extracted copy: " << extract << endl;
    cout << "Now scratch=" << scratch << endl;
    cout << "Duplicate scratch=" << Xml::Document(scratch) << endl;

    neverMind.clearOrphan();
}
Ejemplo n.º 23
0
void MonsterDB::load()
{
    if (mLoaded)
        return;

    mUnknown.addSprite("error.xml");
    mUnknown.setName(_("unnamed"));

    logger->log("Initializing monster database...");

    const XML::Document doc("monsters.xml");
    const xmlNodePtr rootNode = doc.rootNode();

    if (!rootNode || !xmlStrEqual(rootNode->name, BAD_CAST "monsters"))
        logger->error("Monster Database: Error while loading monster.xml!");

    //iterate <monster>s
    for_each_xml_child_node(monsterNode, rootNode)
    {
        if (!xmlStrEqual(monsterNode->name, BAD_CAST "monster"))
            continue;

        MonsterInfo *currentInfo = new MonsterInfo();

        currentInfo->setName(XML::getProperty(monsterNode, "name", _("unnamed")));

        std::string targetCursor;
        targetCursor = XML::getProperty(monsterNode, "targetCursor", "medium");
        if (targetCursor == "small")
            currentInfo->setTargetCursorSize(Being::TC_SMALL);
        else if (targetCursor == "medium")
            currentInfo->setTargetCursorSize(Being::TC_MEDIUM);
        else if (targetCursor == "large")
            currentInfo->setTargetCursorSize(Being::TC_LARGE);
        else
        {
            logger->log("MonsterDB: Unknown target cursor type \"%s\" for %s -"
                        "using medium sized one",
                        targetCursor.c_str(), currentInfo->getName().c_str());
            currentInfo->setTargetCursorSize(Being::TC_MEDIUM);
        }

        //iterate <sprite>s and <sound>s
        for_each_xml_child_node(spriteNode, monsterNode)
        {
            if (xmlStrEqual(spriteNode->name, BAD_CAST "sprite"))
                currentInfo->addSprite(
                        (const char*) spriteNode->xmlChildrenNode->content);

            if (xmlStrEqual(spriteNode->name, BAD_CAST "sound"))
            {
                std::string event = XML::getProperty(spriteNode, "event", "");
                const char *filename;
                filename = (const char*) spriteNode->xmlChildrenNode->content;

                if (event == "hit")
                    currentInfo->addSound(MONSTER_EVENT_HIT, filename);
                else if (event == "miss")
                    currentInfo->addSound(MONSTER_EVENT_MISS, filename);
                else if (event == "hurt")
                    currentInfo->addSound(MONSTER_EVENT_HURT, filename);
                else if (event == "die")
                    currentInfo->addSound(MONSTER_EVENT_DIE, filename);
                else
                {
                    logger->log("MonsterDB: Warning, sound effect %s for "
                                "unknown event %s of monster %s",
                                filename, event.c_str(),
                                currentInfo->getName().c_str());
                }
            }

            if (xmlStrEqual(spriteNode->name, BAD_CAST "attack"))
            {
                std::string event = XML::getProperty(
                        spriteNode, "particle-effect", "");
                currentInfo->addAttackParticleEffect(event);
            }

            if (xmlStrEqual(spriteNode->name, BAD_CAST "particlefx"))
                currentInfo->addParticleEffect(
                    (const char*) spriteNode->xmlChildrenNode->content);
        }
        mMonsterInfos[XML::getProperty(monsterNode, "id", 0)] = currentInfo;
    }

    mLoaded = true;
}
Ejemplo n.º 24
0
    void Entresol::ConstructFromXML(const String& EngineDataPath, const Mezzanine::ArchiveType ArchType, const String& InitializerFile)
    {
        //Add default manager factories
        AddAllEngineDefaultManagerFactories();
        //Set some sane Defaults for some values.
        this->ManualLoopBreak = false;

        // Create Ogre.
        SetupOgre();

        // Load the necessary plugins.
        SubSystemParticleFXPlugin = new Ogre::ParticleFXPlugin();
        Ogre::Root::getSingleton().installPlugin(SubSystemParticleFXPlugin);

        // Set up the data we'll be populating.
        XML::Attribute CurrAttrib;
        String GUIInit, ResourceInit, PluginsInit, LogFileName;
        String PluginExtension, PluginPath;

        // Create or set the resource manager.
        /// @todo This currently forces our default resource manager to be constructed, which isn't in line with our factory/initiailzation design.
        /// This should be addressed somehow.
        if(ResourceManager::SingletonValid())
            { AddManager(ResourceManager::GetSingletonPtr()); }
        else
            { AddManager(new ResourceManager(EngineDataPath, ArchType)); }

        // Open and load the initializer doc.
        ResourceManager* ResourceMan = GetResourceManager();
        /// @todo Replace this stack allocated stream for one initialized from the Resource Manager, after the system is ready.
        Resource::FileStream InitStream(InitializerFile,EngineDataPath);
        XML::Document InitDoc;
        XML::ParseResult DocResult = InitDoc.Load(InitStream);
        if( DocResult.Status != XML::StatusOk )
        {
            StringStream ExceptionStream;
            ExceptionStream << "Failed to parse XML file \"" << InitializerFile << "\".";
            MEZZ_EXCEPTION(Exception::SYNTAX_ERROR_EXCEPTION_XML,ExceptionStream.str());
        }
        XML::Node InitRoot = InitDoc.GetChild("InitializerRoot");
        if( InitRoot.Empty() )
        {
            StringStream ExceptionStream;
            ExceptionStream << "Failed to find expected Root node in \"" << InitializerFile << "\".";
            MEZZ_EXCEPTION(Exception::SYNTAX_ERROR_EXCEPTION_XML,ExceptionStream.str());
        }

        // Get the world settings and set them.
        XML::Node WorldSettings = InitRoot.GetChild("WorldSettings");
        for( XML::NodeIterator SetIt = WorldSettings.begin() ; SetIt != WorldSettings.end() ; ++SetIt )
        {
            String SecName = (*SetIt).Name();
            if( "FrameSettings" == SecName )
            {
                CurrAttrib = (*SetIt).GetAttribute("TargetFrameRate");
                if(CurrAttrib.Empty())
                {
                    CurrAttrib = (*SetIt).GetAttribute("TargetFrameTime");
                    if(!CurrAttrib.Empty())
                        SetTargetFrameTimeMicroseconds(CurrAttrib.AsWhole());
                }else{
                    this->SetTargetFrameRate(CurrAttrib.AsWhole());
                }
            }
            else
            {
                MEZZ_EXCEPTION(Exception::SYNTAX_ERROR_EXCEPTION_XML,String("Unknown WorldSetting ")+SecName);
            }

        }

        SetupLogging(LogFileName);

        // Get the other initializer files we'll be using, since we'll need the plugins initializer.
        XML::Node InitFiles = InitRoot.GetChild("OtherInitializers");
        for( XML::NodeIterator InitIt = InitFiles.begin() ; InitIt != InitFiles.end() ; ++InitIt )
        {
            String InitFileName = (*InitIt).Name();
            if( "PluginInit" == InitFileName )
            {
                CurrAttrib = (*InitIt).GetAttribute("FileName");
                if(!CurrAttrib.Empty())
                    PluginsInit = CurrAttrib.AsString();
            }
            else if( "ResourceInit" == InitFileName )
            {
                CurrAttrib = (*InitIt).GetAttribute("FileName");
                if(!CurrAttrib.Empty())
                    ResourceInit = CurrAttrib.AsString();
            }
            else if( "GUIInit" == InitFileName )
            {
                CurrAttrib = (*InitIt).GetAttribute("FileName");
                if(!CurrAttrib.Empty())
                    GUIInit = CurrAttrib.AsString();
            }
        }

        // Load additional resource groups
        /*if(!ResourceInit.empty())
        {
            /// @todo Replace this stack allocated stream for one initialized from the Resource Manager, after the system is ready.
            Resource::FileStream ResourceStream(ResourceInit,EngineDataPath);
            XML::Document ResourceDoc;
            ResourceDoc.Load(ResourceStream);
            // Get an iterator to the first resource group node, and declare them all.
            XML::Node ResourceLocations = ResourceDoc.GetChild("ResourceLocations");
            for( XML::NodeIterator GroupIt = ResourceLocations.begin() ; GroupIt != ResourceLocations.end() ; ++GroupIt )
            {
                String GroupName, GroupType, GroupPath;
                bool GroupRecursive = false;
                // Get the group path
                CurrAttrib = (*GroupIt).GetAttribute("GroupPath");
                if(!CurrAttrib.Empty())
                    GroupPath = CurrAttrib.AsString();
                // Get the group type
                CurrAttrib = (*GroupIt).GetAttribute("GroupType");
                if(!CurrAttrib.Empty())
                    GroupType = CurrAttrib.AsString();
                // Get the group name
                CurrAttrib = (*GroupIt).GetAttribute("GroupName");
                if(!CurrAttrib.Empty())
                    GroupName = CurrAttrib.AsString();
                // Get whether this is recursive
                CurrAttrib = (*GroupIt).GetAttribute("Recursive");
                if(!CurrAttrib.Empty())
                    GroupRecursive = StringTool::ConvertToBool(CurrAttrib.AsString());
                // Finally create the resource location.
                ResourceMan->AddAssetLocation(GroupPath,GroupType,GroupName,GroupRecursive);
            }
            // Get what resource groups should be initialized.
            XML::Node InitGroups = ResourceDoc.GetChild("InitGroups");
            for( XML::NodeIterator InitIt = InitGroups.begin() ; InitIt != InitGroups.end() ; ++InitIt )
            {
                String GroupName;
                CurrAttrib = (*InitIt).GetAttribute("GroupName");
                if(!CurrAttrib.Empty())
                    GroupName = CurrAttrib.AsString();
                ResourceMan->InitAssetGroup(GroupName);
            }
        }//*/

        // Create the requested managers and set their necessary values.
        XML::Node Managers = InitRoot.GetChild("Managers");
        for( XML::NodeIterator ManIt = Managers.begin() ; ManIt != Managers.end() ; ++ManIt )
        {
            CreateManager( (*ManIt).Name(), (*ManIt) );
        }

        // Load additional resource groups
        if(!ResourceInit.empty())
        {
            /// @todo Replace this stack allocated stream for one initialized from the Resource Manager, after the system is ready.
            Resource::FileStream ResourceStream(ResourceInit,EngineDataPath);
            XML::Document ResourceDoc;
            ResourceDoc.Load(ResourceStream);
            // Get an iterator to the first resource group node, and declare them all.
            XML::Node ResourceLocations = ResourceDoc.GetChild("ResourceLocations");
            for( XML::NodeIterator GroupIt = ResourceLocations.begin() ; GroupIt != ResourceLocations.end() ; ++GroupIt )
            {
                String GroupName, GroupPath;
                ArchiveType GroupType;
                bool GroupRecursive = false;
                // Get the group path
                CurrAttrib = (*GroupIt).GetAttribute("GroupPath");
                if(!CurrAttrib.Empty())
                    GroupPath = CurrAttrib.AsString();
                // Get the group type
                CurrAttrib = (*GroupIt).GetAttribute("GroupType");
                if(!CurrAttrib.Empty())
                    GroupType = ResourceManager::GetArchiveTypeFromString(CurrAttrib.AsString());
                // Get the group name
                CurrAttrib = (*GroupIt).GetAttribute("GroupName");
                if(!CurrAttrib.Empty())
                    GroupName = CurrAttrib.AsString();
                // Get whether this is recursive
                CurrAttrib = (*GroupIt).GetAttribute("Recursive");
                if(!CurrAttrib.Empty())
                    GroupRecursive = StringTools::ConvertToBool(CurrAttrib.AsString());
                // Finally create the resource location.
                ResourceMan->AddAssetLocation(GroupPath,GroupType,GroupName,GroupRecursive);
            }
            // Get what resource groups should be initialized.
            XML::Node InitGroups = ResourceDoc.GetChild("InitGroups");
            for( XML::NodeIterator InitIt = InitGroups.begin() ; InitIt != InitGroups.end() ; ++InitIt )
            {
                String GroupName;
                CurrAttrib = (*InitIt).GetAttribute("GroupName");
                if(!CurrAttrib.Empty())
                    GroupName = CurrAttrib.AsString();
                ResourceMan->InitAssetGroup(GroupName);
            }
        }

        // Configure the UI
        if(!GUIInit.empty())
        {
            /// @todo This is currently not implemented.
        }

        SanityChecks();
    }
Ejemplo n.º 25
0
/** \brief  Creates a new preference dialog for extension preferences
    \param  name  Name of the Extension whose dialog this is
    \param  help  The help string for the extension (NULL if none)
    \param  controls  The extension specific widgets in the dialog

    This function initializes the dialog with the name of the extension
    in the title.  It adds a few buttons and sets up handlers for
    them.  It also places the passed-in widgets into the dialog.
*/
PrefDialog::PrefDialog (Glib::ustring name, gchar const * help, Gtk::Widget * controls, Effect * effect) :
#if WITH_GTKMM_3_0
    Gtk::Dialog::Dialog(_(name.c_str()), true),
#else
    Gtk::Dialog::Dialog(_(name.c_str()), true, true),
#endif
    _help(help),
    _name(name),
    _button_ok(NULL),
    _button_cancel(NULL),
    _button_preview(NULL),
    _param_preview(NULL),
    _effect(effect),
    _exEnv(NULL)
{
    Gtk::HBox * hbox = Gtk::manage(new Gtk::HBox());
    if (controls == NULL) {
        if (_effect == NULL) {
            std::cout << "AH!!!  No controls and no effect!!!" << std::endl;
            return;
        }
        controls = _effect->get_imp()->prefs_effect(_effect, SP_ACTIVE_DESKTOP, &_signal_param_change, NULL);
        _signal_param_change.connect(sigc::mem_fun(this, &PrefDialog::param_change));
    }

    hbox->pack_start(*controls, true, true, 6);
    hbox->show();
    this->get_vbox()->pack_start(*hbox, true, true, 6);

    /*
    Gtk::Button * help_button = add_button(Gtk::Stock::HELP, Gtk::RESPONSE_HELP);
    if (_help == NULL)
        help_button->set_sensitive(false);
    */
    _button_cancel = add_button(_effect == NULL ? Gtk::Stock::CANCEL : Gtk::Stock::CLOSE, Gtk::RESPONSE_CANCEL);
    _button_cancel->set_use_stock(true);

    _button_ok = add_button(_effect == NULL ? Gtk::Stock::OK : Gtk::Stock::APPLY, Gtk::RESPONSE_OK);
    _button_ok->set_use_stock(true);
    set_default_response(Gtk::RESPONSE_OK);
    _button_ok->grab_focus();

    if (_effect != NULL && !_effect->no_live_preview) {
        if (_param_preview == NULL) {
            XML::Document * doc = sp_repr_read_mem(live_param_xml, strlen(live_param_xml), NULL);
            _param_preview = Parameter::make(doc->root(), _effect);
        }

        Gtk::HSeparator * sep = Gtk::manage(new Gtk::HSeparator());
        sep->show();
        this->get_vbox()->pack_start(*sep, true, true, 4);

        hbox = Gtk::manage(new Gtk::HBox());
        _button_preview = _param_preview->get_widget(NULL, NULL, &_signal_preview);
        _button_preview->show();
        hbox->pack_start(*_button_preview, true, true,6);
        hbox->show();
        this->get_vbox()->pack_start(*hbox, true, true, 6);

        Gtk::Box * hbox = dynamic_cast<Gtk::Box *>(_button_preview);
        if (hbox != NULL) {
#if WITH_GTKMM_3_0
            _checkbox_preview = dynamic_cast<Gtk::CheckButton *>(hbox->get_children().front());
#else
            _checkbox_preview = dynamic_cast<Gtk::CheckButton *>(hbox->children().back().get_widget());
#endif
        }

        preview_toggle();
        _signal_preview.connect(sigc::mem_fun(this, &PrefDialog::preview_toggle));
    }

    // Set window modality for effects that don't use live preview
    if (_effect != NULL && _effect->no_live_preview) {
        set_modal(false);
    }

    GtkWidget *dlg = GTK_WIDGET(gobj());
    sp_transientize(dlg);

    return;
}
Ejemplo n.º 26
0
void CharDB::load()
{
    if (mLoaded)
        unload();

    XML::Document *doc = new XML::Document(
        paths.getStringValue("charCreationFile"),
        UseResman_true,
        SkipError_false);
    const XmlNodePtrConst root = doc->rootNode();

    if (!root || !xmlNameEqual(root, "chars"))
    {
        logger->log("CharDB: Failed to parse %s.",
            paths.getStringValue("charCreationFile").c_str());
        delete doc;
        return;
    }

    for_each_xml_child_node(node, root)
    {
        if (xmlNameEqual(node, "haircolor"))
        {
            loadMinMax(node, &mMinHairColor, &mMaxHairColor);
        }
        else if (xmlNameEqual(node, "hairstyle"))
        {
            loadMinMax(node, &mMinHairStyle, &mMaxHairStyle);
        }
        else if (xmlNameEqual(node, "look"))
        {
            loadMinMax(node, &mMinLook, &mMaxLook);
        }
        else if (xmlNameEqual(node, "stat"))
        {
            loadMinMax(node, &mMinStat, &mMaxStat);
            mSumStat = XML::getProperty(node, "sum", 0);
        }
        else if (xmlNameEqual(node, "item"))
        {
            const int id = XML::getProperty(node, "id", 0);
            if (id > 0)
            {
                BeingSlot slot;
                slot.spriteId = id;
                for (int f = 0; f < maxCards; f ++)
                {
                    const std::string cardName = strprintf("card%d", f + 1);
                    slot.cardsId.cards[f] = XML::getProperty(node,
                        cardName.c_str(),
                        0);
                }
                mDefaultItems.push_back(slot);
            }
        }
        else if (xmlNameEqual(node, "race"))
        {
            loadMinMax(node, &mMinRace, &mMaxRace);
        }
    }

    delete doc;

    mLoaded = true;
}
Ejemplo n.º 27
0
void testXmlFromString() {
    Xml::Document fromString;
    fromString.readFromString(xmlJustAComment);
    cout << "Just a comment: '" << fromString << "'\n";

    fromString.readFromString(xmlPlainTextFile);
    cout << "Plain text file: '" << fromString << "'\n";

    // Note that the "condense white space" setting is global, not 
    // document-specific.
    Xml::Document preserveWhite;
    Xml::Document::setXmlCondenseWhiteSpace(false);
    SimTK_TEST(!Xml::Document::isXmlWhiteSpaceCondensed());
    preserveWhite.readFromString(xmlPlainTextFile);
    cout << "Plain text file with white space preserved (raw): " 
         << preserveWhite.getRootElement().getValue() << "\n";
    cout << "... (formatted with condense=false): " 
         << preserveWhite << "\n";    
    Xml::Document::setXmlCondenseWhiteSpace(true);
    cout << "... (formatted with condense=true): " 
         << preserveWhite << "\n";    

    SimTK_TEST_MUST_THROW(fromString.readFromString(xmlEmpty));
    SimTK_TEST_MUST_THROW(fromString.readFromString(xmlUnclosedComment));

    fromString.readFromString(String(xmlPainting));
    cout << "Painting: '" << fromString << "'\n";

    cout << "Doc type is: " << fromString.getRootTag() << endl;
    cout << "  version: " << fromString.getXmlVersion() << endl;
    cout << "  encoding: " << fromString.getXmlEncoding() << endl;
    cout << "  standalone: " 
         << String(fromString.getXmlIsStandalone() ? "yes" : "no") << endl;

    cout << "All nodes in doc:\n";
    Xml::node_iterator np = fromString.node_begin();
    for (; np != fromString.node_end(); ++np)
        cout << "  " << np->getNodeTypeAsString() << endl;


    Xml::Element root = fromString.getRootElement();

    cout << "hasNode()=" << root.hasNode() << endl;
    cout << "hasNode(Comment)=" << root.hasNode(Xml::CommentNode) << endl;
    cout << "hasNode(Unknown)=" << root.hasNode(Xml::UnknownNode) << endl;

    showElement(root);

    Xml::node_iterator p = root.node_begin(Xml::NoJunkNodes);
    for (; p != root.node_end(); ++p)
        cout << p->getNodeTypeAsString() << endl;

    cout << "Caption elements:\n";
    Xml::element_iterator ep(root.element_begin("caption"));
    for (; ep != root.element_end(); ++ep)
        cout << ep->getNodeTypeAsString() << ": <" << ep->getElementTag() 
             << ">" << endl;

    cout << "All elements:\n";
    Array_<Xml::Element> all = root.getAllElements();
    for (unsigned i=0; i < all.size(); ++i)
        cout << "<" << all[i].getElementTag() << ">" << endl;


    Array_<Xml::Node> allNodes(root.node_begin(Xml::NoJunkNodes), 
                               root.node_end());
    for (unsigned i=0; i < allNodes.size(); ++i)
        cout << "Node " << allNodes[i].getNodeTypeAsString() << endl;

    String prettyString, compactString;
    fromString.writeToString(prettyString);
    cout << "String pretty: " << prettyString.size() 
         << "\n'" << prettyString << "'\n";

    fromString.writeToString(compactString, true); // compact
    cout << "String compact: " << compactString.size() 
         << "\n'" << compactString << "'\n";

    SimTK_TEST(compactString.size() < prettyString.size());

    cout << "painting.allNode=" << root.getRequiredElement("painting")
                                        .getAllNodes() << endl;
    cout << "painting.img.allAttr=" << 
        root.getRequiredElement("painting").getRequiredElement("img")
        .getAllAttributes() << endl;
    //fromString.writeToFile("TestXml.xml");

    //Xml ex("TestXml.xml");
    //cout << "Document tag: " << ex.getDocumentTag() << endl;
    //for (Xml::nodu;e_iterator xp=ex.node_begin(); xp != ex.node_end(); ++xp)
    //    cout << "Node type: " << xp->getNodeTypeAsString() << endl;

    //PolygonalMesh mesh;
    //mesh.loadVtpFile("arm_r_humerus.vtp");
    //cout << "num vertices=" << mesh.getNumVertices() << " faces="
    //    << mesh.getNumFaces() << endl;
}
Ejemplo n.º 28
0
Bool BonkEnc::CDDBBatch::ReadEntries()
{
	String	 inputFormat = String::SetInputFormat("UTF-8");
	String	 outputFormat = String::SetOutputFormat("UTF-8");

	// Read saved queries from XML

	XML::Document	*document = new XML::Document();

	if (document->LoadFile(String(config->configDir).Append("cddb\\queries.xml")) == Success())
	{
		XML::Node	*root = document->GetRootNode();

		if (root != NIL)
		{
			for (Int i = 0; i < root->GetNOfNodes(); i++)
			{
				XML::Node	*node = root->GetNthNode(i);

				if (node->GetName() == "query") queries.Add(node->GetContent());
			}
		}
	}

	delete document;

	// Read saved submits from XML and database cache

	document = new XML::Document();

	if (document->LoadFile(String(config->configDir).Append("cddb\\submits.xml")) == Success())
	{
		XML::Node	*root = document->GetRootNode();

		if (root != NIL)
		{
			for (Int i = 0; i < root->GetNOfNodes(); i++)
			{
				XML::Node	*node = root->GetNthNode(i);

				if (node->GetName() == "submit")
				{
					InStream	*in = new InStream(STREAM_FILE, String(config->configDir).Append("cddb\\").Append(node->GetAttributeByName("category")->GetContent()).Append("\\").Append(node->GetContent()), IS_READONLY);

					if (in->Size() > 0)
					{
						String	 result = in->InputString(in->Size());
						CDDBInfo cddbInfo;

						ParseCDDBRecord(result, cddbInfo);

						cddbInfo.category = node->GetAttributeByName("category")->GetContent();

						for (Int i = 0; i < submits.Length(); i++)
						{
							if (submits.GetNth(i) == cddbInfo)
							{
								submits.Remove(submits.GetNthIndex(i));

								break;
							}
						}

						submits.Add(cddbInfo);
					}

					delete in;
				}
			}
		}
	}

	delete document;

	String::SetInputFormat(inputFormat);
	String::SetOutputFormat(outputFormat);

	return True;
}