void XMLEntityMappingDefinitionSerializer::parseScript(TiXmlDocument& xmlDocument)
{

	TiXmlElement* rootElem = xmlDocument.RootElement();

	if (rootElem) {

		for (TiXmlElement* smElem = rootElem->FirstChildElement("entitymapping");
				smElem != 0; smElem = smElem->NextSiblingElement("entitymapping"))
		{
			const char* tmp =  smElem->Attribute("name");
			if (!tmp) {
				continue;
			} else {
				EntityMappingDefinition* definition(0);
				try {
					const std::string name(tmp);
					definition = new EntityMappingDefinition();
					definition->setName(name);
					TiXmlElement* matchElement = smElem->FirstChildElement();
					parseMatchElement(*definition, definition->getRoot(), matchElement);
					mEntityMappingManager.addDefinition(definition);
				} catch (const std::exception& ex) {
					S_LOG_FAILURE("Error when reading model mapping with name '" << tmp << "'." << ex);
					delete definition;
				} catch (...) {
					S_LOG_FAILURE("Error when reading model mapping with name '" << tmp << "'.");
					delete definition;
				}
			}

		}


		for (TiXmlElement* smElem = rootElem->FirstChildElement("nomodel");
				smElem != 0; smElem = smElem->NextSiblingElement("nomodel"))
		{
			const char* tmp =  smElem->Attribute("name");
			if (!tmp) {
				continue;
			} else {
				const std::string name(tmp);
				EntityMappingDefinition* definition(0);
				try {
					definition = new EntityMappingDefinition();
					definition->setName(name);
					definition->getRoot().setType("entitytype");
					CaseDefinition caseDef;
					caseDef.setType("entitytypecase");
					caseDef.getCaseParameters().push_back(CaseDefinition::ParameterEntry("equals", name));
					ActionDefinition actionDef;
					actionDef.setType("hide-model");

					caseDef.getActions().push_back(actionDef);
					definition->getRoot().getCases().push_back(caseDef);

				} catch (const std::exception& ex) {
					delete definition;
					//S_LOG_FAILURE(ex.what());
				} catch (...) {
					delete definition;
					//S_LOG_FAILURE("Error when reading model mapping with name " << name);
				}
				if (definition) {
					mEntityMappingManager.addDefinition(definition);
				}
			}
		}

		//Check for autoentitymapping elements, which allow for a quick mapping between a entity type and a model.
		//format: <autoentitymapping name="oak">
		//or: <autoentitymapping name="oak" modelname="oak_1">
		for (TiXmlElement* smElem = rootElem->FirstChildElement("autoentitymapping");
				smElem != 0; smElem = smElem->NextSiblingElement("autoentitymapping"))
		{
			const char* tmp =  smElem->Attribute("name");
			if (!tmp) {
				continue;
			} else {
				const std::string name(tmp);
				EntityMappingDefinition* definition(0);
				try {
					definition = new EntityMappingDefinition();
					definition->setName(name);
					definition->getRoot().setType("entitytype");
					CaseDefinition caseDef;
					caseDef.setType("entitytypecase");
					caseDef.getCaseParameters().push_back(CaseDefinition::ParameterEntry("equals", name));
					ActionDefinition actionDef;
					actionDef.setType("display-model");

					//check if a model name is set
					const char* tmpModelName = smElem->Attribute("modelname");
					if (tmpModelName) {
						actionDef.setValue(std::string(tmpModelName));
					} else {
						actionDef.setValue(name);
					}

					caseDef.getActions().push_back(actionDef);
					definition->getRoot().getCases().push_back(caseDef);

				} catch (const std::exception& ex) {
					delete definition;
					//S_LOG_FAILURE(ex.what());
				} catch (...) {
					//S_LOG_FAILURE("Error when reading model mapping with name " << name);
					delete definition;
				}
				if (definition) {
					mEntityMappingManager.addDefinition(definition);
				}
			}
		}
	}
}
Esempio n. 2
0
bool CBill::load()
{
	string appPath = getAppPath();
	string sFileNmae = appPath + "tdbilldata.xml";
	// 有时间编译boost
	//if (QFileInfo(sFileNmae).exists())
	//{
	//	cout << sFileNmae << endl;
	//}
	//else
	//{
	//	cout << "未发现数据文件" << endl;
	//}
	cout << sFileNmae << endl;

	//读取xml文件,并遍历
	try
	{
		//创建一个xml的文档对象。
		TiXmlDocument *oDocument = new TiXmlDocument(sFileNmae.c_str());
		oDocument->LoadFile();
		TiXmlElement* root = oDocument->RootElement();

		for (TiXmlNode*  item = root->FirstChild("item"); item;	item = item->NextSibling("item"))
		{
			TiXmlAttribute *oItemAttr = item->ToElement()->FirstAttribute();
			int nItemOrder = boost::lexical_cast<int>(oItemAttr->Value());
			oItemAttr = oItemAttr->Next();
			string sItemName = UTF8ToGBK(string(oItemAttr->Value()));  // 能自动判断编码就好
			CItem* pItem = new CItem(nItemOrder, sItemName);

			for (TiXmlNode* volume = item->FirstChild("volume"); volume; volume = volume->NextSibling("volume"))
			{
				TiXmlAttribute *oVolumeAttr = volume->ToElement()->FirstAttribute();
				int nVolumeOrder = boost::lexical_cast<int>(oVolumeAttr->Value());
				oVolumeAttr = oVolumeAttr->Next();
				string sVolumeTime = UTF8ToGBK(string(oVolumeAttr->Value()));
				CVolume* pVolume = new CVolume(nVolumeOrder, sVolumeTime);

				for (TiXmlNode* goods = volume->FirstChild("goods"); goods; goods = goods->NextSibling("goods"))
				{
					TiXmlAttribute *oGoodsAttr = goods->ToElement()->FirstAttribute();
					int nGoodsOrder = boost::lexical_cast<int>(oGoodsAttr->Value());
					oGoodsAttr = oGoodsAttr->Next();
					string sGoodsType = UTF8ToGBK(string(oGoodsAttr->Value()));
					oGoodsAttr = oGoodsAttr->Next();
					int nGoodsNum = boost::lexical_cast<int>(oGoodsAttr->Value());
					oGoodsAttr = oGoodsAttr->Next();
					string sGoodsPrice = string(oGoodsAttr->Value());
					oGoodsAttr = oGoodsAttr->Next();
					string sGoodsTotalPrice = string(oGoodsAttr->Value());
					oGoodsAttr = oGoodsAttr->Next();
					string sGoodsCustodial = oGoodsAttr->Value();
					oGoodsAttr = oGoodsAttr->Next();
					int nSucc = boost::lexical_cast<int>(oGoodsAttr->Value());

					CCoin oGoodsPrice = CCoin(sGoodsPrice);
					CCoin oGoodsTotalPrice = CCoin(sGoodsTotalPrice);
					CCoin oGoodsCustodial = CCoin(sGoodsCustodial);

					CGoods * pGoods = new CGoods(nGoodsOrder, sGoodsType, nGoodsNum, sGoodsPrice, sGoodsTotalPrice, sGoodsCustodial, TOBOOL(nSucc));
					pVolume->addGoods(pGoods);
				}
				pItem->addVolume(pVolume);
			}
			addItem(pItem);
		}
	}
	catch (string& e)
	{
		cout << "读取数据失败: " << e << endl;
		return false;
	}
	return true;
}
Esempio n. 3
0
void CGUIDialogContentSettings::OnWindowLoaded()
{
    CGUIDialogSettings::OnWindowLoaded();

    CFileItemList items;
    if (m_info.strContent.Equals("albums"))
        CDirectory::GetDirectory(_P("q:\\system\\scrapers\\music"),items,".xml",false);
    else
        CDirectory::GetDirectory(_P("q:\\system\\scrapers\\video"),items,".xml",false);
    for (int i=0; i<items.Size(); ++i)
    {
        if (!items[i]->m_bIsFolder)
        {
            TiXmlDocument doc;
            doc.LoadFile(items[i]->m_strPath);
            if (doc.RootElement())
            {
                const char* content = doc.RootElement()->Attribute("content");
                const char* name = doc.RootElement()->Attribute("name");
                const char* thumb = doc.RootElement()->Attribute("thumb");
                if (content && name)
                {
                    SScraperInfo info;
                    info.strTitle = name;
                    info.strPath = CUtil::GetFileName(items[i]->m_strPath);
                    if (thumb)
                        info.strThumb = thumb;
                    info.strContent = content;
                    info.settings = m_scraperSettings;
                    std::map<CStdString,std::vector<SScraperInfo> >::iterator iter=m_scrapers.find(content);
                    if (iter != m_scrapers.end())
                        iter->second.push_back(info);
                    else
                    {
                        std::vector<SScraperInfo> vec;
                        vec.push_back(info);
                        m_scrapers.insert(std::make_pair<CStdString,std::vector<SScraperInfo> >(content,vec));
                    }
                }
            }
        }
    }

    // now select the correct scraper
    if (!m_info.strContent.IsEmpty())
    {
        std::map<CStdString,std::vector<SScraperInfo> >::iterator iter = m_scrapers.find(m_info.strContent);
        if (iter != m_scrapers.end())
        {
            for (std::vector<SScraperInfo>::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2)
            {
                if (iter2->strPath == m_info.strPath)
                {
                    m_info = *iter2;
                    break;
                }
            }
        }
    }

    CScraperParser parser;
    CStdString strPath;
    if (!m_info.strContent.IsEmpty())
        strPath="q:\\system\\scrapers\\video\\"+m_info.strPath;
    if (!strPath.IsEmpty() && parser.Load(strPath) && parser.HasFunction("GetSettings"))
    {
        CONTROL_ENABLE(CONTROL_SCRAPER_SETTINGS)
    }
    else
    {
        CONTROL_DISABLE(CONTROL_SCRAPER_SETTINGS)
    }
}
Esempio n. 4
0
void DotSceneLoader::parseDotScene(const String &SceneName, const String &groupName, SceneManager *yourSceneMgr, SceneNode *pAttachNode, const String &sPrependNode)
{
	// set up shared object values
	m_sGroupName = groupName;
	mSceneMgr = yourSceneMgr;
	m_sPrependNode = sPrependNode;
	staticObjects.clear();
	dynamicObjects.clear();

	TiXmlDocument   *XMLDoc = 0;
	TiXmlElement   *XMLRoot;

	try
	{
		// Strip the path
		Ogre::String basename, path;
		Ogre::StringUtil::splitFilename(SceneName, basename, path);

		DataStreamPtr pStream = ResourceGroupManager::getSingleton().
			openResource( basename, groupName );

		//DataStreamPtr pStream = ResourceGroupManager::getSingleton().
		//	openResource( SceneName, groupName );

		String data = pStream->getAsString();
		// Open the .scene File
		XMLDoc = new TiXmlDocument();
		XMLDoc->Parse( data.c_str() );
		pStream->close();
		pStream.setNull();

		if( XMLDoc->Error() )
		{
			//We'll just log, and continue on gracefully
			GDebugger::GetSingleton().WriteToLog("[DotSceneLoader] The TiXmlDocument reported an error\n");
			delete XMLDoc;
			return;
		}
	}
	catch(Exception *ep)
	{
		//We'll just log, and continue on gracefully
		GDebugger::GetSingleton().WriteToLog("[DotSceneLoader] Error creating tixmldocument: %s\n",ep->getDescription().c_str());
		delete XMLDoc;
		return;
	}

	// Validate the File
	XMLRoot = XMLDoc->RootElement();
	if( String( XMLRoot->Value()) != "scene"  ) {
		LogManager::getSingleton().logMessage( "[DotSceneLoader] Error: Invalid .scene File. Missing <scene>" );
		delete XMLDoc;      
		return;
	}

	// figure out where to attach any nodes we create
	mAttachNode = pAttachNode;
	if(!mAttachNode)
		mAttachNode = mSceneMgr->getRootSceneNode();

	// Process the scene
	processScene(XMLRoot);

	// Close the XML File
	delete XMLDoc;
}
bool InternetRetrievalDialog::OpenXML(wxString filename)
{
    ClearInternetRetrieval();
    m_lServers->Clear();

    TiXmlDocument doc;
    wxString error;
    wxProgressDialog *progressdialog = NULL;
    wxDateTime start = wxDateTime::UNow();

    if(!doc.LoadFile(filename.mb_str()))
        FAIL(_("Failed to load file: ") + filename);
    else {
        TiXmlElement *root = doc.RootElement();
        if(strcmp(root->Value(), "OCPNWeatherFaxInternetRetrieval"))
            FAIL(_("Invalid xml file"));

        int count = 0;
        for(TiXmlElement* e = root->FirstChildElement(); e; e = e->NextSiblingElement())
            count++;

        int i=0;
        for(TiXmlElement* e = root->FirstChildElement(); e; e = e->NextSiblingElement(), i++) {
            if(progressdialog) {
                if(!progressdialog->Update(i))
                    return true;
            } else {
                wxDateTime now = wxDateTime::UNow();
                if((now-start).GetMilliseconds() > 500 && i < count/3) {
                    progressdialog = new wxProgressDialog(
                        _("WeatherFax Internet Retrieval"), _("Loading"), count, this,
                        wxPD_CAN_ABORT | wxPD_ELAPSED_TIME | wxPD_REMAINING_TIME);
                }
            }

            if(!strcmp(e->Value(), "Server")) {
                FaxServer server;
                server.Name = wxString::FromUTF8(e->Attribute("Name"));

                m_Servers.push_back(server);

                wxString server_url = wxString::FromUTF8(e->Attribute("Url"));
                m_lServers->Append(server.Name);

                for(TiXmlElement* f = e->FirstChildElement(); f; f = f->NextSiblingElement()) {
                    if(!strcmp(f->Value(), "Region")) {
                        FaxRegion region;
                        region.Name = wxString::FromUTF8(f->Attribute("Name"));
                        region.Server = server.Name;

                        for(std::list<FaxRegion>::iterator it = m_Regions.begin();
                            it != m_Regions.end(); it++)
                            if(it->Name == region.Name && it->Server == region.Server)
                                goto duplicate_region;

                        m_Regions.push_back(region);
                    duplicate_region:

                        wxString region_url = server_url + wxString::FromUTF8(f->Attribute("Url"));

                        std::list<FaxUrl> urls;
                        std::list<FaxArea> Areas;

                        for(TiXmlElement* g = f->FirstChildElement(); g; g = g->NextSiblingElement()) {
                            if(!strcmp(g->Value(), "Iterator")) {
                                wxString s_start = wxString::FromUTF8(g->Attribute("From"));
                                wxString s_to = wxString::FromUTF8(g->Attribute("To"));
                                wxString s_by = wxString::FromUTF8(g->Attribute("By"));

                                if(s_start.size() == 0 || s_to.size() == 0 || s_by.size() == 0)
                                    FAIL(_("Invalid iterator: ") + wxString::FromUTF8(g->Value()));
                                
                                long start, to, by;
                                s_start.ToLong(&start);
                                s_to.ToLong(&to);
                                s_by.ToLong(&by);

                                for(TiXmlElement* h = g->FirstChildElement(); h; h = h->NextSiblingElement()) {
                                    if(!strcmp(h->Value(), "Map")) {
                                        FaxUrl url;
                                    
                                        url.Scheduled = false;
                                        url.Server = server.Name;
                                        url.Region = region.Name;
                         
                                        for(int index = start; index <= to; index += by) {
                                            wxString iurl = wxString::FromUTF8(h->Attribute("Url"));
                                            url.Url = region_url + wxString::Format
                                                (iurl, index);
                                            url.Contents = wxString::Format
                                                (wxString::FromUTF8(h->Attribute("Contents")), index);
                                            url.area_name = wxString::FromUTF8(h->Attribute("Area"));
                                        
                                            urls.push_back(url);
                                        }
                                    } else
                                        FAIL(_("Unrecognized xml node: ") + wxString::FromUTF8(g->Value()));
                                }
                            } else if(!strcmp(g->Value(), "Map")) {
                                FaxUrl url;
                                    
                                url.Scheduled = false;
                                url.Server = server.Name;
                                url.Region = region.Name;
                         
                                url.Url = region_url + wxString::FromUTF8(g->Attribute("Url"));
                                url.Contents = wxString::FromUTF8(g->Attribute("Contents"));
                                url.area_name = wxString::FromUTF8(g->Attribute("Area"));

                                urls.push_back(url);
                            } else if(!strcmp(g->Value(), "Area")) {
                                FaxArea Area;
                                Area.name = wxString::FromUTF8(g->Attribute("Name"));
                                Area.description = wxString::FromUTF8(g->Attribute("Description"));
                        
                                Area.lat1 = ParseLatLon(wxString::FromUTF8(g->Attribute("lat1")));
                                Area.lat2 = ParseLatLon(wxString::FromUTF8(g->Attribute("lat2")));
                                Area.lon1 = ParseLatLon(wxString::FromUTF8(g->Attribute("lon1")));
                                Area.lon2 = ParseLatLon(wxString::FromUTF8(g->Attribute("lon2")));

                                Areas.push_back(Area);
                            } else
                                FAIL(_("Unrecognized xml node: ") + wxString::FromUTF8(g->Value()));
                        }

                        for(std::list<FaxUrl>::iterator it = urls.begin();
                            it != urls.end(); it++) {
                            if((*it).area_name.size()) {
                                for(std::list<FaxArea>::iterator it2 = Areas.begin();
                                    it2 != Areas.end(); it2++)
                                    if((*it).area_name == (*it2).name) {
                                        (*it).Area = *it2;
                                        goto resolved;
                                    }
                                FAIL(_("Failed to match Area: ") + (*it).area_name);
                            }
                        resolved:
                            FaxUrl *s = new FaxUrl(*it);
                            m_InternetRetrieval.push_back(s);
                        }
                    } else
                        FAIL(_("Unrecognized xml node: ") + wxString::FromUTF8(f->Value()));
                }
            } else
                FAIL(_("Unrecognized xml node: ") + wxString::FromUTF8(e->Value()));
        }
    }

    delete progressdialog;
    return true;

failed:
    delete progressdialog;

    wxMessageDialog mdlg(this, error, _("Weather Fax"), wxOK | wxICON_ERROR);
    mdlg.ShowModal();

    return false;
}
Esempio n. 6
0
void StyleManager::Init( wxString fromPath )
{
    TiXmlDocument doc;

    if( !wxDir::Exists( fromPath ) ) {
        wxString msg = _T("No styles found at: ");
        msg << fromPath;
        wxLogMessage( msg );
        return;
    }

    wxDir dir( fromPath );
    if( !dir.IsOpened() ) return;

    wxString filename;

    // We allow any number of styles to load from files called style<something>.xml

    bool more = dir.GetFirst( &filename, _T("style*.xml"), wxDIR_FILES );

    if( !more ) {
        wxString msg = _T("No styles found at: ");
        msg << fromPath;
        wxLogMessage( msg );
        return;
    }

    bool firstFile = true;
    while( more ) {
        wxString name, extension;

        if( !firstFile ) more = dir.GetNext( &filename );
        if( !more ) break;
        firstFile = false;

        wxString fullFilePath = fromPath + filename;

        if( !doc.LoadFile( (const char*) fullFilePath.mb_str() ) ) {
            wxString msg( _T("Attempt to load styles from this file failed: ") );
            msg += fullFilePath;
            wxLogMessage( msg );
            continue;
        }

        wxString msg( _T("Styles loading from ") );
        msg += fullFilePath;
        wxLogMessage( msg );

        TiXmlHandle hRoot( doc.RootElement() );

        wxString root = wxString( doc.RootElement()->Value(), wxConvUTF8 );
        if( root != _T("styles" ) ) {
            wxLogMessage( _T("    StyleManager: Expected XML Root <styles> not found.") );
            continue;
        }

        TiXmlElement* styleElem = hRoot.FirstChild().Element();

        for( ; styleElem; styleElem = styleElem->NextSiblingElement() ) {

            if( wxString( styleElem->Value(), wxConvUTF8 ) == _T("style") ) {

                Style* style = new Style();
                styles.Add( style );

                style->name = wxString( styleElem->Attribute( "name" ), wxConvUTF8 );
                style->myConfigFileDir = fromPath;

                TiXmlElement* subNode = styleElem->FirstChild()->ToElement();

                for( ; subNode; subNode = subNode->NextSiblingElement() ) {
                    wxString nodeType( subNode->Value(), wxConvUTF8 );

                    if( nodeType == _T("description") ) {
                        style->description = wxString( subNode->GetText(), wxConvUTF8 );
                        continue;
                    }
                    if( nodeType == _T("chart-status-icon") ) {
                        int w = 0;
                        subNode->QueryIntAttribute( "width", &w );
                        style->chartStatusIconWidth = w;
                        continue;
                    }
                    if( nodeType == _T("chart-status-window") ) {
                        style->chartStatusWindowTransparent = wxString(
                                subNode->Attribute( "transparent" ), wxConvUTF8 ).Lower().IsSameAs(
                                        _T("true") );
                        continue;
                    }
                    if( nodeType == _T("embossed-indicators") ) {
                        style->embossFont = wxString( subNode->Attribute( "font" ), wxConvUTF8 );
                        subNode->QueryIntAttribute( "size", &(style->embossHeight) );
                        continue;
                    }
                    if( nodeType == _T("graphics-file") ) {
                        style->graphicsFile = wxString( subNode->Attribute( "name" ), wxConvUTF8 );
                        isOK = true; // If we got this far we are at least partially OK...
                        continue;
                    }
                    if( nodeType == _T("active-route") ) {
                        TiXmlHandle handle( subNode );
                        TiXmlElement* tag = handle.Child( "font-color", 0 ).ToElement();
                        if( tag ) {
                            int r, g, b;
                            tag->QueryIntAttribute( "r", &r );
                            tag->QueryIntAttribute( "g", &g );
                            tag->QueryIntAttribute( "b", &b );
                            style->consoleFontColor = wxColour( r, g, b );
                        }
                        tag = handle.Child( "text-background-location", 0 ).ToElement();
                        if( tag ) {
                            int x, y, w, h;
                            tag->QueryIntAttribute( "x", &x );
                            tag->QueryIntAttribute( "y", &y );
                            tag->QueryIntAttribute( "width", &w );
                            tag->QueryIntAttribute( "height", &h );
                            style->consoleTextBackgroundLoc = wxPoint( x, y );
                            style->consoleTextBackgroundSize = wxSize( w, h );
                        }
                        continue;
                    }
                    if( nodeType == _T("icons") ) {
                        TiXmlElement* iconNode = subNode->FirstChild()->ToElement();

                        for( ; iconNode; iconNode = iconNode->NextSiblingElement() ) {
                            wxString nodeType( iconNode->Value(), wxConvUTF8 );
                            if( nodeType == _T("icon") ) {
                                Icon* icon = new Icon();
                                style->icons.Add( icon );
                                icon->name = wxString( iconNode->Attribute( "name" ), wxConvUTF8 );
                                style->iconIndex[icon->name] = style->icons.Count() - 1;
                                TiXmlHandle handle( iconNode );
                                TiXmlElement* tag = handle.Child( "icon-location", 0 ).ToElement();
                                if( tag ) {
                                    int x, y;
                                    tag->QueryIntAttribute( "x", &x );
                                    tag->QueryIntAttribute( "y", &y );
                                    icon->iconLoc = wxPoint( x, y );
                                }
                                tag = handle.Child( "size", 0 ).ToElement();
                                if( tag ) {
                                    int x, y;
                                    tag->QueryIntAttribute( "x", &x );
                                    tag->QueryIntAttribute( "y", &y );
                                    icon->size = wxSize( x, y );
                                }
                            }
                        }
                    }
                    if( nodeType == _T("tools") ) {
                        TiXmlElement* toolNode = subNode->FirstChild()->ToElement();

                        for( ; toolNode; toolNode = toolNode->NextSiblingElement() ) {
                            wxString nodeType( toolNode->Value(), wxConvUTF8 );

                            if( nodeType == _T("horizontal") || nodeType == _T("vertical") ) {
                                int orientation = 0;
                                if( nodeType == _T("vertical") ) orientation = 1;

                                TiXmlElement* attrNode = toolNode->FirstChild()->ToElement();
                                for( ; attrNode; attrNode = attrNode->NextSiblingElement() ) {
                                    wxString nodeType( attrNode->Value(), wxConvUTF8 );
                                    if( nodeType == _T("separation") ) {
                                        attrNode->QueryIntAttribute( "distance",
                                                                     &style->toolSeparation[orientation] );
                                        continue;
                                    }
                                    if( nodeType == _T("margin") ) {
                                        attrNode->QueryIntAttribute( "top",
                                                                     &style->toolMarginTop[orientation] );
                                        attrNode->QueryIntAttribute( "right",
                                                                     &style->toolMarginRight[orientation] );
                                        attrNode->QueryIntAttribute( "bottom",
                                                                     &style->toolMarginBottom[orientation] );
                                        attrNode->QueryIntAttribute( "left",
                                                                     &style->toolMarginLeft[orientation] );
                                        wxString invis = wxString(
                                                             attrNode->Attribute( "invisible" ), wxConvUTF8 );
                                        style->marginsInvisible = ( invis.Lower() == _T("true") );
                                        continue;;
                                    }
                                    if( nodeType == _T("toggled-location") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->toggledBGlocation[orientation] = wxPoint( x, y );
                                        x = 0;
                                        y = 0;
                                        attrNode->QueryIntAttribute( "width", &x );
                                        attrNode->QueryIntAttribute( "height", &y );
                                        style->toggledBGSize[orientation] = wxSize( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("toolbar-start") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->toolbarStartLoc[orientation] = wxPoint( x, y );
                                        x = 0;
                                        y = 0;
                                        attrNode->QueryIntAttribute( "width", &x );
                                        attrNode->QueryIntAttribute( "height", &y );
                                        style->toolbarStartSize[orientation] = wxSize( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("toolbar-end") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->toolbarEndLoc[orientation] = wxPoint( x, y );
                                        x = 0;
                                        y = 0;
                                        attrNode->QueryIntAttribute( "width", &x );
                                        attrNode->QueryIntAttribute( "height", &y );
                                        style->toolbarEndSize[orientation] = wxSize( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("toolbar-corners") ) {
                                        int r;
                                        attrNode->QueryIntAttribute( "radius", &r );
                                        style->cornerRadius[orientation] = r;
                                        continue;
                                    }
                                    if( nodeType == _T("background-location") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->normalBGlocation[orientation] = wxPoint( x, y );
                                        style->HasBackground( true );
                                        continue;
                                    }
                                    if( nodeType == _T("active-location") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->activeBGlocation[orientation] = wxPoint( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("size") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->toolSize[orientation] = wxSize( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("icon-offset") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->verticalIconOffset = wxSize( x, y );
                                        continue;
                                    }
                                }
                                continue;
                            }
                            if( nodeType == _T("compass") ) {

                                TiXmlElement* attrNode = toolNode->FirstChild()->ToElement();
                                for( ; attrNode; attrNode = attrNode->NextSiblingElement() ) {
                                    wxString nodeType( attrNode->Value(), wxConvUTF8 );
                                    if( nodeType == _T("margin") ) {
                                        attrNode->QueryIntAttribute( "top",
                                                                     &style->compassMarginTop );
                                        attrNode->QueryIntAttribute( "right",
                                                                     &style->compassMarginRight );
                                        attrNode->QueryIntAttribute( "bottom",
                                                                     &style->compassMarginBottom );
                                        attrNode->QueryIntAttribute( "left",
                                                                     &style->compassMarginLeft );
                                        continue;
                                    }
                                    if( nodeType == _T("compass-corners") ) {
                                        int r;
                                        attrNode->QueryIntAttribute( "radius", &r );
                                        style->compasscornerRadius = r;
                                        continue;
                                    }
                                    if( nodeType == _T("offset") ) {
                                        attrNode->QueryIntAttribute( "x",
                                                                     &style->compassXoffset );
                                        attrNode->QueryIntAttribute( "y",
                                                                     &style->compassYoffset );
                                        continue;
                                    }
                                }
                            }

                            if( nodeType == _T("tool") ) {
                                Tool* tool = new Tool();
                                style->tools.Add( tool );
                                tool->name = wxString( toolNode->Attribute( "name" ), wxConvUTF8 );
                                style->toolIndex[tool->name] = style->tools.Count() - 1;
                                TiXmlHandle toolHandle( toolNode );
                                TiXmlElement* toolTag =
                                    toolHandle.Child( "icon-location", 0 ).ToElement();
                                if( toolTag ) {
                                    int x, y;
                                    toolTag->QueryIntAttribute( "x", &x );
                                    toolTag->QueryIntAttribute( "y", &y );
                                    tool->iconLoc = wxPoint( x, y );
                                }
                                toolTag = toolHandle.Child( "rollover-location", 0 ).ToElement();
                                if( toolTag ) {
                                    int x, y;
                                    toolTag->QueryIntAttribute( "x", &x );
                                    toolTag->QueryIntAttribute( "y", &y );
                                    tool->rolloverLoc = wxPoint( x, y );
                                }
                                toolTag = toolHandle.Child( "disabled-location", 0 ).ToElement();
                                if( toolTag ) {
                                    int x, y;
                                    toolTag->QueryIntAttribute( "x", &x );
                                    toolTag->QueryIntAttribute( "y", &y );
                                    tool->disabledLoc = wxPoint( x, y );
                                }
                                toolTag = toolHandle.Child( "size", 0 ).ToElement();
                                if( toolTag ) {
                                    int x, y;
                                    toolTag->QueryIntAttribute( "x", &x );
                                    toolTag->QueryIntAttribute( "y", &y );
                                    tool->customSize = wxSize( x, y );
                                }
                                continue;
                            }
                        }
                        continue;
                    }
                }
            }
        }
    }
}
// This function will parse through an XML file to construct an array of
// EntityXmlStruct structures
std::vector<EntityXmlStruct> StateEntityParser::parse(ApplicationState* state,
                                                    int parsingLayer)
{
    std::vector<EntityXmlStruct> error;

    TiXmlDocument xmlDoc;

    // Return false if the XML file is not found
    if (!xmlDoc.LoadFile(state->getXmlPath().c_str()))
    {
        printf("[ERROR] parse(): Xml file not found.\n");
        return error;
    }

    // The root element of this xml file
    TiXmlElement* rootElement = xmlDoc.RootElement();

    // The parsing layer root element of this xml file
    TiXmlElement* rootParsingLayer = NULL;

    // Parses through State subelements to find correct parsing layer
    // element, then assigning it to it's own root variable
    for (   TiXmlElement* e = rootElement->FirstChildElement();
            e != NULL;
            e = e->NextSiblingElement())
    {
        if (e->Value() == mapEnumeration(parsingLayer))
        {
            rootParsingLayer = e;
        }
    }

    // Return false if the parsing layer element is not found
    if (rootParsingLayer == NULL)
    {
        printf("[ERROR] parse(): Parsing layer element not found.\n");
        return error;
    }

    // Gets the number of elements in order to construct array
    int arraySize = 0;
    for (   TiXmlElement* e = rootParsingLayer->FirstChildElement();
            e != NULL;
            e = e->NextSiblingElement())
    {
        arraySize++;
    }
    std::vector<EntityXmlStruct> xmlStruct(arraySize);

    // Parses through subelements of the parsing layer element and
    // fills values of the array of EntityXmlStruct as we go
    int index = 0;
    for (   TiXmlElement* e = rootParsingLayer->FirstChildElement();
            e != NULL;
            e = e->NextSiblingElement())
    {
        if (e->Attribute("id") != NULL)
        {
            // Converting c_str to std::string
            const char* cString = e->Attribute("id");
            int cStringSize = strlen(cString);
            xmlStruct[index].id.assign(cString, cStringSize);
        }

        if (e->Attribute("name") != NULL)
        {
            // Converting c_str to std::string
            const char* cString = e->Attribute("name");
            int cStringSize = strlen(cString);
            xmlStruct[index].name.assign(cString, cStringSize);
        }

        if (e->Attribute("type") != NULL)
        {
            // Converting c_str to std::string
            const char* cString = e->Attribute("type");
            int cStringSize = strlen(cString);
            xmlStruct[index].type.assign(cString, cStringSize);
        }

        if (e->Attribute("data") != NULL)
        {
            // Converting c_str to std::string
            const char* cString = e->Attribute("data");
            int cStringSize = strlen(cString);
            xmlStruct[index].data.assign(cString, cStringSize);
        }

        if (e->Attribute("texture") != NULL)
        {
            // Converting c_str to std::string
            const char* cString = e->Attribute("texture");
            int cStringSize = strlen(cString);
            xmlStruct[index].texture.assign(cString, cStringSize);
        }

        if (e->Attribute("spritesheet") != NULL)
        {
            // Converting c_str to std::string
            const char* cString = e->Attribute("spritesheet");
            int cStringSize = strlen(cString);
            xmlStruct[index].spritesheet.assign(cString, cStringSize);
        }

        if (e->Attribute("function") != NULL)
        {
            // Converting c_str to std::string
            const char* cString = e->Attribute("function");
            int cStringSize = strlen(cString);
            xmlStruct[index].function.assign(cString, cStringSize);
        }

        if (e->Attribute("x") != NULL)
        {
            xmlStruct[index].x = atoi(e->Attribute("x"));
        }

        if (e->Attribute("y") != NULL)
        {
            xmlStruct[index].y = atoi(e->Attribute("y"));
        }

        if (e->Attribute("width") != NULL)
        {
            xmlStruct[index].width = atoi(e->Attribute("width"));
        }

        if (e->Attribute("height") != NULL)
        {
            xmlStruct[index].height = atoi(e->Attribute("height"));
        }

        if (e->Attribute("alphaEnabled") != NULL)
        {
            xmlStruct[index].alphaEnabled = true;
        }

        index++;
    }

    std::vector<EntityXmlStruct> xmlStructVector(xmlStruct);
    return xmlStructVector;
}
void SVM_train() {//训练分类器	
	ftest[0].open("test1");
	ftest[1].open("test2");
	ftest[2].open("test3");
	ftest[3].open("test4");
	data[0] = 0;
	data[1] = 0;
	data[2] = 0;
	data[3] = 0;
	TiXmlDocument *tb = new TiXmlDocument("HITChineseDependencyTreeBank_train.xml");//训练数据
    tb->LoadFile();
	TiXmlElement *para = tb->RootElement(), *sent, *word;
	int parent, i, j, m, n;
	while (strcmp(para->Value(), "para") != 0)
		para = para->FirstChildElement();
	//逐句读入训练数据并parse
	for (sent = para->FirstChildElement(); sent; sent = sent->NextSiblingElement()) {
		inputSeq_len = 0;
		S_len = 0;
		for (word = sent->FirstChildElement(); word; word = word->NextSiblingElement()) {
			strcpy_s(inputSeq[inputSeq_len].str, word->Attribute("cont"));
			strcpy_s(inputSeq[inputSeq_len].pos, word->Attribute("pos"));
			inputSeq[inputSeq_len++].parent_position = atoi(word->Attribute("parent"));
		}
		train_sent_parse();
	}
	//设置svm参数,调用svm进行训练
	param.svm_type = C_SVC;
	param.kernel_type = RBF;//核函数
	param.degree = 3;
	param.coef0 = 0;
	param.gamma = 0.18;//核函数参数
	param.cache_size = 40;//缓冲块大小
	param.C = 1;//惩罚因子
	param.eps = 1e-4;//停止条件
	param.shrinking = 1;//训练过程使用压缩
	param.probability = 0;
	param.nu = 1;
	param.p = 0.5;
	//C-SVC权重相关
	param.nr_weight = 2;
	param.weight_label = (int *)malloc(2 * sizeof(int));
	param.weight_label[0] = +1;
	param.weight_label[1] = -1;
	param.weight = (double *)malloc(2 * sizeof(double));
	
	int train_data_num;//当前分类器的训练数据数目,即当前两类操作对应的特征向量数目之和
	char name[15], tmp[10];
	const char * error_msg;//提示信息

	//分别训练6个分类器
	for (m = 0; m < 4; m++) {
		for (n = m + 1; n < 4; n++) {
			//设置C_SVC权重
			if (data[n] > data[m]) {
				param.weight[0] = 1;
				param.weight[1] = data[m] * 1.0 / data[n];
			}
			else {
				param.weight[0] = data[n] * 1.0 / data[m];
				param.weight[1] = 1;
			}

			train_data_num = data[m] + data[n];
			//为训练数据(特征向量)分配内存
			_node = (struct svm_node **)malloc(train_data_num * sizeof(svm_node *));
			y = (double *)malloc(train_data_num * sizeof(double));
			ftest[m].seekp(0);
			ftest[n].seekp(0);
			for (i = 0; i < data[m]; i++) {
				y[i] = +1;//对应类别
				ftest[m] >> feature_num;
				x_space = (svm_node *)malloc((feature_num + 1) * sizeof(svm_node));
				for (j = 0; j < feature_num; j++) {
					ftest[m] >> x_space[j].index;
					x_space[j].value = 1;
				}
				x_space[feature_num].index = -1;
				_node[i] = x_space;
			}
			for (i = data[m]; i < train_data_num; i++) {
				y[i] = -1;//对应类别
				ftest[n] >> feature_num;
				x_space = (svm_node *)malloc((feature_num + 1) * sizeof(svm_node));
				for (j = 0; j < feature_num; j++) {
					ftest[n] >> x_space[j].index;
					x_space[j].value = 1;
				}
				x_space[feature_num].index = -1;
				_node[i] = x_space;
			}
			prob.l = train_data_num;
			prob.x = _node;
			prob.y = y;
			error_msg = svm_check_parameter(&prob, &param);//检查参数是否符合libsvm参数的要求格式
			if (error_msg) {
				cout << "error" << endl;
				exit(1);
			}
			strcpy_s(name, "train_model");
			itoa(++model_num, tmp, 10);
			strcat(name, tmp);
			svm_save_model(name, svm_train(&prob, &param));//训练并保存模型
			for (i = 0; i < train_data_num; i++)
				free(_node[i]);
			free(_node);
			free(y);
		}
	}
	free(param.weight_label);
	free(param.weight);
	ftest[0].close();
	ftest[1].close();
	ftest[2].close();
	ftest[3].close();
}
Esempio n. 9
0
/**
 * Parse the theme map if the mPathMap is empty, else use the mPathMap parsed before.
 */
void MTKThemeManager::parseThemeMapIfNeeded()
{
    if (mPathMap != NULL) {
        ALOGV("The path has already parsed.");
        return;
    }

    /* Load theme map xml file. */
    TiXmlDocument* pDoc = new TiXmlDocument(kThemeMapFile);
    if (pDoc == NULL) {
        ALOGE("Read theme map xml file failed!");
        return;
    }
    pDoc->LoadFile();

    /* Get the root node(thememap) and the first module child node.*/
    TiXmlElement *pRootElement = pDoc->RootElement();
    TiXmlElement *pFirstModuleElement = pRootElement->FirstChildElement(kThemeModuleName);
    ALOGV("Module element is %s, path = %s.", pFirstModuleElement->Value(), pFirstModuleElement->Attribute(kThemePathAttr));

    /* Get module node count to create the path map array.*/
    int moduleCnt = getChildNodeCount(kThemeModuleName, pRootElement, pFirstModuleElement);
    ALOGV("Total element count is %d.", moduleCnt);

    mPathMap = new ThemePathMap[moduleCnt];
    if (mPathMap == NULL) {
        ALOGE("Failed to allocate memory for theme path map.");
        return;
    }
    MTKThemeManager::mModuleCount = moduleCnt;

    TiXmlNode *pModuleNode = pFirstModuleElement;
    TiXmlNode *pItemNode = NULL;
    TiXmlNode *pFirstItemElement = NULL;
    int itemCnt = 0;
    int moduleIndex = 0;
    int tempIndex = 0;

    /* Parse the whole xml by module. */
    while (pModuleNode != NULL) {
        mPathMap[moduleIndex].path = ((TiXmlElement *)pModuleNode)->Attribute(kThemePathAttr);
        ALOGV("parseThemeMap while start moduleIndex = %d, pModuleNode = %d, path = %s.",
                moduleIndex, pModuleNode, mPathMap[moduleIndex].path);

        pFirstItemElement = pModuleNode->FirstChildElement(kThemeItemName);
        itemCnt = getChildNodeCount(kThemeItemName, pModuleNode, pFirstItemElement);
        mPathMap[moduleIndex].fileCount = itemCnt;
        if (itemCnt == 0) {
            ALOGD("There is no item in apk %s.", ((TiXmlElement *)pModuleNode)->Attribute(kThemePathAttr));
            mPathMap[moduleIndex].fileList = NULL;
            continue;
        }

        ThemeFileList *itemFileList = new ThemeFileList[itemCnt];
        if (itemFileList == NULL) {
            ALOGE("Failed to allocate memory for item file list array.");
            return;
        }

        pItemNode = pFirstItemElement;
        tempIndex = 0;
        /* Parse all items in the current module pModuleNode. */
        while (pItemNode != NULL) {
            itemFileList[tempIndex++].fileName = ((TiXmlElement *)pItemNode)->GetText();
            ALOGV("parseThemeMap pItemNode->GetText() = %s, itemFileList[tempIndex].fileName = %s.",
                    ((TiXmlElement *)pItemNode)->GetText(), itemFileList[tempIndex-1].fileName);
            pItemNode = (TiXmlElement *)pModuleNode->IterateChildren(kThemeItemName, pItemNode);
        }

        mPathMap[moduleIndex].fileList = itemFileList;
        ALOGV("parseThemeMap moduleIndex = %d, itemCnt = %d, mPathMap[moduleIndex].fileList = %d,"
                "itemFileList = %d, filename0 = %s, itemFileList filename0 = %s.",
                moduleIndex, itemCnt, mPathMap[moduleIndex].fileList, itemFileList,
                (mPathMap[moduleIndex].fileList)[0].fileName, itemFileList[0].fileName);
        moduleIndex++;

        pModuleNode = (TiXmlElement *)pRootElement->IterateChildren(kThemeModuleName, pModuleNode);
    }
    ALOGV("Theme path map parsed completely.");
}
Esempio n. 10
0
bool TamlXmlParser::accept( const char* pFilename, TamlVisitor& visitor )
{
    // Debug Profiling.
    PROFILE_SCOPE(TamlXmlParser_Accept);

    // Sanity!
    AssertFatal( pFilename != NULL, "Cannot parse a NULL filename." );

    // Expand the file-path.
    char filenameBuffer[1024];
    // TODO: Make sure this is a proper substitute for
    // Con::expandPath (T2D)
    Con::expandToolScriptFilename( filenameBuffer, sizeof(filenameBuffer), pFilename );
    /** T2D uses a custom version of TinyXML that supports FileStream.
      * We don't so we can't do this
      *
    FileStream stream;

#ifdef TORQUE_OS_ANDROID
    if (strlen(pFilename) > strlen(filenameBuffer)) {
    	strcpy(filenameBuffer, pFilename);
    }
#endif

    // File open for read?
    if ( !stream.open( filenameBuffer, Torque::FS::File::AccessMode::Read ) )
    {
        // No, so warn.
        Con::warnf("TamlXmlParser::parse() - Could not open filename '%s' for parse.", filenameBuffer );
        return false;
    }
    
     */

    TiXmlDocument xmlDocument;

    // Load document from stream.
    if ( !xmlDocument.LoadFile( filenameBuffer ) )
    {
        // Warn!
        Con::warnf("TamlXmlParser: Could not load Taml XML file from stream.");
        return false;
    }

    // Close the stream.
    // stream.close();

    // Set parsing filename.
    setParsingFilename( filenameBuffer );

    // Flag document as not dirty.
    mDocumentDirty = false;

    // Parse root element.
    parseElement( xmlDocument.RootElement(), visitor );

    // Reset parsing filename.
    setParsingFilename( StringTable->EmptyString() );

    // Finish if the document is not dirty.
    if ( !mDocumentDirty )
        return true;

    // Open for write?
    /*if ( !stream.open( filenameBuffer, FileStream::StreamWrite ) )
    {
        // No, so warn.
        Con::warnf("TamlXmlParser::parse() - Could not open filename '%s' for write.", filenameBuffer );
        return false;
    }*/

    // Yes, so save the document.
    if ( !xmlDocument.SaveFile( filenameBuffer ) )
    {
        // Warn!
        Con::warnf("TamlXmlParser: Could not save Taml XML document.");
        return false;
    }

    // Close the stream.
    //stream.close();

    return true;
}
Esempio n. 11
0
int main()
{
	//
	// We start with the 'demoStart' todo list. Process it. And
	// should hopefully end up with the todo list as illustrated.
	//
	const char* demoStart =
		"<?xml version=\"1.0\"  standalone='no' >\n"
		"<!-- Our to do list data -->"
		"<ToDo>\n"
		"<!-- Do I need a secure PDA? -->\n"
		"<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>"
		"<Item priority=\"2\" distance='none'> Do bills   </Item>"
		"<Item priority=\"2\" distance='far &amp; back'> Look for Evil Dinosaurs! </Item>"
		"</ToDo>";
		
	{

	#ifdef TIXML_USE_STL
		/*	What the todo list should look like after processing.
			In stream (no formatting) representation. */
		const char* demoEnd =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<!-- Our to do list data -->"
			"<ToDo>"
			"<!-- Do I need a secure PDA? -->"
			"<Item priority=\"2\" distance=\"close\">Go to the"
			"<bold>Toy store!"
			"</bold>"
			"</Item>"
			"<Item priority=\"1\" distance=\"far\">Talk to:"
			"<Meeting where=\"School\">"
			"<Attendee name=\"Marple\" position=\"teacher\" />"
			"<Attendee name=\"Voel\" position=\"counselor\" />"
			"</Meeting>"
			"<Meeting where=\"Lunch\" />"
			"</Item>"
			"<Item priority=\"2\" distance=\"here\">Do bills"
			"</Item>"
			"</ToDo>";
	#endif

		// The example parses from the character string (above):
		#if defined( WIN32 ) && defined( TUNE )
		_CrtMemCheckpoint( &startMemState );
		#endif	

		{
			// Write to a file and read it back, to check file I/O.

			TiXmlDocument doc( "demotest.xml" );
			doc.Parse( demoStart );

			if ( doc.Error() )
			{
				printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() );
				exit( 1 );
			}
			doc.SaveFile();
		}

		TiXmlDocument doc( "demotest.xml" );
		bool loadOkay = doc.LoadFile();

		if ( !loadOkay )
		{
			printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() );
			exit( 1 );
		}

		printf( "** Demo doc read from disk: ** \n\n" );
		printf( "** Printing via doc.Print **\n" );
		doc.Print( stdout );

		{
			printf( "** Printing via TiXmlPrinter **\n" );
			TiXmlPrinter printer;
			doc.Accept( &printer );
			fprintf( stdout, "%s", printer.CStr() );
		}
		#ifdef TIXML_USE_STL	
		{
			printf( "** Printing via operator<< **\n" );
			std::cout << doc;
		}
		#endif
		TiXmlNode* node = 0;
		TiXmlElement* todoElement = 0;
		TiXmlElement* itemElement = 0;


		// --------------------------------------------------------
		// An example of changing existing attributes, and removing
		// an element from the document.
		// --------------------------------------------------------

		// Get the "ToDo" element.
		// It is a child of the document, and can be selected by name.
		node = doc.FirstChild( "ToDo" );
		assert( node );
		todoElement = node->ToElement();
		assert( todoElement  );

		// Going to the toy store is now our second priority...
		// So set the "priority" attribute of the first item in the list.
		node = todoElement->FirstChildElement();	// This skips the "PDA" comment.
		assert( node );
		itemElement = node->ToElement();
		assert( itemElement  );
		itemElement->SetAttribute( "priority", 2 );

		// Change the distance to "doing bills" from
		// "none" to "here". It's the next sibling element.
		itemElement = itemElement->NextSiblingElement();
		assert( itemElement );
		itemElement->SetAttribute( "distance", "here" );

		// Remove the "Look for Evil Dinosaurs!" item.
		// It is 1 more sibling away. We ask the parent to remove
		// a particular child.
		itemElement = itemElement->NextSiblingElement();
		todoElement->RemoveChild( itemElement );

		itemElement = 0;

		// --------------------------------------------------------
		// What follows is an example of created elements and text
		// nodes and adding them to the document.
		// --------------------------------------------------------

		// Add some meetings.
		TiXmlElement item( "Item" );
		item.SetAttribute( "priority", "1" );
		item.SetAttribute( "distance", "far" );

		TiXmlText text( "Talk to:" );

		TiXmlElement meeting1( "Meeting" );
		meeting1.SetAttribute( "where", "School" );

		TiXmlElement meeting2( "Meeting" );
		meeting2.SetAttribute( "where", "Lunch" );

		TiXmlElement attendee1( "Attendee" );
		attendee1.SetAttribute( "name", "Marple" );
		attendee1.SetAttribute( "position", "teacher" );

		TiXmlElement attendee2( "Attendee" );
		attendee2.SetAttribute( "name", "Voel" );
		attendee2.SetAttribute( "position", "counselor" );

		// Assemble the nodes we've created:
		meeting1.InsertEndChild( attendee1 );
		meeting1.InsertEndChild( attendee2 );

		item.InsertEndChild( text );
		item.InsertEndChild( meeting1 );
		item.InsertEndChild( meeting2 );

		// And add the node to the existing list after the first child.
		node = todoElement->FirstChild( "Item" );
		assert( node );
		itemElement = node->ToElement();
		assert( itemElement );

		todoElement->InsertAfterChild( itemElement, item );

		printf( "\n** Demo doc processed: ** \n\n" );
		doc.Print( stdout );


	#ifdef TIXML_USE_STL
		printf( "** Demo doc processed to stream: ** \n\n" );
		cout << doc << endl << endl;
	#endif

		// --------------------------------------------------------
		// Different tests...do we have what we expect?
		// --------------------------------------------------------

		int count = 0;
		TiXmlElement*	element;

		//////////////////////////////////////////////////////

	#ifdef TIXML_USE_STL
		cout << "** Basic structure. **\n";
		ostringstream outputStream( ostringstream::out );
		outputStream << doc;
		XmlTest( "Output stream correct.",	string( demoEnd ).c_str(),
											outputStream.str().c_str(), true );
	#endif

		node = doc.RootElement();
		assert( node );
		XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) );
		XmlTest ( "Root element value is 'ToDo'.", "ToDo",  node->Value());

		node = node->FirstChild();
		XmlTest( "First child exists & is a comment.", true, ( node != 0 && node->ToComment() ) );
		node = node->NextSibling();
		XmlTest( "Sibling element exists & is an element.", true, ( node != 0 && node->ToElement() ) );
		XmlTest ( "Value is 'Item'.", "Item", node->Value() );

		node = node->FirstChild();
		XmlTest ( "First child exists.", true, ( node != 0 && node->ToText() ) );
		XmlTest ( "Value is 'Go to the'.", "Go to the", node->Value() );


		//////////////////////////////////////////////////////
		printf ("\n** Iterators. **\n");

		// Walk all the top level nodes of the document.
		count = 0;
		for( node = doc.FirstChild();
			 node;
			 node = node->NextSibling() )
		{
			count++;
		}
		XmlTest( "Top level nodes, using First / Next.", 3, count );

		count = 0;
		for( node = doc.LastChild();
			 node;
			 node = node->PreviousSibling() )
		{
			count++;
		}
		XmlTest( "Top level nodes, using Last / Previous.", 3, count );

		// Walk all the top level nodes of the document,
		// using a different syntax.
		count = 0;
		for( node = doc.IterateChildren( 0 );
			 node;
			 node = doc.IterateChildren( node ) )
		{
			count++;
		}
		XmlTest( "Top level nodes, using IterateChildren.", 3, count );

		// Walk all the elements in a node.
		count = 0;
		for( element = todoElement->FirstChildElement();
			 element;
			 element = element->NextSiblingElement() )
		{
			count++;
		}
		XmlTest( "Children of the 'ToDo' element, using First / Next.",
			3, count );

		// Walk all the elements in a node by value.
		count = 0;
		for( node = todoElement->FirstChild( "Item" );
			 node;
			 node = node->NextSibling( "Item" ) )
		{
			count++;
		}
		XmlTest( "'Item' children of the 'ToDo' element, using First/Next.", 3, count );

		count = 0;
		for( node = todoElement->LastChild( "Item" );
			 node;
			 node = node->PreviousSibling( "Item" ) )
		{
			count++;
		}
		XmlTest( "'Item' children of the 'ToDo' element, using Last/Previous.", 3, count );

	#ifdef TIXML_USE_STL
		{
			cout << "\n** Parsing. **\n";
			istringstream parse0( "<Element0 attribute0='foo0' attribute1= noquotes attribute2 = '&gt;' />" );
			TiXmlElement element0( "default" );
			parse0 >> element0;

			XmlTest ( "Element parsed, value is 'Element0'.", "Element0", element0.Value() );
			XmlTest ( "Reads attribute 'attribute0=\"foo0\"'.", "foo0", element0.Attribute( "attribute0" ));
			XmlTest ( "Reads incorrectly formatted 'attribute1=noquotes'.", "noquotes", element0.Attribute( "attribute1" ) );
			XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) );
		}
	#endif

		{
			const char* error =	"<?xml version=\"1.0\" standalone=\"no\" ?>\n"
								"<passages count=\"006\" formatversion=\"20020620\">\n"
								"    <wrong error>\n"
								"</passages>";

			TiXmlDocument docTest;
			docTest.Parse( error );
			XmlTest( "Error row", docTest.ErrorRow(), 3 );
			XmlTest( "Error column", docTest.ErrorCol(), 17 );
			//printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 );

		}

	#ifdef TIXML_USE_STL
		{
			//////////////////////////////////////////////////////
			cout << "\n** Streaming. **\n";

			// Round trip check: stream in, then stream back out to verify. The stream
			// out has already been checked, above. We use the output

			istringstream inputStringStream( outputStream.str() );
			TiXmlDocument document0;

			inputStringStream >> document0;

			ostringstream outputStream0( ostringstream::out );
			outputStream0 << document0;

			XmlTest( "Stream round trip correct.",	string( demoEnd ).c_str(), 
													outputStream0.str().c_str(), true );

			std::string str;
			str << document0;

			XmlTest( "String printing correct.", string( demoEnd ).c_str(), 
												 str.c_str(), true );
		}
	#endif
	}
	
	{
		const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";

		TiXmlDocument doc;
		doc.Parse( str );

		TiXmlElement* ele = doc.FirstChildElement();

		int iVal, result;
		double dVal;

		result = ele->QueryDoubleAttribute( "attr0", &dVal );
		XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS );
		XmlTest( "Query attribute: int as double", (int)dVal, 1 );
		result = ele->QueryDoubleAttribute( "attr1", &dVal );
		XmlTest( "Query attribute: double as double", (int)dVal, 2 );
		result = ele->QueryIntAttribute( "attr1", &iVal );
		XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS );
		XmlTest( "Query attribute: double as int", iVal, 2 );
		result = ele->QueryIntAttribute( "attr2", &iVal );
		XmlTest( "Query attribute: not a number", result, TIXML_WRONG_TYPE );
		result = ele->QueryIntAttribute( "bar", &iVal );
		XmlTest( "Query attribute: does not exist", result, TIXML_NO_ATTRIBUTE );
	}
	
	{
		const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
							"</room>";

		TiXmlDocument doc;
		doc.SetTabSize( 8 );
		doc.Parse( str );

		TiXmlHandle docHandle( &doc );
		TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );

		assert( docHandle.Node() );
		assert( roomHandle.Element() );

		TiXmlElement* room = roomHandle.Element();
		assert( room );
		TiXmlAttribute* doors = room->FirstAttribute();
		assert( doors );

		XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 );
		XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 );
		XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 );
		XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 );
	}
	
	{
		const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
							"  <!-- Silly example -->\n"
							"    <door wall='north'>A great door!</door>\n"
							"\t<door wall='east'/>"
							"</room>";

		TiXmlDocument doc;
		doc.Parse( str );

		TiXmlHandle docHandle( &doc );
		TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );
		TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild();
		TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild();
		TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 );
		TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 );

		assert( docHandle.Node() );
		assert( roomHandle.Element() );
		assert( commentHandle.Node() );
		assert( textHandle.Text() );
		assert( door0Handle.Element() );
		assert( door1Handle.Element() );

		TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration();
		assert( declaration );
		TiXmlElement* room = roomHandle.Element();
		assert( room );
		TiXmlAttribute* doors = room->FirstAttribute();
		assert( doors );
		TiXmlText* text = textHandle.Text();
		TiXmlComment* comment = commentHandle.Node()->ToComment();
		assert( comment );
		TiXmlElement* door0 = door0Handle.Element();
		TiXmlElement* door1 = door1Handle.Element();

		XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 );
		XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 );
		XmlTest( "Location tracking: room row", room->Row(), 1 );
		XmlTest( "Location tracking: room col", room->Column(), 45 );
		XmlTest( "Location tracking: doors row", doors->Row(), 1 );
		XmlTest( "Location tracking: doors col", doors->Column(), 51 );
		XmlTest( "Location tracking: Comment row", comment->Row(), 2 );
		XmlTest( "Location tracking: Comment col", comment->Column(), 3 );
		XmlTest( "Location tracking: text row", text->Row(), 3 ); 
		XmlTest( "Location tracking: text col", text->Column(), 24 );
		XmlTest( "Location tracking: door0 row", door0->Row(), 3 );
		XmlTest( "Location tracking: door0 col", door0->Column(), 5 );
		XmlTest( "Location tracking: door1 row", door1->Row(), 4 );
		XmlTest( "Location tracking: door1 col", door1->Column(), 5 );
	}


	// --------------------------------------------------------
	// UTF-8 testing. It is important to test:
	//	1. Making sure name, value, and text read correctly
	//	2. Row, Col functionality
	//	3. Correct output
	// --------------------------------------------------------
	printf ("\n** UTF-8 **\n");
	{
		TiXmlDocument doc( "utf8test.xml" );
		doc.LoadFile();
		if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) {
			printf( "WARNING: File 'utf8test.xml' not found.\n"
					"(Are you running the test from the wrong directory?)\n"
				    "Could not test UTF-8 functionality.\n" );
		}
		else
		{
			TiXmlHandle docH( &doc );
			// Get the attribute "value" from the "Russian" element and check it.
			TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element();
			const unsigned char correctValue[] = {	0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 
													0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 };

			XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true );
			XmlTest( "UTF-8: Russian value row.", 4, element->Row() );
			XmlTest( "UTF-8: Russian value column.", 5, element->Column() );

			const unsigned char russianElementName[] = {	0xd0U, 0xa0U, 0xd1U, 0x83U,
															0xd1U, 0x81U, 0xd1U, 0x81U,
															0xd0U, 0xbaU, 0xd0U, 0xb8U,
															0xd0U, 0xb9U, 0 };
			const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";

			TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text();
			XmlTest( "UTF-8: Browsing russian element name.",
					 russianText,
					 text->Value(),
					 true );
			XmlTest( "UTF-8: Russian element name row.", 7, text->Row() );
			XmlTest( "UTF-8: Russian element name column.", 47, text->Column() );

			TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration();
			XmlTest( "UTF-8: Declaration column.", 1, dec->Column() );
			XmlTest( "UTF-8: Document column.", 1, doc.Column() );

			// Now try for a round trip.
			doc.SaveFile( "utf8testout.xml" );

			// Check the round trip.
			char savedBuf[256];
			char verifyBuf[256];
			int okay = 1;

			FILE* saved  = fopen( "utf8testout.xml", "r" );
			FILE* verify = fopen( "utf8testverify.xml", "r" );
			if ( saved && verify )
			{
				while ( fgets( verifyBuf, 256, verify ) )
				{
					fgets( savedBuf, 256, saved );
					if ( strcmp( verifyBuf, savedBuf ) )
					{
						okay = 0;
						break;
					}
				}
				fclose( saved );
				fclose( verify );
			}
			XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay );

			// On most Western machines, this is an element that contains
			// the word "resume" with the correct accents, in a latin encoding.
			// It will be something else completely on non-wester machines,
			// which is why TinyXml is switching to UTF-8.
			const char latin[] = "<element>r\x82sum\x82</element>";

			TiXmlDocument latinDoc;
			latinDoc.Parse( latin, 0, TIXML_ENCODING_LEGACY );

			text = latinDoc.FirstChildElement()->FirstChild()->ToText();
			XmlTest( "Legacy encoding: Verify text element.", "r\x82sum\x82", text->Value() );
		}
	}		

	//////////////////////
	// Copy and assignment
	//////////////////////
	printf ("\n** Copy and Assignment **\n");
	{
		TiXmlElement element( "foo" );
		element.Parse( "<element name='value' />", 0, TIXML_ENCODING_UNKNOWN );

		TiXmlElement elementCopy( element );
		TiXmlElement elementAssign( "foo" );
		elementAssign.Parse( "<incorrect foo='bar'/>", 0, TIXML_ENCODING_UNKNOWN );
		elementAssign = element;

		XmlTest( "Copy/Assign: element copy #1.", "element", elementCopy.Value() );
		XmlTest( "Copy/Assign: element copy #2.", "value", elementCopy.Attribute( "name" ) );
		XmlTest( "Copy/Assign: element assign #1.", "element", elementAssign.Value() );
		XmlTest( "Copy/Assign: element assign #2.", "value", elementAssign.Attribute( "name" ) );
		XmlTest( "Copy/Assign: element assign #3.", true, ( 0 == elementAssign.Attribute( "foo" )) );

		TiXmlComment comment;
		comment.Parse( "<!--comment-->", 0, TIXML_ENCODING_UNKNOWN );
		TiXmlComment commentCopy( comment );
		TiXmlComment commentAssign;
		commentAssign = commentCopy;
		XmlTest( "Copy/Assign: comment copy.", "comment", commentCopy.Value() );
		XmlTest( "Copy/Assign: comment assign.", "comment", commentAssign.Value() );

		TiXmlUnknown unknown;
		unknown.Parse( "<[unknown]>", 0, TIXML_ENCODING_UNKNOWN );
		TiXmlUnknown unknownCopy( unknown );
		TiXmlUnknown unknownAssign;
		unknownAssign.Parse( "incorrect", 0, TIXML_ENCODING_UNKNOWN );
		unknownAssign = unknownCopy;
		XmlTest( "Copy/Assign: unknown copy.", "[unknown]", unknownCopy.Value() );
		XmlTest( "Copy/Assign: unknown assign.", "[unknown]", unknownAssign.Value() );
		
		TiXmlText text( "TextNode" );
		TiXmlText textCopy( text );
		TiXmlText textAssign( "incorrect" );
		textAssign = text;
		XmlTest( "Copy/Assign: text copy.", "TextNode", textCopy.Value() );
		XmlTest( "Copy/Assign: text assign.", "TextNode", textAssign.Value() );

		TiXmlDeclaration dec;
		dec.Parse( "<?xml version='1.0' encoding='UTF-8'?>", 0, TIXML_ENCODING_UNKNOWN );
		TiXmlDeclaration decCopy( dec );
		TiXmlDeclaration decAssign;
		decAssign = dec;

		XmlTest( "Copy/Assign: declaration copy.", "UTF-8", decCopy.Encoding() );
		XmlTest( "Copy/Assign: text assign.", "UTF-8", decAssign.Encoding() );

		TiXmlDocument doc;
		elementCopy.InsertEndChild( textCopy );
		doc.InsertEndChild( decAssign );
		doc.InsertEndChild( elementCopy );
		doc.InsertEndChild( unknownAssign );

		TiXmlDocument docCopy( doc );
		TiXmlDocument docAssign;
		docAssign = docCopy;

		#ifdef TIXML_USE_STL
		std::string original, copy, assign;
		original << doc;
		copy << docCopy;
		assign << docAssign;
		XmlTest( "Copy/Assign: document copy.", original.c_str(), copy.c_str(), true );
		XmlTest( "Copy/Assign: document assign.", original.c_str(), assign.c_str(), true );

		#endif
	}	

	//////////////////////////////////////////////////////
#ifdef TIXML_USE_STL
	printf ("\n** Parsing, no Condense Whitespace **\n");
	TiXmlBase::SetCondenseWhiteSpace( false );
	{
		istringstream parse1( "<start>This  is    \ntext</start>" );
		TiXmlElement text1( "text" );
		parse1 >> text1;

		XmlTest ( "Condense white space OFF.", "This  is    \ntext",
					text1.FirstChild()->Value(),
					true );
	}
	TiXmlBase::SetCondenseWhiteSpace( true );
#endif

	//////////////////////////////////////////////////////
	// GetText();
	{
		const char* str = "<foo>This is text</foo>";
		TiXmlDocument doc;
		doc.Parse( str );
		const TiXmlElement* element = doc.RootElement();

		XmlTest( "GetText() normal use.", "This is text", element->GetText() );

		str = "<foo><b>This is text</b></foo>";
		doc.Clear();
		doc.Parse( str );
		element = doc.RootElement();

		XmlTest( "GetText() contained element.", element->GetText() == 0, true );

		str = "<foo>This is <b>text</b></foo>";
		doc.Clear();
		TiXmlBase::SetCondenseWhiteSpace( false );
		doc.Parse( str );
		TiXmlBase::SetCondenseWhiteSpace( true );
		element = doc.RootElement();

		XmlTest( "GetText() partial.", "This is ", element->GetText() );
	}


	//////////////////////////////////////////////////////
	// CDATA
	{
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"I am > the rules!\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		TiXmlDocument doc;
		doc.Parse( str );
		doc.Print();

		XmlTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 true );

		#ifdef TIXML_USE_STL
		//cout << doc << '\n';

		doc.Clear();

		istringstream parse0( str );
		parse0 >> doc;
		//cout << doc << '\n';

		XmlTest( "CDATA stream.", doc.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 true );
		#endif

		TiXmlDocument doc1 = doc;
		//doc.Print();

		XmlTest( "CDATA copy.", doc1.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 true );
	}
	{
		// [ 1482728 ] Wrong wide char parsing
		char buf[256];
		buf[255] = 0;
		for( int i=0; i<255; ++i ) {
			buf[i] = (char)((i>=32) ? i : 32);
		}
		TIXML_STRING str( "<xmlElement><![CDATA[" );
		str += buf;
		str += "]]></xmlElement>";

		TiXmlDocument doc;
		doc.Parse( str.c_str() );

		TiXmlPrinter printer;
		printer.SetStreamPrinting();
		doc.Accept( &printer );

		XmlTest( "CDATA with all bytes #1.", str.c_str(), printer.CStr(), true );

		#ifdef TIXML_USE_STL
		doc.Clear();
		istringstream iss( printer.Str() );
		iss >> doc;
		std::string out;
		out << doc;
		XmlTest( "CDATA with all bytes #2.", out.c_str(), printer.CStr(), true );
		#endif
	}
	{
		// [ 1480107 ] Bug-fix for STL-streaming of CDATA that contains tags
		// CDATA streaming had a couple of bugs, that this tests for.
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"<b>I am > the rules!</b>\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		TiXmlDocument doc;
		doc.Parse( str );
		doc.Print();

		XmlTest( "CDATA parse. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 true );

		#ifdef TIXML_USE_STL

		doc.Clear();

		istringstream parse0( str );
		parse0 >> doc;

		XmlTest( "CDATA stream. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 true );
		#endif

		TiXmlDocument doc1 = doc;
		//doc.Print();

		XmlTest( "CDATA copy. [ 1480107 ]", doc1.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 true );
	}
	//////////////////////////////////////////////////////
	// Visit()



	//////////////////////////////////////////////////////
	printf( "\n** Fuzzing... **\n" );

	const int FUZZ_ITERATION = 300;

	// The only goal is not to crash on bad input.
	int len = (int) strlen( demoStart );
	for( int i=0; i<FUZZ_ITERATION; ++i ) 
	{
		char* demoCopy = new char[ len+1 ];
		strcpy( demoCopy, demoStart );

		demoCopy[ i%len ] = (char)((i+1)*3);
		demoCopy[ (i*7)%len ] = '>';
		demoCopy[ (i*11)%len ] = '<';

		TiXmlDocument xml;
		xml.Parse( demoCopy );

		delete [] demoCopy;
	}
	printf( "** Fuzzing Complete. **\n" );
	
	//////////////////////////////////////////////////////
	printf ("\n** Bug regression tests **\n");

	// InsertBeforeChild and InsertAfterChild causes crash.
	{
		TiXmlElement parent( "Parent" );
		TiXmlElement childText0( "childText0" );
		TiXmlElement childText1( "childText1" );
		TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
		TiXmlNode* childNode1 = parent.InsertBeforeChild( childNode0, childText1 );

		XmlTest( "Test InsertBeforeChild on empty node.", ( childNode1 == parent.FirstChild() ), true );
	}

	{
		// InsertBeforeChild and InsertAfterChild causes crash.
		TiXmlElement parent( "Parent" );
		TiXmlElement childText0( "childText0" );
		TiXmlElement childText1( "childText1" );
		TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
		TiXmlNode* childNode1 = parent.InsertAfterChild( childNode0, childText1 );

		XmlTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent.LastChild() ), true );
	}

	// Reports of missing constructors, irregular string problems.
	{
		// Missing constructor implementation. No test -- just compiles.
		TiXmlText text( "Missing" );

		#ifdef TIXML_USE_STL
			// Missing implementation:
			TiXmlDocument doc;
			string name = "missing";
			doc.LoadFile( name );

			TiXmlText textSTL( name );
		#else
			// verifying some basic string functions:
			TiXmlString a;
			TiXmlString b( "Hello" );
			TiXmlString c( "ooga" );

			c = " World!";
			a = b;
			a += c;
			a = a;

			XmlTest( "Basic TiXmlString test. ", "Hello World!", a.c_str() );
		#endif
 	}

	// Long filenames crashing STL version
	{
		TiXmlDocument doc( "midsummerNightsDreamWithAVeryLongFilenameToConfuseTheStringHandlingRoutines.xml" );
		bool loadOkay = doc.LoadFile();
		loadOkay = true;	// get rid of compiler warning.
		// Won't pass on non-dev systems. Just a "no crash" check.
		//XmlTest( "Long filename. ", true, loadOkay );
	}

	{
		// Entities not being written correctly.
		// From Lynn Allen

		const char* passages =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<passages count=\"006\" formatversion=\"20020620\">"
				"<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
				" It also has &lt;, &gt;, and &amp;, as well as a fake copyright &#xA9;.\"> </psg>"
			"</passages>";

		TiXmlDocument doc( "passages.xml" );
		doc.Parse( passages );
		TiXmlElement* psg = doc.RootElement()->FirstChildElement();
		const char* context = psg->Attribute( "context" );
		const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";

		XmlTest( "Entity transformation: read. ", expected, context, true );

		FILE* textfile = fopen( "textfile.txt", "w" );
		if ( textfile )
		{
			psg->Print( textfile, 0 );
			fclose( textfile );
		}
		textfile = fopen( "textfile.txt", "r" );
		assert( textfile );
		if ( textfile )
		{
			char buf[ 1024 ];
			fgets( buf, 1024, textfile );
			XmlTest( "Entity transformation: write. ",
					 "<psg context=\'Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
					 " It also has &lt;, &gt;, and &amp;, as well as a fake copyright \xC2\xA9.' />",
					 buf,
					 true );
		}
		fclose( textfile );
	}

    {
		FILE* textfile = fopen( "test5.xml", "w" );
		if ( textfile )
		{
            fputs("<?xml version='1.0'?><a.elem xmi.version='2.0'/>", textfile);
            fclose(textfile);

			TiXmlDocument doc;
            doc.LoadFile( "test5.xml" );
            XmlTest( "dot in element attributes and names", doc.Error(), 0);
		}
    }

	{
		FILE* textfile = fopen( "test6.xml", "w" );
		if ( textfile )
		{
            fputs("<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>", textfile );
            fclose(textfile);

            TiXmlDocument doc;
            bool result = doc.LoadFile( "test6.xml" );
            XmlTest( "Entity with one digit.", result, true );

			TiXmlText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
			XmlTest( "Entity with one digit.",
						text->Value(), "1.1 Start easy ignore fin thickness\n" );
		}
    }

	{
		// DOCTYPE not preserved (950171)
		// 
		const char* doctype =
			"<?xml version=\"1.0\" ?>"
			"<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
			"<!ELEMENT title (#PCDATA)>"
			"<!ELEMENT books (title,authors)>"
			"<element />";

		TiXmlDocument doc;
		doc.Parse( doctype );
		doc.SaveFile( "test7.xml" );
		doc.Clear();
		doc.LoadFile( "test7.xml" );
		
		TiXmlHandle docH( &doc );
		TiXmlUnknown* unknown = docH.Child( 1 ).Unknown();
		XmlTest( "Correct value of unknown.", "!DOCTYPE PLAY SYSTEM 'play.dtd'", unknown->Value() );
		#ifdef TIXML_USE_STL
		TiXmlNode* node = docH.Child( 2 ).Node();
		std::string str;
		str << (*node);
		XmlTest( "Correct streaming of unknown.", "<!ELEMENT title (#PCDATA)>", str.c_str() );
		#endif
	}

	{
		// [ 791411 ] Formatting bug
		// Comments do not stream out correctly.
		const char* doctype = 
			"<!-- Somewhat<evil> -->";
		TiXmlDocument doc;
		doc.Parse( doctype );

		TiXmlHandle docH( &doc );
		TiXmlComment* comment = docH.Child( 0 ).Node()->ToComment();

		XmlTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
		#ifdef TIXML_USE_STL
		std::string str;
		str << (*comment);
		XmlTest( "Comment streaming.", "<!-- Somewhat<evil> -->", str.c_str() );
		#endif
	}

	{
		// [ 870502 ] White space issues
		TiXmlDocument doc;
		TiXmlText* text;
		TiXmlHandle docH( &doc );
	
		const char* doctype0 = "<element> This has leading and trailing space </element>";
		const char* doctype1 = "<element>This has  internal space</element>";
		const char* doctype2 = "<element> This has leading, trailing, and  internal space </element>";

		TiXmlBase::SetCondenseWhiteSpace( false );
		doc.Clear();
		doc.Parse( doctype0 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space kept.", " This has leading and trailing space ", text->Value() );

		doc.Clear();
		doc.Parse( doctype1 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space kept.", "This has  internal space", text->Value() );

		doc.Clear();
		doc.Parse( doctype2 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space kept.", " This has leading, trailing, and  internal space ", text->Value() );

		TiXmlBase::SetCondenseWhiteSpace( true );
		doc.Clear();
		doc.Parse( doctype0 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space condensed.", "This has leading and trailing space", text->Value() );

		doc.Clear();
		doc.Parse( doctype1 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space condensed.", "This has internal space", text->Value() );

		doc.Clear();
		doc.Parse( doctype2 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space condensed.", "This has leading, trailing, and internal space", text->Value() );
	}

	{
		// Double attributes
		const char* doctype = "<element attr='red' attr='blue' />";

		TiXmlDocument doc;
		doc.Parse( doctype );
		
		XmlTest( "Parsing repeated attributes.", 0, (int)doc.Error() );	// not an  error to tinyxml
		XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) );
	}

	{
		// Embedded null in stream.
		const char* doctype = "<element att\0r='red' attr='blue' />";

		TiXmlDocument doc;
		doc.Parse( doctype );
		XmlTest( "Embedded null throws error.", true, doc.Error() );

		#ifdef TIXML_USE_STL
		istringstream strm( doctype );
		doc.Clear();
		doc.ClearError();
		strm >> doc;
		XmlTest( "Embedded null throws error.", true, doc.Error() );
		#endif
	}

    {
            // Legacy mode test. (This test may only pass on a western system)
            const char* str =
                        "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"
                        "<ä>"
                        "CöntäntßäöüÄÖÜ"
                        "</ä>";

            TiXmlDocument doc;
            doc.Parse( str );

            TiXmlHandle docHandle( &doc );
            TiXmlHandle aHandle = docHandle.FirstChildElement( "ä" );
            TiXmlHandle tHandle = aHandle.Child( 0 );
            assert( aHandle.Element() );
            assert( tHandle.Text() );
            XmlTest( "ISO-8859-1 Parsing.", "CöntäntßäöüÄÖÜ", tHandle.Text()->Value() );
    }

	{
		// Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717
		const char* str = "    ";
		TiXmlDocument doc;
		doc.Parse( str );
		XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() );
	}
	#ifndef TIXML_USE_STL
	{
		// String equality. [ 1006409 ] string operator==/!= no worky in all cases
		TiXmlString temp;
		XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true );

		TiXmlString    foo;
		TiXmlString    bar( "" );
		XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true );
	}

	#endif
	{
		// Bug [ 1195696 ] from marlonism
		TiXmlBase::SetCondenseWhiteSpace(false); 
		TiXmlDocument xml; 
		xml.Parse("<text><break/>This hangs</text>"); 
		XmlTest( "Test safe error return.", xml.Error(), false );
	}

	{
		// Bug [ 1243992 ] - another infinite loop
		TiXmlDocument doc;
		doc.SetCondenseWhiteSpace(false);
		doc.Parse("<p><pb></pb>test</p>");
	} 
	{
		// Low entities
		TiXmlDocument xml;
		xml.Parse( "<test>&#x0e;</test>" );
		const char result[] = { 0x0e, 0 };
		XmlTest( "Low entities.", xml.FirstChildElement()->GetText(), result );
		xml.Print();
	}
	{
		// Bug [ 1451649 ] Attribute values with trailing quotes not handled correctly
		TiXmlDocument xml;
		xml.Parse( "<foo attribute=bar\" />" );
		XmlTest( "Throw error with bad end quotes.", xml.Error(), true );
	}
	#ifdef TIXML_USE_STL
	{
		// Bug [ 1449463 ] Consider generic query
		TiXmlDocument xml;
		xml.Parse( "<foo bar='3' barStr='a string'/>" );

		TiXmlElement* ele = xml.FirstChildElement();
		double d;
		int i;
		float f;
		bool b;
		//std::string str;

		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &d ), TIXML_SUCCESS );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &i ), TIXML_SUCCESS );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &f ), TIXML_SUCCESS );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &b ), TIXML_WRONG_TYPE );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "nobar", &b ), TIXML_NO_ATTRIBUTE );
		//XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "barStr", &str ), TIXML_SUCCESS );

		XmlTest( "QueryValueAttribute", (d==3.0), true );
		XmlTest( "QueryValueAttribute", (i==3), true );
		XmlTest( "QueryValueAttribute", (f==3.0f), true );
		//XmlTest( "QueryValueAttribute", (str==std::string( "a string" )), true );
	}
	#endif

	#ifdef TIXML_USE_STL
	{
		// [ 1505267 ] redundant malloc in TiXmlElement::Attribute
		TiXmlDocument xml;
		xml.Parse( "<foo bar='3' />" );
		TiXmlElement* ele = xml.FirstChildElement();
		double d;
		int i;

		std::string bar = "bar";

		const std::string* atrrib = ele->Attribute( bar );
		ele->Attribute( bar, &d );
		ele->Attribute( bar, &i );

		XmlTest( "Attribute", atrrib->empty(), false );
		XmlTest( "Attribute", (d==3.0), true );
		XmlTest( "Attribute", (i==3), true );
	}
	#endif

	{
		// [ 1356059 ] Allow TiXMLDocument to only be at the top level
		TiXmlDocument xml, xml2;
		xml.InsertEndChild( xml2 );
		XmlTest( "Document only at top level.", xml.Error(), true );
		XmlTest( "Document only at top level.", xml.ErrorId(), TiXmlBase::TIXML_ERROR_DOCUMENT_TOP_ONLY );
	}

	{
		// [ 1663758 ] Failure to report error on bad XML
		TiXmlDocument xml;
		xml.Parse("<x>");
		XmlTest("Missing end tag at end of input", xml.Error(), true);
		xml.Parse("<x> ");
		XmlTest("Missing end tag with trailing whitespace", xml.Error(), true);
	} 

	{
		// [ 1635701 ] fail to parse files with a tag separated into two lines
		// I'm not sure this is a bug. Marked 'pending' for feedback.
		TiXmlDocument xml;
		xml.Parse( "<title><p>text</p\n><title>" );
		//xml.Print();
		//XmlTest( "Tag split by newline", xml.Error(), false );
	}

	#ifdef TIXML_USE_STL
	{
		// [ 1475201 ] TinyXML parses entities in comments
		TiXmlDocument xml;
		istringstream parse1( "<!-- declarations for <head> & <body> -->"
						      "<!-- far &amp; away -->" );
		parse1 >> xml;

		TiXmlNode* e0 = xml.FirstChild();
		TiXmlNode* e1 = e0->NextSibling();
		TiXmlComment* c0 = e0->ToComment();
		TiXmlComment* c1 = e1->ToComment();

		XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
		XmlTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
	}
	#endif

	{
		// [ 1475201 ] TinyXML parses entities in comments
		TiXmlDocument xml;
		xml.Parse("<!-- declarations for <head> & <body> -->"
				  "<!-- far &amp; away -->" );

		TiXmlNode* e0 = xml.FirstChild();
		TiXmlNode* e1 = e0->NextSibling();
		TiXmlComment* c0 = e0->ToComment();
		TiXmlComment* c1 = e1->ToComment();

		XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
		XmlTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
	}
	/*
	{
		TiXmlDocument xml;
		xml.Parse( "<tag>/</tag>" );
		xml.Print();
		xml.FirstChild()->Print( stdout, 0 );
		xml.FirstChild()->Type();
	}
	*/
	
	/*  1417717 experiment
	{
		TiXmlDocument xml;
		xml.Parse("<text>Dan & Tracie</text>");
		xml.Print(stdout);
	}
	{
		TiXmlDocument xml;
		xml.Parse("<text>Dan &foo; Tracie</text>");
		xml.Print(stdout);
	}
	*/
	#if defined( WIN32 ) && defined( TUNE )
	_CrtMemCheckpoint( &endMemState );
	//_CrtMemDumpStatistics( &endMemState );

	_CrtMemState diffMemState;
	_CrtMemDifference( &diffMemState, &startMemState, &endMemState );
	_CrtMemDumpStatistics( &diffMemState );
	#endif

	printf ("\nPass %d, Fail %d\n", gPass, gFail);
	return gFail;
}
Esempio n. 12
0
//*********************************************************************************************
bool CRTVDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
    CURL url(strPath);

    CStdString strRoot = strPath;
    URIUtils::AddSlashAtEnd(strRoot);

    // Host name is "*" so we try to discover all ReplayTVs.  This requires some trickery but works.
    if (url.GetHostName() == "*")
    {
        // Check to see whether the URL's path is blank or "Video"
        if (url.GetFileName() == "" || url.GetFileName() == "Video")
        {
            int iOldSize=items.Size();
            struct RTV * rtv = NULL;
            int numRTV;

            // Request that all ReplayTVs on the LAN identify themselves.  Each ReplayTV
            // is given 3000ms to respond to the request.  rtv_discovery returns an array
            // of structs containing the IP and friendly name of all ReplayTVs found on the LAN.
            // For some reason, DVArchive doesn't respond to this request (probably only responds
            // to requests from an IP address of a real ReplayTV).
            numRTV = rtv_discovery(&rtv, 3000);

            // Run through the array and add the ReplayTVs found as folders in XBMC.
            // We must add the IP of each ReplayTV as if it is a file name at the end of a the
            // auto-discover URL--e.g. rtv://*/192.168.1.100--because XBMC does not permit
            // dyamically added shares and will not play from them.  This little trickery is
            // the best workaround I could come up with.
            for (int i = 0; i < numRTV; i++)
            {
                CFileItemPtr pItem(new CFileItem(rtv[i].friendlyName));
                // This will keep the /Video or / and allow one to set up an auto ReplayTV
                // share of either type--simple file listing or ReplayGuide listing.
                pItem->m_strPath = strRoot + rtv[i].hostname;
                pItem->m_bIsFolder = true;
                pItem->SetLabelPreformated(true);
                items.Add(pItem);
            }
            free(rtv);
            return (items.Size()>iOldSize);
            // Else the URL's path should be an IP address of the ReplayTV
        }
        else
        {
            CStdString strURL, strRTV;
            int pos;

            // Isolate the IP from the URL and replace the "*" with the real IP
            // of the ReplayTV.  E.g., rtv://*/Video/192.168.1.100/ becomes
            // rtv://192.168.1.100/Video/ .  This trickery makes things work.
            strURL = strRoot.TrimRight('/');
            pos = strURL.ReverseFind('/');
            strRTV = strURL.Left(pos + 1);
            strRTV.Replace("*", strURL.Mid(pos + 1));
            CURL tmpURL(strRTV);

            // Force the newly constructed share into the right variables to
            // be further processed by the remainder of GetDirectory.
            url = tmpURL;
            strRoot = strRTV;
        }
    }

    // Allow for ReplayTVs on ports other than 80
    CStdString strHostAndPort;
    strHostAndPort = url.GetHostName();
    if (url.HasPort())
    {
        char buffer[10];
        strHostAndPort += ':';
        strHostAndPort += itoa(url.GetPort(), buffer, 10);
    }

    // No path given, list shows from ReplayGuide
    if (url.GetFileName() == "")
    {
        unsigned char * data = NULL;

        // Get the RTV guide data in XML format
        rtv_get_guide_xml(&data, strHostAndPort.c_str());

        // Begin parsing the XML data
        TiXmlDocument xmlDoc;
        xmlDoc.Parse( (const char *) data );
        if ( xmlDoc.Error() )
        {
            free(data);
            return false;
        }
        TiXmlElement* pRootElement = xmlDoc.RootElement();
        if (!pRootElement)
        {
            free(data);
            return false;
        }

        const TiXmlNode *pChild = pRootElement->FirstChild();
        while (pChild > 0)
        {
            CStdString strTagName = pChild->Value();

            if ( !strcmpi(strTagName.c_str(), "ITEM") )
            {
                const TiXmlNode *nameNode = pChild->FirstChild("DISPLAYNAME");
                const TiXmlNode *qualityNode = pChild->FirstChild("QUALITY");
                const TiXmlNode *recordedNode = pChild->FirstChild("RECORDED");
                const TiXmlNode *pathNode = pChild->FirstChild("PATH");
                const TiXmlNode *durationNode = pChild->FirstChild("DURATION");
                const TiXmlNode *sizeNode = pChild->FirstChild("SIZE");
                const TiXmlNode *atrbNode = pChild->FirstChild("ATTRIB");

                SYSTEMTIME dtDateTime;
                DWORD dwFileSize = 0;
                memset(&dtDateTime, 0, sizeof(dtDateTime));

                // DISPLAYNAME
                const char* szName = NULL;
                if (nameNode)
                {
                    szName = nameNode->FirstChild()->Value() ;
                }
                else
                {
                    // Something went wrong, the recording has no name
                    free(data);
                    return false;
                }

                // QUALITY
                const char* szQuality = NULL;
                if (qualityNode)
                {
                    szQuality = qualityNode->FirstChild()->Value() ;
                }

                // RECORDED
                if (recordedNode)
                {
                    CStdString strRecorded = recordedNode->FirstChild()->Value();
                    int iYear, iMonth, iDay;

                    iYear = atoi(strRecorded.Left(4).c_str());
                    iMonth = atoi(strRecorded.Mid(5, 2).c_str());
                    iDay = atoi(strRecorded.Mid(8, 2).c_str());
                    dtDateTime.wYear = iYear;
                    dtDateTime.wMonth = iMonth;
                    dtDateTime.wDay = iDay;

                    int iHour, iMin, iSec;
                    iHour = atoi(strRecorded.Mid(11, 2).c_str());
                    iMin = atoi(strRecorded.Mid(14, 2).c_str());
                    iSec = atoi(strRecorded.Mid(17, 2).c_str());
                    dtDateTime.wHour = iHour;
                    dtDateTime.wMinute = iMin;
                    dtDateTime.wSecond = iSec;
                }

                // PATH
                const char* szPath = NULL;
                if (pathNode)
                {
                    szPath = pathNode->FirstChild()->Value() ;
                }
                else
                {
                    // Something went wrong, the recording has no filename
                    free(data);
                    return false;
                }

                // DURATION
                const char* szDuration = NULL;
                if (durationNode)
                {
                    szDuration = durationNode->FirstChild()->Value() ;
                }

                // SIZE
                // NOTE: Size here is actually just duration in minutes because
                // filesize is not reported by the stripped down GuideParser I use
                if (sizeNode)
                {
                    dwFileSize = atol( sizeNode->FirstChild()->Value() );
                }

                // ATTRIB
                // NOTE: Not currently reported in the XML guide data, nor is it particularly
                // needed unless someone wants to add the ability to sub-divide the recordings
                // into categories, as on a real RTV.
                int attrib = 0;
                if (atrbNode)
                {
                    attrib = atoi( atrbNode->FirstChild()->Value() );
                }

                bool bIsFolder(false);
                if (attrib & FILE_ATTRIBUTE_DIRECTORY)
                    bIsFolder = true;

                CFileItemPtr pItem(new CFileItem(szName));
                pItem->m_dateTime=dtDateTime;
                pItem->m_strPath = strRoot + szPath;
                // Hack to show duration of show in minutes as KB in XMBC because
                // it doesn't currently permit showing duration in minutes.
                // E.g., a 30 minute show will show as 29.3 KB in XBMC.
                pItem->m_dwSize = dwFileSize * 1000;
                pItem->m_bIsFolder = bIsFolder;
                pItem->SetLabelPreformated(true);
                items.Add(pItem);
            }

            pChild = pChild->NextSibling();
        }

        free(data);

        // Path given (usually Video), list filenames only
    }
    else
    {

        unsigned char * data;
        char * p, * q;
        unsigned long status;

        // Return a listing of all files in the given path
        status = rtv_list_files(&data, strHostAndPort.c_str(), url.GetFileName().c_str());
        if (status == 0)
        {
            return false;
        }

        // Loop through the file list using pointers p and q, where p will point to the current
        // filename and q will point to the next filename
        p = (char *) data;
        while (p)
        {
            // Look for the end of the current line of the file listing
            q = strchr(p, '\n');
            // If found, replace the newline character with the NULL terminator
            if (q)
            {
                *q = '\0';
                // Increment q so that it points to the next filename
                q++;
                // *p should be the current null-terminated filename in the list
                if (*p)
                {
                    // Only display MPEG files in XBMC (but not circular.mpg, as that is the RTV
                    // video buffer and XBMC may cause problems if it tries to play it)
                    if (strstr(p, ".mpg") && !strstr(p, "circular"))
                    {
                        CFileItemPtr pItem(new CFileItem(p));
                        pItem->m_strPath = strRoot + p;
                        pItem->m_bIsFolder = false;
                        // The list returned by the RTV doesn't include file sizes, unfortunately
                        //pItem->m_dwSize = atol(szSize);
                        pItem->SetLabelPreformated(true);
                        items.Add(pItem);
                    }
                }
            }
            // Point p to the next filename in the list and loop
            p = q;
        }

        free(data);
    }

    return true;
}
Esempio n. 13
0
TEST(TestUtilities, GetAttribute)
{
  TiXmlDocument doc;
  doc.LoadFile("src/Utility/Test/refdata/getattribute.xml");
  ASSERT_TRUE(doc.RootElement());

  const char* bTrue[4]  = { "booltrue" , "boolone" , "boolon" , "boolyes" };
  const char* bFalse[4] = { "boolfalse", "boolzero", "booloff", "boolno"  };

  int i;
  for (i = 0; i < 4; i++) {
    const TiXmlElement* elem = doc.RootElement()->FirstChildElement(bTrue[i]);
    ASSERT_TRUE(elem != nullptr);
    bool b = false;
    ASSERT_TRUE(utl::getAttribute(elem, "bar", b));
    ASSERT_TRUE(b);
  }

  for (i = 0; i < 4; i++) {
    const TiXmlElement* elem = doc.RootElement()->FirstChildElement(bFalse[i]);
    ASSERT_TRUE(elem != nullptr);
    bool b = false;
    ASSERT_TRUE(utl::getAttribute(elem, "bar", b));
    ASSERT_FALSE(b);
  }

  const TiXmlElement* elem = doc.RootElement()->FirstChildElement("intval");
  ASSERT_TRUE(elem != nullptr);
  int val1 = 0;
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val1));
  ASSERT_EQ(val1, 1);
  size_t val2 = 0;
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val2));
  ASSERT_EQ(val2, 1U);

  elem = doc.RootElement()->FirstChildElement("realval");
  ASSERT_TRUE(elem != nullptr);
  double val3 = 0.0;
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val3));
  ASSERT_FLOAT_EQ(val3, 2.01);

  elem = doc.RootElement()->FirstChildElement("vecval1");
  ASSERT_TRUE(elem != nullptr);
  Vec3 val4;
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val4));
  ASSERT_FLOAT_EQ(val4.x, 1.2);
  ASSERT_FLOAT_EQ(val4.y, 0.0);
  ASSERT_FLOAT_EQ(val4.z, 0.0);
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val4, 2));
  ASSERT_FLOAT_EQ(val4.x, 1.2);
  ASSERT_FLOAT_EQ(val4.y, 1.2);
  ASSERT_FLOAT_EQ(val4.z, 0.0);
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val4, 3));
  ASSERT_FLOAT_EQ(val4.x, 1.2);
  ASSERT_FLOAT_EQ(val4.y, 1.2);
  ASSERT_FLOAT_EQ(val4.z, 1.2);

  elem = doc.RootElement()->FirstChildElement("vecval2");
  ASSERT_TRUE(elem != nullptr);
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val4));
  ASSERT_FLOAT_EQ(val4.x, 1.2);
  ASSERT_FLOAT_EQ(val4.y, 3.4);
  ASSERT_FLOAT_EQ(val4.z, 0.0);
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val4, 2));
  ASSERT_FLOAT_EQ(val4.x, 1.2);
  ASSERT_FLOAT_EQ(val4.y, 3.4);
  ASSERT_FLOAT_EQ(val4.z, 0.0);
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val4, 3));
  ASSERT_FLOAT_EQ(val4.x, 1.2);
  ASSERT_FLOAT_EQ(val4.y, 3.4);
  ASSERT_FLOAT_EQ(val4.z, 3.4);

  elem = doc.RootElement()->FirstChildElement("vecval3");
  ASSERT_TRUE(elem != nullptr);
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val4));
  ASSERT_FLOAT_EQ(val4.x, 1.2);
  ASSERT_FLOAT_EQ(val4.y, 3.4);
  ASSERT_FLOAT_EQ(val4.z, 5.6);
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val4, 2));
  ASSERT_FLOAT_EQ(val4.x, 1.2);
  ASSERT_FLOAT_EQ(val4.y, 3.4);
  ASSERT_FLOAT_EQ(val4.z, 0.0);
  ASSERT_TRUE(utl::getAttribute(elem, "bar", val4, 3));
  ASSERT_FLOAT_EQ(val4.x, 1.2);
  ASSERT_FLOAT_EQ(val4.y, 3.4);
  ASSERT_FLOAT_EQ(val4.z, 5.6);
}
Esempio n. 14
0
bool CSavestate::Deserialize(const std::string& path)
{
  Reset();

  TiXmlDocument xmlFile;
  if (!xmlFile.LoadFile(path))
  {
    CLog::Log(LOGERROR, "Failed to open %s: %s", path.c_str(), xmlFile.ErrorDesc());
    return false;
  }

  TiXmlElement* pElement = xmlFile.RootElement();
  if (!pElement || pElement->NoChildren() || pElement->ValueStr() != SAVESTATE_XML_ROOT)
  {
    CLog::Log(LOGERROR, "Can't find root <%s> tag", SAVESTATE_XML_ROOT);
    return false;
  }

  // Path
  if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_PATH, m_path))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_PATH);
    return false;
  }

  // Type
  std::string type;
  if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_TYPE, type))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_TYPE);
    return false;
  }
  m_type = CSavestateTranslator::TranslateType(type);
  if (m_type == SAVETYPE::UNKNOWN)
  {
    CLog::Log(LOGERROR, "Invalid savestate type: %s", type.c_str());
    return false;
  }

  // Slot
  if (m_type == SAVETYPE::SLOT)
  {
    if (!XMLUtils::GetInt(pElement, SAVESTATE_FIELD_SLOT, m_slot))
    {
      CLog::Log(LOGERROR, "Savestate has type \"%s\" but no <%s> element!", type.c_str(), SAVESTATE_FIELD_TYPE);
      return false;
    }
    if (m_slot < 0)
    {
      CLog::Log(LOGERROR, "Invalid savestate slot: %d", m_slot);
      return false;
    }
  }

  // Label (optional)
  XMLUtils::GetString(pElement, SAVESTATE_FIELD_LABEL, m_label);

  // Size
  long size;
  if (!XMLUtils::GetLong(pElement, SAVESTATE_FIELD_SIZE, size))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_SIZE);
    return false;
  }
  if (size < 0)
  {
    CLog::Log(LOGERROR, "Invalid savestate size: %ld", size);
    return false;
  }
  m_size = size;

  // Game client
  if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_GAMECLIENT, m_gameClient))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_GAMECLIENT);
    return false;
  }

  // Game path
  if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_GAME_PATH, m_gamePath))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_GAME_PATH);
    return false;
  }

  // Game CRC
  if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_GAME_CRC, m_gameCRC))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_GAME_CRC);
    return false;
  }

  // Playtime (frames)
  long playtimeFrames;
  if (!XMLUtils::GetLong(pElement, SAVESTATE_FIELD_FRAMES, playtimeFrames))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_FRAMES);
    return false;
  }
  if (playtimeFrames < 0)
  {
    CLog::Log(LOGERROR, "Invalid savestate frame count: %ld", playtimeFrames);
    return false;
  }
  m_size = playtimeFrames;

  // Playtime (wall clock)
  float playtimeWallClock;
  if (!XMLUtils::GetFloat(pElement, SAVESTATE_FIELD_WALLCLOCK, playtimeWallClock))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_WALLCLOCK);
    return false;
  }
  m_playtimeWallClock = playtimeWallClock;

  // Timestamp
  std::string timestamp;
  if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_TIMESTAMP, timestamp))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_TIMESTAMP);
    return false;
  }
  if (!m_timestamp.SetFromDBDateTime(timestamp))
  {
    CLog::Log(LOGERROR, "Invalid savestate timestamp: %s", timestamp.c_str());
    return false;
  }

  // Thumbnail
  if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_THUMBNAIL, m_thumbnail))
  {
    CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_THUMBNAIL);
    return false;
  }

  return true;
}
Esempio n. 15
0
void readSchoolXml() 
{
	using namespace std;

	const char *xmlFile = "conf/school.xml";

	TiXmlDocument doc;
	if (!doc.LoadFile(xmlFile))
	{
		cout << "Load xml file failed.\t" << xmlFile << endl;
		return;
	}

	cout << "Load xml file OK." << endl;
	
	TiXmlDeclaration *decl = doc.FirstChild()->ToDeclaration();

	if (!decl)
	{
		cout << "decl is null.\n" << endl;
		return;
	}
	
	cout <<  decl->Encoding();
	cout <<  decl->Version();
	cout <<  decl->Standalone() << endl;



	TiXmlHandle docHandle(&doc);
	TiXmlElement *child 
		= docHandle.FirstChild("School").FirstChild("Class").Child("Student", 0).ToElement();

	for ( ; child != NULL; child = child->NextSiblingElement())
	{
		TiXmlAttribute *attr = child->FirstAttribute();

		for (; attr != NULL; attr = attr->Next())
		{
			cout << attr->Name() << " : " << attr->Value() << endl;
		}
		
		TiXmlElement *ct = child->FirstChildElement();
		for (; ct != NULL; ct = ct->NextSiblingElement())
		{
			char buf[1024] = {0};
			u2g(ct->GetText(), strlen(ct->GetText()), buf, sizeof(buf));
			cout << ct->Value() << " : " << buf << endl;
		}
		cout << "=====================================" << endl;
	}
	
	TiXmlElement *schl = doc.RootElement();
	const char *value_t =schl->Attribute("name");
	
	char buf[1024] = {0};
	if ( u2g(value_t, strlen(value_t), buf, sizeof(buf)) == -1) {
		return;
	}
	cout << "Root Element value: " << buf << endl;
	schl->RemoveAttribute("name");
	schl->SetValue("NewSchool");


	cout << "Save file: " << (doc.SaveFile("conf/new.xml") ? "Ok" : "Failed") << endl;

return ;
	TiXmlElement *rootElement = doc.RootElement();
	TiXmlElement *classElement = rootElement->FirstChildElement();
	TiXmlElement *studentElement = classElement->FirstChildElement();


	// N 个 Student 节点
	for ( ; studentElement!= NULL; studentElement = studentElement->NextSiblingElement()) 
	{
		// 获得student
		TiXmlAttribute *stuAttribute = studentElement->FirstAttribute();
		for (; stuAttribute != NULL; stuAttribute = stuAttribute->Next()) 
		{
			cout << stuAttribute->Name() << " : " << stuAttribute->Value() << endl;
		}

		// 获得student的第一个联系方式 
		TiXmlElement *contact = studentElement->FirstChildElement();
		for (; contact != NULL; contact = contact->NextSiblingElement())
		{
			const char *text = contact->GetText();
			char buf[1024] = {0};
			if ( u2g(text, strlen(text), buf, sizeof(buf)) == -1) {
				continue;
			}
			cout << contact->Value() << " : " << buf << endl; 
		}
	}
}
Esempio n. 16
0
int NetClient::receiver (void* instance){ /** CRITICA **/
	NetClient* pNetClient = (NetClient *) instance;

	UDPpacket* in_packet;
	TiXmlDocument* xmlcontainer = new TiXmlDocument();
	TiXmlElement* net_msg;
	string msg_type;
	int msg_id;
	string plyName;
	char* data = NULL;


	in_packet = SDLNet_AllocPacket(NetControl::M_PACKET_SIZE);

	while (!pNetClient->m_stopClient){
		pNetClient->m_threadReceiverReady = true;
		while(!SDLNet_UDP_Recv(pNetClient->m_sock, in_packet)){
			pNetClient->checkServerTimeout();
			
			if (pNetClient->m_stopClient)
				break;
			
			SDL_Delay(NetControl::M_RECEIVER_DELAY); //  RECEIVER_DELAY/1000 seconds
		}

		if (pNetClient->m_stopClient)
			break;
			
			pNetClient->m_lastServerMsg = SDL_GetTicks();
	
		data = new char[in_packet->len];
		memcpy (data, in_packet->data, in_packet->len);
	
		xmlcontainer->Clear();
		xmlcontainer->Parse( data );
		net_msg = xmlcontainer->RootElement();

		if ( data ) 
			delete [] data;
	
		if( m_pNetClient->handleMessage(net_msg) ) continue;
		
		msg_type = net_msg->Attribute( "TYPE" );
		net_msg->QueryIntAttribute( "ID", &msg_id );
	
		if ( net_msg->Attribute( "PLYNAME" ) )
			plyName = net_msg->Attribute( "PLYNAME" );
		else
			plyName = "unnamed";
	
		NetControl::waitForSync();
		//SDL_SemWait (NetControl::m_pSemNetAndLocalSync);
		SDL_SemWait (pNetClient->m_pSemEntityValues); /** comecando a mexer nas entidades... travar acesso **/
	
	
		if (msg_type == "ENT"){ //nessa situacao, supoe-se que o cliente ja saiba da existencia
			//da origem dessa mensagem, portanto o lugar no vetor ja existe!
			EntityFactory* pEntityFactory = EntityFactory::getInstance();
	
			pNetClient->checkOtherPlayer( msg_id , plyName);
	
			IEntity* newEntity = pEntityFactory->loadEntity( net_msg );
	
			int ent_id;
			net_msg->QueryIntAttribute( "ENTID", &ent_id );
	
			while (pNetClient->m_vOthersEntities[msg_id].size() <= ent_id){
				pNetClient->m_vOthersEntities[msg_id].push_back( NULL );
			}
	
			pNetClient->m_vOthersEntities[msg_id][ent_id] = newEntity;
		}
	
	
		if (msg_type == "RMENT"){
			EntityFactory* pEntityFactory = EntityFactory::getInstance();
			string uniqueId = net_msg->Attribute( "UNIQUEID" );
			int entId;
			net_msg->Attribute( "ENTID" , &entId );
			
			pNetClient->m_vOthersEntities[msg_id][entId] = NULL;
	
			pEntityFactory->rmEntity( pEntityFactory->getEntity( uniqueId ) );
		}
	
	
		if (msg_type == "LGNGRA"){ //arranja um lugar no vetor de outras entidades para o novo vizinho
			pNetClient->checkOtherPlayer( msg_id , plyName );
		}
	
	
		if (msg_type == "BYE"){ //aqui supoe-se que ja exista a posicao msg_id no vector
			pNetClient->rmOtherPlayer( msg_id );
		}
	
	
		if (msg_type == "TIMEOUT_BYE"){ //o servidor informou que o cliente (msg_id) desconectou-se por timeout
			pNetClient->rmOtherPlayer( msg_id );
		}
	
	
		if (msg_type == "CUS"){ //mensagem personalizada
			NetCustomMessage* cus_msg = new NetCustomMessage(net_msg);
			//adiconar *net_msg a um vector (ou outro container) para uso futuro pelo usuario
			pNetClient->m_qCustomMessageQueue.push( cus_msg );
		}
	
	
		if (msg_type == "SERVER_CLOSED"){
			pNetClient->stopEverything();
			break;
		}
			
			
		if (msg_type == "SERVER_PING"){
			pNetClient->answerPing();
		}
	
	
		SDL_SemPost (pNetClient->m_pSemEntityValues); /** terminou de mexer nas entidades... liberar acesso **/
		NetControl::postForSync();
		//SDL_SemPost (NetControl::m_pSemNetAndLocalSync);
	}
	
	SDLNet_FreePacket( in_packet );
	if ( xmlcontainer ) 
		delete ( xmlcontainer );

	return 0;
}
Esempio n. 17
0
	bool CConfiger::LoadShopList( const char *file )
	{
		CRFile *prfile = rfOpen( file );
		if( prfile == NULL )
		{
			PutoutLog( LOG_FILE, LT_ERROR, "Load file %s failed.", file );
			return false;
		}

		TiXmlDocument doc;
		if( !doc.LoadData( prfile->GetData(), prfile->GetDatalen() ) )
		{
			PutoutLog( LOG_FILE, LT_ERROR, "Parse %s failed, invalid xml format.", file );
			rfClose( prfile );
			return false;
		}
		rfClose( prfile );
		TiXmlElement *root = doc.RootElement();
		{
			// global config
			TiXmlElement *node = root->FirstChildElement( "Global" );
			QUERY_NUM( "goods_update_interval", m_GlobalCfg.uGoodsUpdateInter, node, unsigned long );
			QUERY_NUM( "buy_count", m_GlobalCfg.lBuyCount, node, long );
			QUERY_NUM( "enable", m_GlobalCfg.lEnable, node, long );
			QUERY_NUM( "player_buy_count", m_GlobalCfg.lPlayerBuyCount, node, long );

			char strCoinGoods[64];
			QUERY_STR( "coin_goods", strCoinGoods, node );
			m_GlobalCfg.lCoinGoodsIndex = CGoodsFactory::QueryGoodsIDByOriginalName( strCoinGoods );
		}
		{
			// shop list
			TiXmlElement *shoplist_node = root->FirstChildElement( "ShopList" );
			for( TiXmlElement *shop_node = shoplist_node->FirstChildElement();
				shop_node != NULL; shop_node = shop_node->NextSiblingElement() )
			{
				long id;
				QUERY_NUM( "id", id, shop_node, long );
				if( m_ShopTable.find( id ) != m_ShopTable.end() )
				{
					// more than 1 shop with the same id, ignore it.
					PutoutLog( LOG_FILE, LT_WARNING, "More than 1 shop with the same id [%d].", id );
					continue;
				}
				Shop shop;
				QUERY_STR( "npc_orig_name", shop.npcOrigName, shop_node );
				SellGoodsListT *pSellGoodsList = new SellGoodsListT();
				shop.SellList = pSellGoodsList;
				for( TiXmlElement *goods_node = shop_node->FirstChildElement();
					goods_node != NULL; goods_node = goods_node->NextSiblingElement() )
				{
					SellGoods goods;
					char strOrigName[64];
					QUERY_STR( "orig_name", strOrigName, goods_node );
					goods.lIndex = CGoodsFactory::QueryGoodsIDByOriginalName( strOrigName );
					pSellGoodsList->push_back( goods );
				}
				m_ShopTable.insert( std::make_pair( id, shop ) );
			}
		}
		return true;
	}
Esempio n. 18
0
int NetClient::connectToServer(string ip_address, unsigned short port){
	if (m_isConnected) return m_myNetId;

	if (!m_clientIsOn){
		cerr << "ERRO: eh necessario startar o client antes de conectar-se a um servidor" << endl;
		return -1;
	}

	TiXmlDocument* xmlcontainer = new TiXmlDocument();
	TiXmlElement* net_msg = new TiXmlElement("InGENetMsg");
	TiXmlElement* server_answer;
	string msg_string;
	string msg_type;
	UDPpacket* out_packet = NULL;
	UDPpacket* in_packet = NULL;
	char* data = NULL;
	int waitForAnswerRetries = NetControl::M_SERVER_TIMEOUT / NetControl::M_LOGIN_RETRY_DELAY; //TIMEOUT

	SDLNet_ResolveHost(&m_serverAddress, ip_address.c_str(), port);
	
// 	cout << "Client: tentando conectar no ip " << ip_address << ", na porta " << port << "." << endl;

	out_packet = SDLNet_AllocPacket(NetControl::M_PACKET_SIZE);

	net_msg->SetAttribute( "ID", -1 );
	net_msg->SetAttribute( "PLYNAME", m_myNetName );
	net_msg->SetAttribute( "TYPE", "LGNREQ" );

	msg_string << *net_msg;

	memcpy (out_packet->data, msg_string.c_str(), msg_string.size() + 1);
	out_packet->len = msg_string.size() + 1;
	out_packet->address = m_serverAddress;

	SDLNet_UDP_Send(m_sock,-1,out_packet);


	in_packet=SDLNet_AllocPacket(NetControl::M_PACKET_SIZE);
	
// 	cout << "Client: esperando por resposta do servidor." << endl;

	while(!SDLNet_UDP_Recv(m_sock, in_packet)){
		if (waitForAnswerRetries <= 0) 
			return -1;
		
		waitForAnswerRetries--;
		SDL_Delay(NetControl::M_LOGIN_RETRY_DELAY); // LOGIN_RETRY_DELAY/1000 second
	}

	data = new char[in_packet->len];
	memcpy (data, in_packet->data, in_packet->len);

	xmlcontainer->Clear();
	xmlcontainer->Parse( data );

	server_answer = xmlcontainer->RootElement();


	msg_type = server_answer->Attribute( "TYPE" );

	int returnedId;

	if ( msg_type == "LGNGRA" ){
		server_answer->QueryIntAttribute( "ID", &m_myNetId );
		m_isConnected = true;
		returnedId = m_myNetId;
		m_currentScene = server_answer->Attribute( "SCENE" );
	}
	else
		returnedId = -1;

	SDLNet_FreePacket(out_packet);
	SDLNet_FreePacket(in_packet);
	if (xmlcontainer)
		delete (xmlcontainer);
	if (net_msg)
		delete (net_msg);
    if(data)
		delete [] data;

	NetClient* pNetClient = getInstance();
	atexit(disconnectFromServerAtExit);

	return returnedId;

}
Esempio n. 19
0
void GUIFontManager::LoadFonts(const CStdString& strFontSet)
{
  TiXmlDocument xmlDoc;
  if (!OpenFontFile(xmlDoc))
    return;

  TiXmlElement* pRootElement = xmlDoc.RootElement();
  const TiXmlNode *pChild = pRootElement->FirstChild();

  // If there are no fontset's defined in the XML (old skin format) run in backward compatibility
  // and ignore the fontset request
  CStdString strValue = pChild->Value();
  if (strValue == "fontset")
  {
    CStdString foundTTF;
    while (pChild)
    {
      strValue = pChild->Value();
      if (strValue == "fontset")
      {
        const char* idAttr = ((TiXmlElement*) pChild)->Attribute("id");

        const char* unicodeAttr = ((TiXmlElement*) pChild)->Attribute("unicode");

        if (foundTTF.IsEmpty() && idAttr != NULL && unicodeAttr != NULL && stricmp(unicodeAttr, "true") == 0)
          foundTTF = idAttr;

        // Check if this is the fontset that we want
        if (idAttr != NULL && stricmp(strFontSet.c_str(), idAttr) == 0)
        {
          m_fontsetUnicode=false;
          // Check if this is the a ttf fontset
          if (unicodeAttr != NULL && stricmp(unicodeAttr, "true") == 0)
            m_fontsetUnicode=true;

          if (m_fontsetUnicode)
          {
            LoadFonts(pChild->FirstChild());
            break;
          }
        }

      }

      pChild = pChild->NextSibling();
    }

    // If no fontset was loaded
    if (pChild == NULL)
    {
      CLog::Log(LOGWARNING, "file doesnt have <fontset> with name '%s', defaulting to first fontset", strFontSet.c_str());
      if (!foundTTF.IsEmpty())
        LoadFonts(foundTTF);
    }
  }
  else
  {
    CLog::Log(LOGERROR, "file doesnt have <fontset> in <fonts>, but rather %s", strValue.c_str());
    return ;
  }
}
void Template::LoadFromFile(const std::string &path)
{
    TiXmlDocument *doc = new TiXmlDocument(path.c_str());
    doc->LoadFile(path.c_str());

    TiXmlElement *descEle = doc->RootElement()->FirstChildElement("Description");
    TiXmlElement *ele = doc->RootElement()->FirstChildElement("Keyframes");
    TiXmlElement *descriptionsEle = doc->RootElement()->FirstChildElement("BonesDescriptions");

    m_keyFrames.clear();
    m_boneDescriptions.clear();

    float period = 0;
    int keyframesTypes = AngleKeyFrame|LengthKeyFrame|PositionXKeyFrame|PositionYKeyFrame|ImageKeyFrame;
    ele->QueryFloatAttribute("period", &period);
    ele->QueryIntAttribute("types", &keyframesTypes);
    m_period = period;
    m_types = keyframesTypes;
    m_description = descEle != 0 ? std::string(descEle->GetText()) : "";

    //Query all BoneAnimation
    TiXmlNode *child;
    for( child = ele->FirstChild("Bone"); child; child = child->NextSibling("Bone") )
    {
        if(child->ToElement())
        {
            m_keyFrames[std::string(child->ToElement()->Attribute("name"))] = BoneAnimation();
            BoneAnimation *currentBoneAnim = &m_keyFrames[std::string(child->ToElement()->Attribute("name"))];
            currentBoneAnim->keyFrames.clear();

            //Query all frames types
            TiXmlNode *keyframetypes;
            for( keyframetypes = child->ToElement()->FirstChild("Type"); keyframetypes; keyframetypes = keyframetypes->NextSibling() )
            {
                int typeInt = 0;
                keyframetypes->ToElement()->QueryIntAttribute("type", &typeInt);

                KeyFrameType type = static_cast<KeyFrameType>(typeInt);

                //Query all KeyFrames
                TiXmlNode *keyframe;
                for( keyframe = keyframetypes->ToElement()->FirstChild("Keyframe"); keyframe; keyframe = keyframe->NextSibling() )
                {
                    if(keyframe->ToElement())
                    {
                        KeyFrame timefloat;
                        keyframe->ToElement()->QueryFloatAttribute("time", &timefloat.time);
                        keyframe->ToElement()->QueryFloatAttribute("value", &timefloat.value);
                        if(keyframe->ToElement()->Attribute("valueStr") != 0)
                            timefloat.valueStr = std::string(keyframe->ToElement()->Attribute("valueStr"));

                        if(keyframe->ToElement()->Attribute("interpolation"))
                            timefloat.interpolation = std::string(keyframe->ToElement()->Attribute("interpolation"));
                        else
                            timefloat.interpolation = "Linear";

                        currentBoneAnim->keyFrames[type].push_back(timefloat);
                    }
                }
            }
        }
    }

    TiXmlNode *descrBoneEle;
    for( descrBoneEle = descriptionsEle->FirstChild("BoneDescription"); descrBoneEle; descrBoneEle = descrBoneEle->NextSibling("BoneDescription") )
    {
        if(descrBoneEle->ToElement())
        {
            std::pair<std::string, std::string> descripPair(std::string(descrBoneEle->ToElement()->Attribute("bone")),
                                                            std::string(descrBoneEle->ToElement()->Attribute("description")));

            m_boneDescriptions.push_back(descripPair);
        }
    }
}
void ClientTerrainFunctionsClass::RegisterTerrainFromXMLString( const char *XMLString )
{
    TiXmlDocument IPC;
    IPC.Parse( XMLString );
    RegisterTerrainFromXML( IPC.RootElement() );
}
Level* LevelParser::parseLevel(const char *levelFile)
{
    // create a tinyXML document and load the map xml
    TiXmlDocument levelDocument;
    levelDocument.LoadFile(levelFile);
    
    // create the level object
    Level* pLevel = new Level();
    
    // get the root node and display some values
    TiXmlElement* pRoot = levelDocument.RootElement();
    
    std::cout << "Loading level:\n" << "Version: " << pRoot->Attribute("version") << "\n";
    std::cout << "Width:" << pRoot->Attribute("width") << " - Height:" << pRoot->Attribute("height") << "\n";
    std::cout << "Tile Width:" << pRoot->Attribute("tilewidth") << " - Tile Height:" << pRoot->Attribute("tileheight") << "\n";
    
    pRoot->Attribute("tilewidth", &m_tileSize);
    pRoot->Attribute("width", &m_width);
    pRoot->Attribute("height", &m_height);
    
    //we know that properties is the first child of the root
    TiXmlElement* pProperties = pRoot->FirstChildElement();
    
    // we must parse the textures needed for this level, which have been added to properties
    for(TiXmlElement* e = pProperties->FirstChildElement(); e != NULL; e = e->NextSiblingElement())
    {
        if(e->Value() == std::string("property"))
        {
            parseTextures(e);
        }
    }
    
    // we must now parse the tilesets
    for(TiXmlElement* e = pRoot->FirstChildElement(); e != NULL; e = e->NextSiblingElement())
    {
        if(e->Value() == std::string("tileset"))
        {
            parseTilesets(e, pLevel->getTilesets());
        }
    }
    
    // parse any object layers
    for(TiXmlElement* e = pRoot->FirstChildElement(); e != NULL; e = e->NextSiblingElement())
    {
        if(e->Value() == std::string("objectgroup") || e->Value() == std::string("layer"))
        {
            if(e->FirstChildElement()->Value() == std::string("object"))
            {
                parseObjectLayer(e, pLevel->getLayers(), pLevel);
            }
            else if(e->FirstChildElement()->Value() == std::string("data") ||
                    (e->FirstChildElement()->NextSiblingElement() != 0 && e->FirstChildElement()->NextSiblingElement()->Value() == std::string("data")))
            {
                parseTileLayer(e, pLevel->getLayers(), pLevel->getTilesets(), pLevel->getCollisionLayers());
            }
        }
    }
    
    // set the players collision layer
   // pLevel->getPlayer()->setCollisionLayers(pLevel->getCollisionLayers());
    
    return pLevel;
}
bool CGUIWindow::Load(TiXmlDocument &xmlDoc)
{
  TiXmlElement* pRootElement = xmlDoc.RootElement();
  if (strcmpi(pRootElement->Value(), "window"))
  {
    CLog::Log(LOGERROR, "file : XML file doesnt contain <window>");
    return false;
  }

  // set the scaling resolution so that any control creation or initialisation can
  // be done with respect to the correct aspect ratio
  g_graphicsContext.SetScalingResolution(m_coordsRes, m_needsScaling);

  // Resolve any includes that may be present
  g_SkinInfo->ResolveIncludes(pRootElement);
  // now load in the skin file
  SetDefaults();

  CGUIControlFactory::GetInfoColor(pRootElement, "backgroundcolor", m_clearBackground);
  CGUIControlFactory::GetMultipleString(pRootElement, "onload", m_loadActions);
  CGUIControlFactory::GetMultipleString(pRootElement, "onunload", m_unloadActions);
  CGUIControlFactory::GetHitRect(pRootElement, m_hitRect);

  TiXmlElement *pChild = pRootElement->FirstChildElement();
  while (pChild)
  {
    CStdString strValue = pChild->Value();
    if (strValue == "type" && pChild->FirstChild())
    {
      // if we have are a window type (ie not a dialog), and we have <type>dialog</type>
      // then make this window act like a dialog
      if (!IsDialog() && strcmpi(pChild->FirstChild()->Value(), "dialog") == 0)
        m_isDialog = true;
    }
    else if (strValue == "previouswindow" && pChild->FirstChild())
    {
      m_previousWindow = CButtonTranslator::TranslateWindow(pChild->FirstChild()->Value());
    }
    else if (strValue == "defaultcontrol" && pChild->FirstChild())
    {
      const char *always = pChild->Attribute("always");
      if (always && strcmpi(always, "true") == 0)
        m_defaultAlways = true;
      m_defaultControl = atoi(pChild->FirstChild()->Value());
    }
    else if (strValue == "visible" && pChild->FirstChild())
    {
      CGUIControlFactory::GetConditionalVisibility(pRootElement, m_visibleCondition);
    }
    else if (strValue == "animation" && pChild->FirstChild())
    {
      CRect rect(0, 0, (float)g_settings.m_ResInfo[m_coordsRes].iWidth, (float)g_settings.m_ResInfo[m_coordsRes].iHeight);
      CAnimation anim;
      anim.Create(pChild, rect);
      m_animations.push_back(anim);
    }
    else if (strValue == "zorder" && pChild->FirstChild())
    {
      m_renderOrder = atoi(pChild->FirstChild()->Value());
    }
    else if (strValue == "coordinates")
    {
      // resolve any includes within coordinates tag (such as multiple origin includes)
      g_SkinInfo->ResolveIncludes(pChild);
      TiXmlNode* pSystem = pChild->FirstChild("system");
      if (pSystem)
      {
        int iCoordinateSystem = atoi(pSystem->FirstChild()->Value());
        m_bRelativeCoords = (iCoordinateSystem == 1);
      }

      CGUIControlFactory::GetFloat(pChild, "posx", m_posX);
      CGUIControlFactory::GetFloat(pChild, "posy", m_posY);

      TiXmlElement *originElement = pChild->FirstChildElement("origin");
      while (originElement)
      {
        COrigin origin;
        g_SkinInfo->ResolveConstant(originElement->Attribute("x"), origin.x);
        g_SkinInfo->ResolveConstant(originElement->Attribute("y"), origin.y);
        if (originElement->FirstChild())
          origin.condition = g_infoManager.TranslateString(originElement->FirstChild()->Value());
        m_origins.push_back(origin);
        originElement = originElement->NextSiblingElement("origin");
      }
    }
    else if (strValue == "camera")
    { // z is fixed
      g_SkinInfo->ResolveConstant(pChild->Attribute("x"), m_camera.x);
      g_SkinInfo->ResolveConstant(pChild->Attribute("y"), m_camera.y);
      m_hasCamera = true;
    }
    else if (strValue == "controls")
    {
      // resolve any includes within controls tag (such as whole <control> includes)
      g_SkinInfo->ResolveIncludes(pChild);

      TiXmlElement *pControl = pChild->FirstChildElement();
      while (pControl)
      {
        if (strcmpi(pControl->Value(), "control") == 0)
        {
          LoadControl(pControl, NULL);
        }
        pControl = pControl->NextSiblingElement();
      }
    }
    else if (strValue == "allowoverlay")
    {
      bool overlay = false;
      if (XMLUtils::GetBoolean(pRootElement, "allowoverlay", overlay))
        m_overlayState = overlay ? OVERLAY_STATE_SHOWN : OVERLAY_STATE_HIDDEN;
    }

    pChild = pChild->NextSiblingElement();
  }
  LoadAdditionalTags(pRootElement);

  m_windowLoaded = true;
  OnWindowLoaded();
  return true;
}
bool GazeboRosControllerManager::LoadControllerManagerFromURDF()
{
  std::string urdf_string = GetURDF(this->robotParam);

  // initialize TiXmlDocument doc with a string
  TiXmlDocument doc;
  if (!doc.Parse(urdf_string.c_str()) && doc.Error())
  {
    ROS_ERROR("Could not load the gazebo controller manager plugin's"
              " configuration file: %s\n", urdf_string.c_str());
    return false;
  }
  else
  {
    // debug
    // doc.Print();
    // std::cout << *(doc.RootElement()) << std::endl;

    // Pulls out the list of actuators used in the robot configuration.
    struct GetActuators : public TiXmlVisitor
    {
      std::set<std::string> actuators;
      virtual bool VisitEnter(const TiXmlElement &elt, const TiXmlAttribute *)
      {
        if (elt.ValueStr() == std::string("actuator") && elt.Attribute("name"))
          actuators.insert(elt.Attribute("name"));
        else if (elt.ValueStr() ==
          std::string("rightActuator") && elt.Attribute("name"))
          actuators.insert(elt.Attribute("name"));
        else if (elt.ValueStr() ==
          std::string("leftActuator") && elt.Attribute("name"))
          actuators.insert(elt.Attribute("name"));
        return true;
      }
    } get_actuators;
    doc.RootElement()->Accept(&get_actuators);

    // Places the found actuators into the hardware interface.
    std::set<std::string>::iterator it;
    for (it = get_actuators.actuators.begin();
         it != get_actuators.actuators.end(); ++it)
    {
      // std::cout << " adding actuator " << (*it) << std::endl;
      pr2_hardware_interface::Actuator* pr2_actuator =
        new pr2_hardware_interface::Actuator(*it);
      pr2_actuator->state_.is_enabled_ = true;
      this->hardware_interface_.addActuator(pr2_actuator);
    }

    // Setup mechanism control node
    this->controller_manager_->initXml(doc.RootElement());

    if (this->controller_manager_->state_ == NULL)
    {
      ROS_ERROR("Mechanism unable to parse robot_description URDF"
                " to fill out robot state in controller_manager.");
      return false;
    }

    // set fake calibration states for simulation
    for (unsigned int i = 0;
      i < this->controller_manager_->state_->joint_states_.size(); ++i)
      this->controller_manager_->state_->joint_states_[i].calibrated_ =
        calibration_status_;

    return true;
  }
}
Esempio n. 25
0
bool CVideoInfoTag::Save(TiXmlNode *node, const CStdString &tag, bool savePathInfo)
{
  if (!node) return false;

  // we start with a <tag> tag
  TiXmlElement movieElement(tag.c_str());
  TiXmlNode *movie = node->InsertEndChild(movieElement);

  if (!movie) return false;

  XMLUtils::SetString(movie, "title", m_strTitle);
  if (!m_strOriginalTitle.IsEmpty())
    XMLUtils::SetString(movie, "originaltitle", m_strOriginalTitle);
  if (!m_strSortTitle.IsEmpty())
    XMLUtils::SetString(movie, "sorttitle", m_strSortTitle);
  XMLUtils::SetFloat(movie, "rating", m_fRating);
  XMLUtils::SetInt(movie, "year", m_iYear);
  XMLUtils::SetInt(movie, "top250", m_iTop250);
  if (tag == "episodedetails" || tag == "tvshow")
  {
    XMLUtils::SetInt(movie, "season", m_iSeason);
    XMLUtils::SetInt(movie, "episode", m_iEpisode);
    XMLUtils::SetInt(movie, "displayseason",m_iSpecialSortSeason);
    XMLUtils::SetInt(movie, "displayepisode",m_iSpecialSortEpisode);
  }
  if (tag == "musicvideo")
  {
    XMLUtils::SetInt(movie, "track", m_iTrack);
    XMLUtils::SetString(movie, "album", m_strAlbum);
  }
  XMLUtils::SetString(movie, "votes", m_strVotes);
  XMLUtils::SetString(movie, "outline", m_strPlotOutline);
  XMLUtils::SetString(movie, "plot", m_strPlot);
  XMLUtils::SetString(movie, "tagline", m_strTagLine);
  XMLUtils::SetString(movie, "runtime", m_strRuntime);
  if (!m_strPictureURL.m_xml.empty())
  {
    TiXmlDocument doc;
    doc.Parse(m_strPictureURL.m_xml); 
    const TiXmlNode* thumb = doc.FirstChild("thumb");
    while (thumb)
    {
      movie->InsertEndChild(*thumb);
      thumb = thumb->NextSibling("thumb");
    }
  }
  if (m_fanart.m_xml.size())
  {
    TiXmlDocument doc;
    doc.Parse(m_fanart.m_xml);
    movie->InsertEndChild(*doc.RootElement());
  }
  XMLUtils::SetString(movie, "mpaa", m_strMPAARating);
  XMLUtils::SetInt(movie, "playcount", m_playCount);
  XMLUtils::SetString(movie, "lastplayed", m_lastPlayed);
  if (savePathInfo)
  {
    XMLUtils::SetString(movie, "file", m_strFile);
    XMLUtils::SetString(movie, "path", m_strPath);
    XMLUtils::SetString(movie, "filenameandpath", m_strFileNameAndPath);
  }
  if (!m_strEpisodeGuide.IsEmpty())
    XMLUtils::SetString(movie, "episodeguide", m_strEpisodeGuide);

  XMLUtils::SetString(movie, "id", m_strIMDBNumber);
  XMLUtils::SetString(movie, "genre", m_strGenre);
  XMLUtils::SetString(movie, "set", m_strSet);
  XMLUtils::SetString(movie, "credits", m_strWritingCredits);
  XMLUtils::SetString(movie, "director", m_strDirector);
  XMLUtils::SetString(movie, "premiered", m_strPremiered);
  XMLUtils::SetString(movie, "status", m_strStatus);
  XMLUtils::SetString(movie, "code", m_strProductionCode);
  XMLUtils::SetString(movie, "aired", m_strFirstAired);
  XMLUtils::SetString(movie, "studio", m_strStudio);
  XMLUtils::SetString(movie, "trailer", m_strTrailer);

  if (m_streamDetails.HasItems())
  {
    // it goes fileinfo/streamdetails/[video|audio|subtitle]
    TiXmlElement fileinfo("fileinfo");
    TiXmlElement streamdetails("streamdetails");
    for (int iStream=1; iStream<=m_streamDetails.GetVideoStreamCount(); iStream++)
    {
      TiXmlElement stream("video");
      XMLUtils::SetString(&stream, "codec", m_streamDetails.GetVideoCodec(iStream));
      XMLUtils::SetFloat(&stream, "aspect", m_streamDetails.GetVideoAspect(iStream));
      XMLUtils::SetInt(&stream, "width", m_streamDetails.GetVideoWidth(iStream));
      XMLUtils::SetInt(&stream, "height", m_streamDetails.GetVideoHeight(iStream));
      streamdetails.InsertEndChild(stream);
    }
    for (int iStream=1; iStream<=m_streamDetails.GetAudioStreamCount(); iStream++)
    {
      TiXmlElement stream("audio");
      XMLUtils::SetString(&stream, "codec", m_streamDetails.GetAudioCodec(iStream));
      XMLUtils::SetString(&stream, "language", m_streamDetails.GetAudioLanguage(iStream));
      XMLUtils::SetInt(&stream, "channels", m_streamDetails.GetAudioChannels(iStream));
      streamdetails.InsertEndChild(stream);
    }
    for (int iStream=1; iStream<=m_streamDetails.GetSubtitleStreamCount(); iStream++)
    {
      TiXmlElement stream("subtitle");
      XMLUtils::SetString(&stream, "language", m_streamDetails.GetSubtitleLanguage(iStream));
      streamdetails.InsertEndChild(stream);
    }
    fileinfo.InsertEndChild(streamdetails);
    movie->InsertEndChild(fileinfo);
  }  /* if has stream details */

  // cast
  for (iCast it = m_cast.begin(); it != m_cast.end(); ++it)
  {
    // add a <actor> tag
    TiXmlElement cast("actor");
    TiXmlNode *node = movie->InsertEndChild(cast);
    TiXmlElement actor("name");
    TiXmlNode *actorNode = node->InsertEndChild(actor);
    TiXmlText name(it->strName);
    actorNode->InsertEndChild(name);
    TiXmlElement role("role");
    TiXmlNode *roleNode = node->InsertEndChild(role);
    TiXmlText character(it->strRole);
    roleNode->InsertEndChild(character);
    TiXmlElement thumb("thumb");
    TiXmlNode *thumbNode = node->InsertEndChild(thumb);
    TiXmlText th(it->thumbUrl.GetFirstThumb().m_url);
    thumbNode->InsertEndChild(th);
  }
  XMLUtils::SetString(movie, "artist", m_strArtist);

  return true;
}
Esempio n. 26
0
bool CIMDB::InternalGetEpisodeList(const CScraperUrl& url, IMDB_EPISODELIST& details)
{
  IMDB_EPISODELIST temp;
  for(unsigned int i=0; i < url.m_url.size(); i++)
  {
    CStdString strHTML;
    if (!CScraperUrl::Get(url.m_url[i],strHTML, m_http) || strHTML.size() == 0)
    {
      CLog::Log(LOGERROR, "%s: Unable to retrieve web site",__FUNCTION__);
      if (temp.size() > 0 || (i == 0 && url.m_url.size() > 1)) // use what was fetched
        continue;

      return false;
    }
    m_parser.m_param[0] = strHTML;
    m_parser.m_param[1] = url.m_url[i].m_url;

    CStdString strXML = m_parser.Parse("GetEpisodeList",&m_info.settings);
    //CLog::Log(LOGDEBUG,"scraper: GetEpisodeList returned %s",strXML.c_str());
    if (strXML.IsEmpty())
    {
      CLog::Log(LOGERROR, "%s: Unable to parse web site",__FUNCTION__);
      if (temp.size() > 0 || (i == 0 && url.m_url.size() > 1)) // use what was fetched
        continue;

      return false;
    }
    // ok, now parse the xml file
    TiXmlDocument doc;
    doc.Parse(strXML.c_str());
    if (!doc.RootElement())
    {
      CLog::Log(LOGERROR, "%s: Unable to parse xml",__FUNCTION__);
      return false;
    }

    if (!XMLUtils::HasUTF8Declaration(strXML))
      g_charsetConverter.unknownToUTF8(strXML);

    TiXmlHandle docHandle( &doc );
    TiXmlElement *movie = docHandle.FirstChild( "episodeguide" ).FirstChild( "episode" ).Element();

    while (movie) 
    {
      TiXmlNode *title = movie->FirstChild("title");
      TiXmlElement *link = movie->FirstChildElement("url");
      TiXmlNode *epnum = movie->FirstChild("epnum");
      TiXmlNode *season = movie->FirstChild("season");
      TiXmlNode* id = movie->FirstChild("id");
      TiXmlNode *aired = movie->FirstChild("aired");
      if (link && link->FirstChild() && epnum && epnum->FirstChild() && season && season->FirstChild())
      {
        CScraperUrl url2;
        if (title && title->FirstChild())
          url2.strTitle = title->FirstChild()->Value();
        else
          url2.strTitle = g_localizeStrings.Get(416);

        while (link && link->FirstChild())
        {
          url2.ParseElement(link);
          link = link->NextSiblingElement("url");
        }

        if (id && id->FirstChild())
          url2.strId = id->FirstChild()->Value();
        pair<int,int> key(atoi(season->FirstChild()->Value()),atoi(epnum->FirstChild()->Value()));
        IMDB_EPISODE newEpisode;
        newEpisode.key = key;
        newEpisode.cDate.SetValid(FALSE);
        if (aired && aired->FirstChild())
        {
          const char *dateStr = aired->FirstChild()->Value();
          // date must be the format of yyyy-mm-dd
          if (strlen(dateStr)==10)
          {
            char year[5];
            char month[3];
            memcpy(year,dateStr,4);
            year[4] = '\0';
            memcpy(month,dateStr+5,2);
            month[2] = '\0';
            newEpisode.cDate.SetDate(atoi(year),atoi(month),atoi(dateStr+8));
      }
        }
        newEpisode.cScraperUrl = url2;
        temp.push_back(newEpisode);
      }
      movie = movie->NextSiblingElement();
    }
  }

  // find minimum in each season
  map<int,int> min;
  for (IMDB_EPISODELIST::iterator iter=temp.begin(); iter != temp.end(); ++iter ) 
  { 
    if ((signed int) min.size() == (iter->key.first -1))
      min.insert(iter->key);
    else if (iter->key.second < min[iter->key.first])
      min[iter->key.first] = iter->key.second;
  }
  // correct episode numbers
  for (IMDB_EPISODELIST::iterator iter=temp.begin(); iter != temp.end(); ++iter ) 
  {
    int episode=iter->key.second - min[iter->key.first];
    if (min[iter->key.first] > 0)
      episode++;
    pair<int,int> key(iter->key.first,episode);
    IMDB_EPISODE newEpisode;
    newEpisode.key = key;
    newEpisode.cDate = iter->cDate;
    newEpisode.cScraperUrl = iter->cScraperUrl;
    details.push_back(newEpisode);
  }

  return true;
}
Esempio n. 27
0
string FabAtHomePrinter::loadFabFile(string filePath)
{
      //Load the file.
	 TiXmlDocument file;
	 if(!file.LoadFile(filePath.c_str()))
	 {
		return "Could not interpret "+filePath+" as a xml file.";
      }

     //Clear previously loaded data.
	materialCalibrations.clear();
	model.paths.clear();

     TiXmlNode* root(file.RootElement());
	for(TiXmlNode* child = root->FirstChild(); child != NULL; child = root->IterateChildren(child))
	{
		if(strcmp(child->Value(), "materialCalibration") == 0)
		{
			loadMaterialCalibration(child);
		}
		else if(strcmp(child->Value(), "path") == 0)
		{
			loadPath(child);
		}
          else if(strcmp(child->Value(), "printAcceleration") == 0)
          {
               PRINT_ACCELERATION = Util::assertType<double>(child->FirstChild()->Value());
          }
	}
	 
     return "";

     /*     
     XMLParser parser;
     string result = parser.load(filePath);
     if(result.compare("") != 0)
     {
          return result;
     }
   
	//Clear previously loaded data.
	materialCalibrations.clear();
	model.paths.clear();

     PRINT_ACCELERATION = Util::assertType<double>(parser.text("fabAtHomePrinter 0\\printAcceleration 0"));

     //Load material calibrations.
     unsigned int count = parser.count("fabAtHomePrinter 0\\materialCalibration");
     for(unsigned int i = 0; i < count; ++i)
     {
          string base = "fabAtHomePrinter 0\\materialCalibration "+Util::toString(i)+"\\";
          string name = parser.text(base+"name 0");
          double pathSpeed = Util::assertType<double>(parser.text(base+"pathSpeed 0"));
          double pathWidth = Util::assertType<double>(parser.text(base+"pathWidth 0"));
          double depositionRate = Util::assertType<double>(parser.text(base+"depositionRate 0"));
          double pushout = Util::assertType<double>(parser.text(base+"pushout 0"));
          double suckback = Util::assertType<double>(parser.text(base+"suckback 0"));
          double suckbackDelay = Util::assertType<double>(parser.text(base+"suckbackDelay 0"));
          double clearance = Util::assertType<double>(parser.text(base+"clearance 0"));
          int pausePaths = Util::assertType<int>(parser.text(base+"pausePaths 0"));
          double pitch = Util::assertType<double>(parser.text(base+"pitch 0"));
          materialCalibrations[name] = MaterialCalibration(name,pathSpeed,pathWidth,depositionRate,pushout,suckback,suckbackDelay,clearance,pausePaths,pitch);    
     }

     //Load paths.
     unsigned int pathCount = parser.count("fabAtHomePrinter 0\\path");
     for(unsigned int i = 0; i < pathCount; ++i)
     {
          string iBase = "fabAtHomePrinter 0\\path "+Util::toString(i)+"\\";
          string materialCalibrationName = parser.text(iBase+"materialCalibrationName 0");
          if(materialCalibrations.find(materialCalibrationName) == materialCalibrations.end())
          {
               return "A path references material calibration "+materialCalibrationName+" which has not been loaded.";
          }
         	vector<Point> points;
          unsigned int pointCount = parser.count(iBase+"point");
          for(unsigned int j = 0; j < pointCount; ++j)
          {
               string jBase = iBase+"point "+Util::toString(j)+"\\";
               double x = Util::assertType<double>(parser.text(jBase+"x 0"));
			double y = Util::assertType<double>(parser.text(jBase+"y 0"));
			double z = Util::assertType<double>(parser.text(jBase+"z 0"));
               points.push_back(Point(x,y,z));
          }
     	model.paths.push_back(Path(&(materialCalibrations[materialCalibrationName]),points));
     }
     
     return "";
     */
     
}
Esempio n. 28
0
int CIMDB::InternalFindMovie(const CStdString &strMovie, IMDB_MOVIELIST& movielist, bool& sortMovieList, const CStdString& strFunction, CScraperUrl* pUrl)
{
  movielist.clear();

  CScraperUrl scrURL;
  
  CStdString strName = strMovie;
  CStdString movieTitle, movieTitleAndYear, movieYear;
  CUtil::CleanString(strName, movieTitle, movieTitleAndYear, movieYear, true);

  movieTitle.ToLower();

  CLog::Log(LOGDEBUG, "%s: Searching for '%s' using %s scraper (file: '%s', content: '%s', language: '%s', date: '%s', framework: '%s')",
    __FUNCTION__, movieTitle.c_str(), m_info.strTitle.c_str(), m_info.strPath.c_str(), m_info.strContent.c_str(), m_info.strLanguage.c_str(), m_info.strDate.c_str(), m_info.strFramework.c_str());

  if (!pUrl)
  {
  if (m_parser.HasFunction("CreateSearchUrl"))
  {
      GetURL(strMovie, movieTitle, movieYear, scrURL);
  }
  else if (m_info.strContent.Equals("musicvideos"))
  {
    if (!m_parser.HasFunction("FileNameScrape"))
      return false;
    
    CScraperUrl scrURL("filenamescrape");
    scrURL.strTitle = strMovie;
    movielist.push_back(scrURL);
      return 1;
  }
    if (scrURL.m_xml.IsEmpty())
      return 0;
  }
  else
    scrURL = *pUrl;  

  vector<CStdString> strHTML;
  for (unsigned int i=0;i<scrURL.m_url.size();++i)
  {
    CStdString strCurrHTML;
    if (!CScraperUrl::Get(scrURL.m_url[i],strCurrHTML,m_http) || strCurrHTML.size() == 0)
      return 0;
    strHTML.push_back(strCurrHTML);
  }
  
  // now grab our details using the scraper
  for (unsigned int i=0;i<strHTML.size();++i)
    m_parser.m_param[i] = strHTML[i];
  m_parser.m_param[strHTML.size()] = scrURL.m_url[0].m_url;
  CStdString strXML = m_parser.Parse(strFunction,&m_info.settings);
  //CLog::Log(LOGDEBUG,"scraper: %s returned %s",strFunction.c_str(),strXML.c_str());
  if (strXML.IsEmpty())
  {
    CLog::Log(LOGERROR, "%s: Unable to parse web site",__FUNCTION__);
    return 0;
  }
  
  if (!XMLUtils::HasUTF8Declaration(strXML))
    g_charsetConverter.unknownToUTF8(strXML);

  // ok, now parse the xml file
  TiXmlDocument doc;
  doc.Parse(strXML.c_str(),0,TIXML_ENCODING_UTF8);
  if (!doc.RootElement())
  {
    CLog::Log(LOGERROR, "%s: Unable to parse xml",__FUNCTION__);
    return 0;
  }
  if (stricmp(doc.RootElement()->Value(),"error")==0)
  {
    TiXmlElement* title = doc.RootElement()->FirstChildElement("title");
    CStdString strTitle;
    if (title && title->FirstChild() && title->FirstChild()->Value())
      strTitle = title->FirstChild()->Value();
    TiXmlElement* message = doc.RootElement()->FirstChildElement("message");
    CStdString strMessage;
    if (message && message->FirstChild() && message->FirstChild()->Value())
      strMessage = message->FirstChild()->Value();
    CGUIDialogOK* dialog = (CGUIDialogOK*)g_windowManager.GetWindow(WINDOW_DIALOG_OK);
    dialog->SetHeading(strTitle);
    dialog->SetLine(0,strMessage);
    g_application.getApplicationMessenger().DoModal(dialog,WINDOW_DIALOG_OK);
    return -1;
  }
 
  TiXmlHandle docHandle( &doc );

  TiXmlElement* xurl = doc.RootElement()->FirstChildElement("url");
  while (xurl && xurl->FirstChild())
  {
    const char* szFunction = xurl->Attribute("function");
    if (szFunction)
    {
      CScraperUrl scrURL(xurl);
      InternalFindMovie(strMovie,movielist,sortMovieList,szFunction,&scrURL);
    }
    xurl = xurl->NextSiblingElement("url");
  }

  TiXmlElement *movie = docHandle.FirstChild( "results" ).FirstChild( "entity" ).Element();
  if (!movie)
    return 0;

  while (movie)
  {
    // is our result already sorted correctly when handed over from scraper? if so, do not let xbmc sort it
    if (sortMovieList)
    {
      TiXmlElement* results = docHandle.FirstChild("results").Element();
      if (results)
      {
        CStdString szSorted = results->Attribute("sorted");
        sortMovieList = (szSorted.CompareNoCase("yes") != 0);
      }
    }

    CScraperUrl url;
    TiXmlNode *title = movie->FirstChild("title");
    TiXmlElement *link = movie->FirstChildElement("url");
    TiXmlNode *year = movie->FirstChild("year");
    TiXmlNode* id = movie->FirstChild("id");
    TiXmlNode* language = movie->FirstChild("language");
    if (title && title->FirstChild() && link && link->FirstChild())
    {
      url.strTitle = title->FirstChild()->Value();
      while (link && link->FirstChild())
      {
        url.ParseElement(link);
        link = link->NextSiblingElement("url");
      }
      if (id && id->FirstChild())
        url.strId = id->FirstChild()->Value();

      // calculate the relavance of this hit
      CStdString compareTitle = url.strTitle;
      compareTitle.ToLower();
      CStdString matchTitle = movieTitle;
      matchTitle.ToLower();
      // see if we need to add year information
      CStdString compareYear;
        if(year && year->FirstChild())
        compareYear = year->FirstChild()->Value();
      if (!movieYear.IsEmpty() && !compareYear.IsEmpty())
          {
        matchTitle.AppendFormat(" (%s)", movieYear.c_str());
        compareTitle.AppendFormat(" (%s)", compareYear.c_str());
          }
      url.relevance = fstrcmp(matchTitle.c_str(), compareTitle.c_str(), 0);
      // reconstruct a title for the user
      CStdString title = url.strTitle;
      if (!compareYear.IsEmpty())
        title.AppendFormat(" (%s)", compareYear.c_str());
      if (language && language->FirstChild())
        title.AppendFormat(" (%s)", language->FirstChild()->Value());
      url.strTitle = title;
        movielist.push_back(url);
    }
    movie = movie->NextSiblingElement();
  }

  return 1;
}
Esempio n. 29
0
bool CUpdateXMLHandler::LoadXMLToMem (std::string rootDir)
{
    std::string UpdateXMLFilename = rootDir  + DirSepChar + "xbmc-txupdate.xml";
    TiXmlDocument xmlUpdateXML;

    if (!xmlUpdateXML.LoadFile(UpdateXMLFilename.c_str()))
    {
        CLog::Log(logERROR, "UpdXMLHandler: No 'xbmc-txupdate.xml' file exists in the specified project dir. Cannot continue. "
                  "Please create one!");
        return false;
    }

    CLog::Log(logINFO, "UpdXMLHandler: Succesfuly found the update.xml file in the specified project directory");

    TiXmlElement* pRootElement = xmlUpdateXML.RootElement();
    if (!pRootElement || pRootElement->NoChildren() || pRootElement->ValueTStr()!="resources")
    {
        CLog::Log(logERROR, "UpdXMLHandler: No root element called \"resources\" in xml file. Cannot continue. Please create it");
        return false;
    }

    std::string strProjName ;
    if (pRootElement->Attribute("projectname") && (strProjName = pRootElement->Attribute("projectname")) != "")
    {
        CLog::Log(logINFO, "UpdXMLHandler: Found projectname in xbmc-txupdate.xml file: %s",strProjName.c_str());
        g_Settings.SetProjectname(strProjName);
    }
    else
        CLog::Log(logERROR, "UpdXMLHandler: No projectname specified in xbmc-txupdate.xml file. Cannot continue. "
                  "Please specify the Transifex projectname in the xml file");

    std::string strHTTPCacheExp;
    if (pRootElement->Attribute("http_cache_expire") && (strHTTPCacheExp = pRootElement->Attribute("http_cache_expire")) != "")
    {
        CLog::Log(logINFO, "UpdXMLHandler: Found http cache expire time in xbmc-txupdate.xml file: %s", strHTTPCacheExp.c_str());
        g_Settings.SetHTTPCacheExpire(strtol(&strHTTPCacheExp[0], NULL, 10));
    }
    else
        CLog::Log(logINFO, "UpdXMLHandler: No http cache expire time specified in xbmc-txupdate.xml file. Using default value: %iminutes",
                  DEFAULTCACHEEXPIRE);

    std::string strMinCompletion;
    if (pRootElement->Attribute("min_completion") && (strMinCompletion = pRootElement->Attribute("min_completion")) != "")
    {
        CLog::Log(logINFO, "UpdXMLHandler: Found min completion percentage in xbmc-txupdate.xml file: %s", strMinCompletion.c_str());
        g_Settings.SetMinCompletion(strtol(&strMinCompletion[0], NULL, 10));
    }
    else
        CLog::Log(logINFO, "UpdXMLHandler: No min completion percentage specified in xbmc-txupdate.xml file. Using default value: %i%",
                  DEFAULTMINCOMPLETION);

    std::string strMergedLangfileDir;
    if (pRootElement->Attribute("merged_langfiledir") && (strMergedLangfileDir = pRootElement->Attribute("merged_langfiledir")) != "")
    {
        CLog::Log(logINFO, "UpdXMLHandler: Found merged language file directory in xbmc-txupdate.xml file: %s", strMergedLangfileDir.c_str());
        g_Settings.SetMergedLangfilesDir(strMergedLangfileDir);
    }
    else
        CLog::Log(logINFO, "UpdXMLHandler: No merged language file directory specified in xbmc-txupdate.xml file. Using default value: %s",
                  g_Settings.GetMergedLangfilesDir().c_str());

    std::string strTXUpdatelangfileDir;
    if (pRootElement->Attribute("temptxupdate_langfiledir") && (strTXUpdatelangfileDir = pRootElement->Attribute("temptxupdate_langfiledir")) != "")
    {
        CLog::Log(logINFO, "UpdXMLHandler: Found temp tx update language file directory in xbmc-txupdate.xml file: %s", strTXUpdatelangfileDir.c_str());
        g_Settings.SetTXUpdateLangfilesDir(strTXUpdatelangfileDir);
    }
    else
        CLog::Log(logINFO, "UpdXMLHandler: No temp tx update language file directory specified in xbmc-txupdate.xml file. Using default value: %s",
                  g_Settings.GetTXUpdateLangfilesDir().c_str());

    std::string strSupportEmailAdd;
    if (pRootElement->Attribute("support_email") && (strSupportEmailAdd = pRootElement->Attribute("support_email")) != "")
    {
        CLog::Log(logINFO, "UpdXMLHandler: Found support email address in xbmc-txupdate.xml file: %s", strSupportEmailAdd.c_str());
        g_Settings.SetSupportEmailAdd(strSupportEmailAdd);
    }
    else
        CLog::Log(logINFO, "UpdXMLHandler: No support email address specified in xbmc-txupdate.xml file. Using default value: %s",
                  g_Settings.GetSupportEmailAdd().c_str());

    std::string strForcePOComm;
    if (pRootElement->Attribute("forcePOComm") && (strForcePOComm = pRootElement->Attribute("forcePOComm")) == "true")
    {
        CLog::Log(logINFO, "UpdXMLHandler: Forced PO file comments for non English languages.", strMergedLangfileDir.c_str());
        g_Settings.SetForcePOComments(true);
    }

    const TiXmlElement *pChildResElement = pRootElement->FirstChildElement("resource");
    if (!pChildResElement || pChildResElement->NoChildren())
    {
        CLog::Log(logERROR, "UpdXMLHandler: No xml element called \"resource\" exists in the xml file. Cannot continue. Please create at least one");
        return false;
    }

    std::string strType;
    while (pChildResElement && pChildResElement->FirstChild())
    {
        CXMLResdata currResData;
        std::string strResName;
        if (!pChildResElement->Attribute("name") || (strResName = pChildResElement->Attribute("name")) == "")
        {
            CLog::Log(logERROR, "UpdXMLHandler: No name specified for resource. Cannot continue. Please specify it.");
            return false;
        }

        if (pChildResElement->FirstChild())
        {
            const TiXmlElement *pChildURLElement = pChildResElement->FirstChildElement("upstreamURL");
            if (pChildURLElement && pChildURLElement->FirstChild())
                currResData.strUpstreamURL = pChildURLElement->FirstChild()->Value();
            if (currResData.strUpstreamURL.empty())
                CLog::Log(logERROR, "UpdXMLHandler: UpstreamURL entry is empty or missing for resource %s", strResName.c_str());
            if (pChildURLElement->Attribute("filetype"))
                currResData.strLangFileType = pChildURLElement->Attribute("filetype"); // For PO no need to explicitly specify. Only for XML.
            if (pChildURLElement->Attribute("URLsuffix"))
                currResData.strURLSuffix = pChildURLElement->Attribute("URLsuffix"); // Some http servers need suffix strings after filename(eg. gitweb)
            if (pChildURLElement->Attribute("HasChangelog"))
            {
                std::string strHaschangelog = pChildURLElement->Attribute("HasChangelog"); // Note if the addon has upstream changelog
                currResData.bHasChangelog = strHaschangelog == "true";
            }
            if (pChildURLElement->Attribute("LogFormat"))
            {
                std::string strLogFormat = pChildURLElement->Attribute("LogFormat");
                currResData.strLogFormat = strLogFormat;
            }
            if (pChildURLElement->Attribute("LogFilename"))
            {
                std::string strLogFilename = pChildURLElement->Attribute("LogFilename");
                currResData.strLogFilename = strLogFilename;
            }

            const TiXmlElement *pChildUpstrLElement = pChildResElement->FirstChildElement("upstreamLangs");
            if (pChildUpstrLElement && pChildUpstrLElement->FirstChild())
                currResData.strLangsFromUpstream = pChildUpstrLElement->FirstChild()->Value();

            const TiXmlElement *pChildResTypeElement = pChildResElement->FirstChildElement("resourceType");
            if (pChildResTypeElement->Attribute("AddonXMLSuffix"))
                currResData.strAddonXMLSuffix = pChildResTypeElement->Attribute("AddonXMLSuffix"); // Some addons have unique addon.xml filename eg. pvr addons with .in suffix
            if (pChildResTypeElement && pChildResTypeElement->FirstChild())
            {
                strType = pChildResTypeElement->FirstChild()->Value();
                if (strType == "addon")
                    currResData.Restype = ADDON;
                else if (strType == "addon_nostrings")
                    currResData.Restype = ADDON_NOSTRINGS;
                else if (strType == "skin")
                    currResData.Restype = SKIN;
                else if (strType == "xbmc_core")
                    currResData.Restype = CORE;
            }
            if (currResData.Restype == UNKNOWN)
                CLog::Log(logERROR, "UpdXMLHandler: Unknown type found or missing resourceType field for resource %s", strResName.c_str());

            const TiXmlElement *pChildResDirElement = pChildResElement->FirstChildElement("resourceSubdir");
            if (pChildResDirElement && pChildResDirElement->FirstChild())
                currResData.strResDirectory = pChildResDirElement->FirstChild()->Value();
            if (pChildResDirElement->Attribute("writePO"))
            {
                std::string strBool = pChildResDirElement->Attribute("writePO");
                currResData.bWritePO = strBool == "true";
            }
            if (pChildResDirElement->Attribute("writeXML"))
            {
                std::string strBool = pChildResDirElement->Attribute("writeXML");
                currResData.bWriteXML = strBool == "true";
            }
            if (pChildResDirElement->Attribute("DIRprefix"))
                currResData.strDIRprefix = pChildResDirElement->Attribute("DIRprefix"); // If there is any SUBdirectory needed in the tree

            const TiXmlElement *pChildTXNameElement = pChildResElement->FirstChildElement("TXname");
            if (pChildTXNameElement && pChildTXNameElement->FirstChild())
                currResData.strTXResName = pChildTXNameElement->FirstChild()->Value();
            if (currResData.strTXResName.empty())
                CLog::Log(logERROR, "UpdXMLHandler: Transifex resource name is empty or missing for resource %s", strResName.c_str());

            m_mapXMLResdata[strResName] = currResData;
            CLog::Log(logINFO, "UpdXMLHandler: found resource in update.xml file: %s, Type: %s, SubDir: %s",
                      strResName.c_str(), strType.c_str(), currResData.strResDirectory.c_str());
        }
        pChildResElement = pChildResElement->NextSiblingElement("resource");
    }

    return true;
};
Esempio n. 30
0
    AnimationPtr AnimationLoader::load(const std::string& filename) {
        bfs::path animPath(filename);

        std::string animationFilename = animPath.string();

        TiXmlDocument doc;

        AnimationPtr animation;

        try {
            RawData* data = m_vfs->open(animationFilename);

            if (data) {
                if (data->getDataLength() != 0) {
                    doc.Parse(data->readString(data->getDataLength()).c_str());

                    if (doc.Error()) {
                        return animation;
                    }

                    // done with data delete resource
                    delete data;
                    data = 0;
                }
            }
        }
        catch (NotFound& e) {
            FL_ERR(_log, e.what());

            // TODO - should we abort here
            //        or rethrow the exception
            //        or just keep going

            return animation;
        }

        // if we get here then everything loaded properly
        // so we can just parse out the contents
        TiXmlElement* root = doc.RootElement();

        if (root) {
            animation.reset(new Animation());

            int animDelay = 0;
            root->QueryValueAttribute("delay", &animDelay);

            int animXoffset = 0;
            int animYoffset = 0;
            int action = -1;
            root->QueryValueAttribute("x_offset", &animXoffset);
            root->QueryValueAttribute("y_offset", &animYoffset);
            root->QueryValueAttribute("action", &action);

            for (TiXmlElement* frameElement = root->FirstChildElement("frame"); frameElement; frameElement = frameElement->NextSiblingElement("frame")) {
                if (animation) {
                    animation->setActionFrame(action);

                    const std::string* sourceId = frameElement->Attribute(std::string("source"));

                    if (sourceId) {
                        bfs::path framePath(filename);

                        if (HasParentPath(framePath)) {
							framePath = GetParentPath(framePath) / *sourceId;
						} else {
							framePath = bfs::path(*sourceId);
						}

						ImagePtr imagePtr;
						if(!m_imageManager->exists(framePath.string())) {
                        	imagePtr = m_imageManager->create(framePath.string());
						}
						else {
							imagePtr = m_imageManager->getPtr(framePath.string());
						}

                        if (imagePtr) {
                            int frameXoffset = 0;
                            int frameYoffset = 0;

                            int success = root->QueryValueAttribute("x_offset", &frameXoffset);

                            if (success == TIXML_SUCCESS) {
                                imagePtr->setXShift(frameXoffset);
                            }
                            else {
                                imagePtr->setXShift(animXoffset);
                            }

                            success = root->QueryValueAttribute("y_offset", &frameYoffset);

                            if (success == TIXML_SUCCESS) {
                                imagePtr->setYShift(frameYoffset);
                            }
                            else {
                                imagePtr->setYShift(animYoffset);
                            }

                            int frameDelay = 0;
                            success = root->QueryValueAttribute("delay", &frameDelay);

                            if (success == TIXML_SUCCESS) {
                                animation->addFrame(imagePtr, frameDelay);
                            }
                            else {
                                animation->addFrame(imagePtr, animDelay);
                            }
                        }
                    }
                }
            }
        }

        return animation;
    }