Пример #1
0
void LoadNode(Node *parent, TiXmlElement *element, int level)
{
    Node *node = new Node;
    parent->AppendChild(node);
    
    // name
    const char* name = element->Attribute("name");
    node->SetName(name);
    PrintIndent(level);
    printf("object [");
    if ( name ) printf("%s",name);
    printf("]");
    
    // type
    const char* type = element->Attribute("type");
    if ( type ) {
        if ( COMPARE(type,"sphere") ) {
            node->SetObject( &theSphere );
            printf(" - Sphere");
        } else if ( COMPARE(type,"plane") ) {
            node->SetObject( &thePlane );
            printf(" - Plane");
        } else if ( COMPARE(type,"obj") ) {
            printf(" - OBJ");
            Object *obj = objList.Find(name);
            if ( obj == NULL ) {    // object is not on the list, so we should load it now
                TriObj *tobj = new TriObj;
                if ( ! tobj->Load( name ) ) {
                    printf(" -- ERROR: Cannot load file \"%s.\"", name);
                    delete tobj;
                } else {
                    objList.Append(tobj,name);  // add to the list
                    obj = tobj;
                }
            }
            node->SetObject( obj );
        } else {
            printf(" - UNKNOWN TYPE");
        }
    }
    
    // type
    const char* mtlName = element->Attribute("material");
    if ( mtlName ) {
        printf(" <%s>", mtlName);
        NodeMtl nm;
        nm.node = node;
        nm.mtlName = mtlName;
        nodeMtlList.push_back(nm);
    }
    
    printf("\n");
    
    
    for ( TiXmlElement *child = element->FirstChildElement(); child!=NULL; child = child->NextSiblingElement() ) {
        if ( COMPARE( child->Value(), "object" ) ) {
            LoadNode(node,child,level+1);
        }
    }
    LoadTransform( node, element, level );
    
}
Пример #2
0
void CAdvancedSettings::ParseSettingsFile(const CStdString &file)
{
  CXBMCTinyXML advancedXML;
  if (!CFile::Exists(file))
  {
    CLog::Log(LOGNOTICE, "No settings file to load (%s)", file.c_str());
    return;
  }

  if (!advancedXML.LoadFile(file))
  {
    CLog::Log(LOGERROR, "Error loading %s, Line %d\n%s", file.c_str(), advancedXML.ErrorRow(), advancedXML.ErrorDesc());
    return;
  }

  TiXmlElement *pRootElement = advancedXML.RootElement();
  if (!pRootElement || strcmpi(pRootElement->Value(),"advancedsettings") != 0)
  {
    CLog::Log(LOGERROR, "Error loading %s, no <advancedsettings> node", file.c_str());
    return;
  }

  // succeeded - tell the user it worked
  CLog::Log(LOGNOTICE, "Loaded settings file from %s", file.c_str());

  // Dump contents of AS.xml to debug log
  TiXmlPrinter printer;
  printer.SetLineBreak("\n");
  printer.SetIndent("  ");
  advancedXML.Accept(&printer);
  CLog::Log(LOGNOTICE, "Contents of %s are...\n%s", file.c_str(), printer.CStr());

  TiXmlElement *pElement = pRootElement->FirstChildElement("audio");
  if (pElement)
  {
    XMLUtils::GetFloat(pElement, "ac3downmixgain", m_ac3Gain, -96.0f, 96.0f);
    XMLUtils::GetInt(pElement, "headroom", m_audioHeadRoom, 0, 12);
    XMLUtils::GetString(pElement, "defaultplayer", m_audioDefaultPlayer);
    // 101 on purpose - can be used to never automark as watched
    XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_audioPlayCountMinimumPercent, 0.0f, 101.0f);

    XMLUtils::GetBoolean(pElement, "usetimeseeking", m_musicUseTimeSeeking);
    XMLUtils::GetInt(pElement, "timeseekforward", m_musicTimeSeekForward, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackward", m_musicTimeSeekBackward, -6000, 0);
    XMLUtils::GetInt(pElement, "timeseekforwardbig", m_musicTimeSeekForwardBig, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_musicTimeSeekBackwardBig, -6000, 0);

    XMLUtils::GetInt(pElement, "percentseekforward", m_musicPercentSeekForward, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackward", m_musicPercentSeekBackward, -100, 0);
    XMLUtils::GetInt(pElement, "percentseekforwardbig", m_musicPercentSeekForwardBig, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_musicPercentSeekBackwardBig, -100, 0);

    XMLUtils::GetInt(pElement, "resample", m_audioResample, 0, 192000);
    XMLUtils::GetBoolean(pElement, "allowtranscode44100", m_allowTranscode44100);
    XMLUtils::GetBoolean(pElement, "forceDirectSound", m_audioForceDirectSound);
    XMLUtils::GetBoolean(pElement, "audiophile", m_audioAudiophile);
    XMLUtils::GetBoolean(pElement, "allchannelstereo", m_allChannelStereo);
    XMLUtils::GetString(pElement, "transcodeto", m_audioTranscodeTo);
    XMLUtils::GetInt(pElement, "audiosinkbufferdurationmsec", m_audioSinkBufferDurationMsec);

    TiXmlElement* pAudioExcludes = pElement->FirstChildElement("excludefromlisting");
    if (pAudioExcludes)
      GetCustomRegexps(pAudioExcludes, m_audioExcludeFromListingRegExps);

    pAudioExcludes = pElement->FirstChildElement("excludefromscan");
    if (pAudioExcludes)
      GetCustomRegexps(pAudioExcludes, m_audioExcludeFromScanRegExps);

    XMLUtils::GetString(pElement, "audiohost", m_audioHost);
    XMLUtils::GetBoolean(pElement, "applydrc", m_audioApplyDrc);
    XMLUtils::GetBoolean(pElement, "dvdplayerignoredtsinwav", m_dvdplayerIgnoreDTSinWAV);

    XMLUtils::GetFloat(pElement, "limiterhold", m_limiterHold, 0.0f, 100.0f);
    XMLUtils::GetFloat(pElement, "limiterrelease", m_limiterRelease, 0.001f, 100.0f);
  }

  pElement = pRootElement->FirstChildElement("karaoke");
  if (pElement)
  {
    XMLUtils::GetFloat(pElement, "syncdelaycdg", m_karaokeSyncDelayCDG, -3.0f, 3.0f); // keep the old name for comp
    XMLUtils::GetFloat(pElement, "syncdelaylrc", m_karaokeSyncDelayLRC, -3.0f, 3.0f);
    XMLUtils::GetBoolean(pElement, "alwaysreplacegenre", m_karaokeChangeGenreForKaraokeSongs );
    XMLUtils::GetBoolean(pElement, "storedelay", m_karaokeKeepDelay );
    XMLUtils::GetInt(pElement, "autoassignstartfrom", m_karaokeStartIndex, 1, 2000000000);
    XMLUtils::GetBoolean(pElement, "nocdgbackground", m_karaokeAlwaysEmptyOnCdgs );
    XMLUtils::GetBoolean(pElement, "lookupsongbackground", m_karaokeUseSongSpecificBackground );

    TiXmlElement* pKaraokeBackground = pElement->FirstChildElement("defaultbackground");
    if (pKaraokeBackground)
    {
      const char* attr = pKaraokeBackground->Attribute("type");
      if ( attr )
        m_karaokeDefaultBackgroundType = attr;

      attr = pKaraokeBackground->Attribute("path");
      if ( attr )
        m_karaokeDefaultBackgroundFilePath = attr;
    }
  }

  pElement = pRootElement->FirstChildElement("video");
  if (pElement)
  {
    XMLUtils::GetFloat(pElement, "subsdelayrange", m_videoSubsDelayRange, 10, 600);
    XMLUtils::GetFloat(pElement, "audiodelayrange", m_videoAudioDelayRange, 10, 600);
    XMLUtils::GetInt(pElement, "blackbarcolour", m_videoBlackBarColour, 0, 255);
    XMLUtils::GetString(pElement, "defaultplayer", m_videoDefaultPlayer);
    XMLUtils::GetString(pElement, "defaultdvdplayer", m_videoDefaultDVDPlayer);
    XMLUtils::GetBoolean(pElement, "fullscreenonmoviestart", m_fullScreenOnMovieStart);
    // 101 on purpose - can be used to never automark as watched
    XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_videoPlayCountMinimumPercent, 0.0f, 101.0f);
    XMLUtils::GetInt(pElement, "ignoresecondsatstart", m_videoIgnoreSecondsAtStart, 0, 900);
    XMLUtils::GetFloat(pElement, "ignorepercentatend", m_videoIgnorePercentAtEnd, 0, 100.0f);

    XMLUtils::GetInt(pElement, "smallstepbackseconds", m_videoSmallStepBackSeconds, 1, INT_MAX);
    XMLUtils::GetInt(pElement, "smallstepbacktries", m_videoSmallStepBackTries, 1, 10);
    XMLUtils::GetInt(pElement, "smallstepbackdelay", m_videoSmallStepBackDelay, 100, 5000); //MS

    XMLUtils::GetBoolean(pElement, "usetimeseeking", m_videoUseTimeSeeking);
    XMLUtils::GetInt(pElement, "timeseekforward", m_videoTimeSeekForward, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackward", m_videoTimeSeekBackward, -6000, 0);
    XMLUtils::GetInt(pElement, "timeseekforwardbig", m_videoTimeSeekForwardBig, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_videoTimeSeekBackwardBig, -6000, 0);

    XMLUtils::GetInt(pElement, "percentseekforward", m_videoPercentSeekForward, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackward", m_videoPercentSeekBackward, -100, 0);
    XMLUtils::GetInt(pElement, "percentseekforwardbig", m_videoPercentSeekForwardBig, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_videoPercentSeekBackwardBig, -100, 0);

    TiXmlElement* pVideoExcludes = pElement->FirstChildElement("excludefromlisting");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_videoExcludeFromListingRegExps);

    pVideoExcludes = pElement->FirstChildElement("excludefromscan");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_moviesExcludeFromScanRegExps);

    pVideoExcludes = pElement->FirstChildElement("excludetvshowsfromscan");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_tvshowExcludeFromScanRegExps);

    pVideoExcludes = pElement->FirstChildElement("cleanstrings");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_videoCleanStringRegExps);

    XMLUtils::GetString(pElement,"cleandatetime", m_videoCleanDateTimeRegExp);
    XMLUtils::GetString(pElement,"ppffmpegdeinterlacing",m_videoPPFFmpegDeint);
    XMLUtils::GetString(pElement,"ppffmpegpostprocessing",m_videoPPFFmpegPostProc);
    XMLUtils::GetBoolean(pElement,"vdpauscaling",m_videoVDPAUScaling);
    XMLUtils::GetFloat(pElement, "nonlinearstretchratio", m_videoNonLinStretchRatio, 0.01f, 1.0f);
    XMLUtils::GetBoolean(pElement,"enablehighqualityhwscalers", m_videoEnableHighQualityHwScalers);
    XMLUtils::GetFloat(pElement,"autoscalemaxfps",m_videoAutoScaleMaxFps, 0.0f, 1000.0f);
    XMLUtils::GetBoolean(pElement,"allowmpeg4vdpau",m_videoAllowMpeg4VDPAU);
    XMLUtils::GetBoolean(pElement,"allowmpeg4vaapi",m_videoAllowMpeg4VAAPI);    
    XMLUtils::GetBoolean(pElement, "disablebackgrounddeinterlace", m_videoDisableBackgroundDeinterlace);
    XMLUtils::GetInt(pElement, "useocclusionquery", m_videoCaptureUseOcclusionQuery, -1, 1);

    TiXmlElement* pAdjustRefreshrate = pElement->FirstChildElement("adjustrefreshrate");
    if (pAdjustRefreshrate)
    {
      TiXmlElement* pRefreshOverride = pAdjustRefreshrate->FirstChildElement("override");
      while (pRefreshOverride)
      {
        RefreshOverride override = {0};

        float fps;
        if (XMLUtils::GetFloat(pRefreshOverride, "fps", fps))
        {
          override.fpsmin = fps - 0.01f;
          override.fpsmax = fps + 0.01f;
        }

        float fpsmin, fpsmax;
        if (XMLUtils::GetFloat(pRefreshOverride, "fpsmin", fpsmin) &&
            XMLUtils::GetFloat(pRefreshOverride, "fpsmax", fpsmax))
        {
          override.fpsmin = fpsmin;
          override.fpsmax = fpsmax;
        }

        float refresh;
        if (XMLUtils::GetFloat(pRefreshOverride, "refresh", refresh))
        {
          override.refreshmin = refresh - 0.01f;
          override.refreshmax = refresh + 0.01f;
Пример #3
0
bool CConfigManager::SaveConfig()
{
	TiXmlDocument doc;
	doc.LoadFile(m_strConfigFile.c_str());

	TiXmlElement* pRoot = doc.RootElement();
	const char* szRoot = pRoot->Value();
	if(strcmp("system", szRoot) != 0)
		return false;

	for (TiXmlElement* pChiled = pRoot->FirstChildElement(); pChiled != NULL; pChiled = pChiled->NextSiblingElement())
	{
		const char* szValue = pChiled->Value();
		if(strcmp(Software, szValue) == 0)
		{
			pChiled->SetAttribute(Ver, m_strAppVer.c_str());
		}
		else if(strcmp(Configur, szValue) == 0)
		{
			pChiled->SetAttribute(Ver, m_strConfigVer.c_str());
		}
// 		else if(strcmp(Globle, szValue) == 0)
// 		{
// 			m_strHeight = pChiled->Attribute(Height);
// 			m_strWidth = pChiled->Attribute(Width);
// 			string strAdverCount = pChiled->Attribute(AdverCount);
// 			m_nAdverCount = atoi(strAdverCount.c_str());
// 		}
		else if(strcmp(Sever, szValue) == 0)
		{
			pChiled->SetAttribute(IP, m_strIp.c_str());
			pChiled->SetAttribute(Port, m_strPort.c_str());
		}
		else if(strcmp(Notice, szValue) == 0)
		{
			pChiled->SetAttribute(Dir, m_strNoticeDir.c_str());
		}
		else if(strcmp(Template, szValue) == 0)
		{
			pChiled->SetAttribute(Ver, m_strTempVer.c_str());
			pChiled->SetAttribute(Dir, m_strTemplatePath.c_str());
		}
		else if(strcmp(Adver, szValue) == 0)
		{
			m_Adver.SaveAdver(pChiled);
		}
		else if(strcmp(BusStop, szValue) == 0)
		{
			m_Busstop.SaveBusStop(pChiled);
		}
		else if(strcmp(Picture, szValue) == 0)
		{
			pChiled->SetAttribute(Dir, m_strPictrueDir.c_str());
		}
		else if(strcmp(Default, szValue) == 0)
		{
			pChiled->SetAttribute(Dir, m_strDefaultPath.c_str());
		}
	}

	doc.SaveFile();
	return true;
}
Пример #4
0
TiXmlElement* wxsVersionConverter::ConvertFromOldConfig(TiXmlElement* ConfigNode,TiXmlDocument* Doc,wxsProject* Project) const
{
    if ( cbMessageBox(_("This project uses old wxSmith configuration format\n"
                        "Would you like me to convert to new one?\n"),
                      _("wxSmith: Converting from old format"),
                      wxYES_NO) != wxID_YES ) return 0;

    TiXmlElement* NewConfig = Doc->InsertEndChild(TiXmlElement("wxSmith"))->ToElement();
    TiXmlElement* Resources = NewConfig->InsertEndChild(TiXmlElement("resources"))->ToElement();
    NewConfig->SetAttribute("version",CurrentVersionStr);
    for ( TiXmlElement* Node = ConfigNode->FirstChildElement(); Node; Node = Node->NextSiblingElement() )
    {
        wxString NodeName = cbC2U(Node->Value());
        if ( NodeName == _T("configuration") )
        {
            const char* AppSrc  = Node->Attribute("app_src_file");
            const char* Main    = Node->Attribute("main_resource");
            const char* InitAll = Node->Attribute("init_all_handlers");

            if ( AppSrc )
            {
                TiXmlElement* GUINode = NewConfig->InsertEndChild(TiXmlElement("gui"))->ToElement();
                GUINode->SetAttribute("name","wxWidgets");
                GUINode->SetAttribute("src",AppSrc);
                GUINode->SetAttribute("main",Main?Main:"");
                GUINode->SetAttribute("init_handlers",InitAll?InitAll:"necessary");
                GUINode->SetAttribute("language","CPP");
            }
        }
        else
        {
            if ( NodeName == _T("dialog") ||
                 NodeName == _T("frame") ||
                 NodeName == _T("panel") )
            {
                const char* Wxs   = Node->Attribute("wxs_file");
                const char* Class = Node->Attribute("class");
                const char* Src   = Node->Attribute("src_file");
                const char* Hdr   = Node->Attribute("header_file");
                const char* Xrc   = Node->Attribute("xrc_file");
                const char* Mode  = Node->Attribute("edit_mode");

                if ( Wxs && Class && Src && Hdr && Mode )
                {
                    if ( cbC2U(Mode) == _T("Source") ) Xrc = 0;
                    TiXmlElement* Res = Resources->InsertEndChild(TiXmlElement(
                        NodeName == _T("dialog") ? "wxDialog" :
                        NodeName == _T("frame")  ? "wxFrame" :
                                                   "wxPanel" ))->ToElement();

                    Res->SetAttribute("wxs",cbU2C(_T("wxsmith/")+cbC2U(Wxs)));
                    Res->SetAttribute("src",Src);
                    Res->SetAttribute("hdr",Hdr);
                    if ( Xrc ) Res->SetAttribute("xrc",Xrc);
                    Res->SetAttribute("name",Class);
                    Res->SetAttribute("language","CPP");

                    ConvertOldWxsFile(Project->GetProjectPath()+_T("wxsmith/")+cbC2U(Wxs),Xrc!=0);
                    AdoptOldSourceFile(Project->GetProjectPath()+cbC2U(Src),cbC2U(Class));
                }
            }
        }
    }
    return NewConfig;
}
Пример #5
0
bool CGUIWindow::Load(TiXmlElement *pRootElement)
{
  if (!pRootElement)
    return false;

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

  // now load in the skin file
  SetDefaults();

  CGUIControlFactory::GetInfoColor(pRootElement, "backgroundcolor", m_clearBackground, GetID());
  CGUIControlFactory::GetActions(pRootElement, "onload", m_loadActions);
  CGUIControlFactory::GetActions(pRootElement, "onunload", m_unloadActions);
  CRect parentRect(0, 0, static_cast<float>(m_coordsRes.iWidth), static_cast<float>(m_coordsRes.iHeight));
  CGUIControlFactory::GetHitRect(pRootElement, m_hitRect, parentRect);

  TiXmlElement *pChild = pRootElement->FirstChildElement();
  while (pChild)
  {
    std::string strValue = pChild->Value();
    if (strValue == "previouswindow" && pChild->FirstChild())
    {
      m_previousWindow = CWindowTranslator::TranslateWindow(pChild->FirstChild()->Value());
    }
    else if (strValue == "defaultcontrol" && pChild->FirstChild())
    {
      const char *always = pChild->Attribute("always");
      if (always && StringUtils::EqualsNoCase(always, "true"))
        m_defaultAlways = true;
      m_defaultControl = atoi(pChild->FirstChild()->Value());
    }
    else if(strValue == "menucontrol" && pChild->FirstChild())
    {
      m_menuControlID = atoi(pChild->FirstChild()->Value());
    }
    else if (strValue == "visible" && pChild->FirstChild())
    {
      std::string condition;
      CGUIControlFactory::GetConditionalVisibility(pRootElement, condition);
      m_visibleCondition = CServiceBroker::GetGUI()->GetInfoManager().Register(condition, GetID());
    }
    else if (strValue == "animation" && pChild->FirstChild())
    {
      CRect rect(0, 0, static_cast<float>(m_coordsRes.iWidth), static_cast<float>(m_coordsRes.iHeight));
      CAnimation anim;
      anim.Create(pChild, rect, GetID());
      m_animations.push_back(anim);
    }
    else if (strValue == "zorder" && pChild->FirstChild())
    {
      m_renderOrder = atoi(pChild->FirstChild()->Value());
    }
    else if (strValue == "coordinates")
    {
      XMLUtils::GetFloat(pChild, "posx", m_posX);
      XMLUtils::GetFloat(pChild, "posy", m_posY);
      XMLUtils::GetFloat(pChild, "left", m_posX);
      XMLUtils::GetFloat(pChild, "top", m_posY);

      TiXmlElement *originElement = pChild->FirstChildElement("origin");
      while (originElement)
      {
        COrigin origin;
        origin.x = CGUIControlFactory::ParsePosition(originElement->Attribute("x"), static_cast<float>(m_coordsRes.iWidth));
        origin.y = CGUIControlFactory::ParsePosition(originElement->Attribute("y"), static_cast<float>(m_coordsRes.iHeight));
        if (originElement->FirstChild())
          origin.condition = CServiceBroker::GetGUI()->GetInfoManager().Register(originElement->FirstChild()->Value(), GetID());
        m_origins.push_back(origin);
        originElement = originElement->NextSiblingElement("origin");
      }
    }
    else if (strValue == "camera")
    { // z is fixed
      m_camera.x = CGUIControlFactory::ParsePosition(pChild->Attribute("x"), static_cast<float>(m_coordsRes.iWidth));
      m_camera.y = CGUIControlFactory::ParsePosition(pChild->Attribute("y"), static_cast<float>(m_coordsRes.iHeight));
      m_hasCamera = true;
    }
    else if (strValue == "depth" && pChild->FirstChild())
    { 
      float stereo = static_cast<float>(atof(pChild->FirstChild()->Value()));
      m_stereo = std::max(-1.f, std::min(1.f, stereo));
    }
    else if (strValue == "controls")
    {
      TiXmlElement *pControl = pChild->FirstChildElement();
      while (pControl)
      {
        if (StringUtils::EqualsNoCase(pControl->Value(), "control"))
        {
          LoadControl(pControl, nullptr, CRect(0, 0, static_cast<float>(m_coordsRes.iWidth), static_cast<float>(m_coordsRes.iHeight)));
        }
        pControl = pControl->NextSiblingElement();
      }
    }

    pChild = pChild->NextSiblingElement();
  }

  return true;
}
Пример #6
0
bool CSiteManager::AddBookmark(wxString sitePath, const wxString& name, const wxString &local_dir, const CServerPath &remote_dir, bool sync)
{
	if (local_dir.empty() && remote_dir.IsEmpty())
		return false;

	if (sitePath[0] != '0')
		return false;

	sitePath = sitePath.Mid(1);

	// We have to synchronize access to sitemanager.xml so that multiple processed don't write
	// to the same file or one is reading while the other one writes.
	CInterProcessMutex mutex(MUTEX_SITEMANAGER);

	CXmlFile file;
	TiXmlElement* pDocument = 0;

	pDocument = file.Load(_T("sitemanager"));

	if (!pDocument)
	{
		wxString msg = file.GetError() + _T("\n") + _("The bookmark could not be added.");
		wxMessageBox(msg, _("Error loading xml file"), wxICON_ERROR);

		return false;
	}

	TiXmlElement* pElement = pDocument->FirstChildElement("Servers");
	if (!pElement)
		return false;

	std::list<wxString> segments;
	if (!UnescapeSitePath(sitePath, segments))
	{
		wxMessageBox(_("Site path is malformed."), _("Invalid site path"));
		return 0;
	}

	TiXmlElement* pChild = GetElementByPath(pElement, segments);
	if (!pChild || strcmp(pChild->Value(), "Server"))
	{
		wxMessageBox(_("Site does not exist."), _("Invalid site path"));
		return 0;
	}

	// Bookmarks
	TiXmlElement *pInsertBefore = 0;
	TiXmlElement* pBookmark;
	for (pBookmark = pChild->FirstChildElement("Bookmark"); pBookmark; pBookmark = pBookmark->NextSiblingElement("Bookmark"))
	{
		TiXmlHandle handle(pBookmark);

		wxString old_name = GetTextElement_Trimmed(pBookmark, "Name");
		if (old_name.empty())
			continue;

		if (name == old_name)
		{
			wxMessageBox(_("Name of bookmark already exists."), _("New bookmark"), wxICON_EXCLAMATION);
			return false;
		}
		if (name < old_name && !pInsertBefore)
			pInsertBefore = pBookmark;
	}

	if (pInsertBefore)
		pBookmark = pChild->InsertBeforeChild(pInsertBefore, TiXmlElement("Bookmark"))->ToElement();
	else
		pBookmark = pChild->LinkEndChild(new TiXmlElement("Bookmark"))->ToElement();
	AddTextElement(pBookmark, "Name", name);
	if (!local_dir.empty())
		AddTextElement(pBookmark, "LocalDir", local_dir);
	if (!remote_dir.IsEmpty())
		AddTextElement(pBookmark, "RemoteDir", remote_dir.GetSafePath());
	if (sync)
		AddTextElementRaw(pBookmark, "SyncBrowsing", "1");

	wxString error;
	if (!file.Save(&error))
	{
		if (COptions::Get()->GetOptionVal(OPTION_DEFAULT_KIOSKMODE) == 2)
			return true;

		wxString msg = wxString::Format(_("Could not write \"%s\", the selected sites could not be exported: %s"), file.GetFileName().GetFullPath().c_str(), error.c_str());
		wxMessageBox(msg, _("Error writing xml file"), wxICON_ERROR);
	}

	return true;
}
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;
}
Пример #8
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;
                    }
                }
            }
        }
    }
}
Пример #9
0
Module* XmlModLoader::parsXml(const char* szFile)
{
    module.clear();
    ErrorLogger* logger  = ErrorLogger::Instance();
    
    TiXmlDocument doc(szFile);
    if(!doc.LoadFile()) 
    {
        OSTRINGSTREAM err;
        err<<"Syntax error while loading "<<szFile<<" at line "\
           <<doc.ErrorRow()<<": ";
        err<<doc.ErrorDesc();
        logger->addError(err);
        return NULL;
    }
    
    /* retrieving root module */
    TiXmlElement *root = doc.RootElement();
    if(!root)    
    {
        OSTRINGSTREAM err;
        err<<"Syntax error while loading "<<szFile<<" . ";
        err<<"No root element.";
        logger->addError(err);
        return NULL;
    }
    
    if(!compareString(root->Value(), "module"))
    {
        /*
        OSTRINGSTREAM msg;
        msg<<szFile<<" is not a module descriptor file.";
        logger->addWarning(msg);
        */
        return NULL;
    }
    
    /* retrieving name */
    TiXmlElement* name = (TiXmlElement*) root->FirstChild("name");
    if(!name || !name->GetText())
    {
        OSTRINGSTREAM err;
        err<<"Module from "<<szFile<<" has no name.";
        logger->addError(err);      
        //return NULL;
    }

    module.setXmlFile(szFile);
    
    if(name)
        module.setName(name->GetText());

    /* retrieving description */
    TiXmlElement* desc;
    if((desc = (TiXmlElement*) root->FirstChild("description")))
        module.setDescription(desc->GetText());

    /* retrieving version */
    TiXmlElement* ver;
    if((ver = (TiXmlElement*) root->FirstChild("version")))
        module.setVersion(ver->GetText());


    /* retrieving parameter */
    TiXmlElement* arguments;
    if((arguments = (TiXmlElement*) root->FirstChild("arguments")))
        for(TiXmlElement* param = arguments->FirstChildElement(); param;
                param = param->NextSiblingElement())
        {
            if(compareString(param->Value(), "param"))
            {           
                if(param->GetText())
                {   
                    bool brequired = false;
                    if(compareString(param->Attribute("required"), "yes"))
                        brequired = true; 
                    Argument arg(param->GetText(), 
                                 brequired,
                                 param->Attribute("desc"));
                    arg.setDefault(param->Attribute("default"));
                    module.addArgument(arg);                 
                }
            }
            else
            if(compareString(param->Value(), "switch"))
            {           
                if(param->GetText())
                {   
                    bool brequired = false;
                    if(compareString(param->Attribute("required"), "yes"))
                        brequired = true; 
                    Argument arg(param->GetText(), 
                                 brequired,
                                 param->Attribute("desc"), true);
                    arg.setDefault(param->Attribute("default"));
                    module.addArgument(arg);                 
                }
            }                      
            else
            {
                OSTRINGSTREAM war;
                war<<"Unrecognized tag from "<<szFile<<" at line "\
                   <<param->Row()<<".";
                logger->addWarning(war);                                
            }
            
        }
    

    /* retrieving rank */
    TiXmlElement* rank;
    if((rank = (TiXmlElement*) root->FirstChild("rank")) &&
        rank->GetText())
        module.setRank(atoi(rank->GetText()));


    /* retrieving authors information*/
    TiXmlElement* authors;
    if((authors = (TiXmlElement*) root->FirstChild("authors")))
        for(TiXmlElement* ath = authors->FirstChildElement(); ath;
                ath = ath->NextSiblingElement())
        {
            if(compareString(ath->Value(), "author"))
            {
                Author author;
                if(ath->GetText())
                    author.setName(ath->GetText());
                if(ath->Attribute("email"))
                    author.setEmail(ath->Attribute("email"));
                module.addAuthor(author);
            }
            else
            {
                OSTRINGSTREAM war;
                war<<"Unrecognized tag from "<<szFile<<" at line "\
                   <<ath->Row()<<".";
                logger->addWarning(war);                                
            }
            
        }


   /* retrieving data */
    if(root->FirstChild("data"))
        for(TiXmlElement* data = root->FirstChild("data")->FirstChildElement();
            data; data = data->NextSiblingElement())
        {       
            /* output data */               
            if(compareString(data->Value(), "output"))
            {
                OutputData output;
                TiXmlElement* element;
                if((element = (TiXmlElement*) data->FirstChild("type")))
                    output.setName(element->GetText());
                else
                {
                    OSTRINGSTREAM war;
                    war<<"Output data from "<<szFile<<" at line "\
                       <<data->Row()<<" has no type.";
                    logger->addWarning(war);                
                }
                
                if((element = (TiXmlElement*) data->FirstChild("port")))
                {
                    output.setPort(element->GetText());                 
                    output.setCarrier(element->Attribute("carrier"));  
                }
                else
                {
                    OSTRINGSTREAM war;
                    war<<"Output data from "<<szFile<<" at line "\
                       <<data->Row()<<" has no port.";
                    logger->addWarning(war);                
                }
                
                if((element = (TiXmlElement*) data->FirstChild("description")))
                    output.setDescription(element->GetText());

                module.addOutput(output);
            } // end of output data         

            /* input data */                
            if(compareString(data->Value(), "input"))
            {                   
                InputData input;
                
                TiXmlElement* element;
                if((element = (TiXmlElement*) data->FirstChild("type")))
                    input.setName(element->GetText());
                else
                {
                    OSTRINGSTREAM war;
                    war<<"Input data from "<<szFile<<" at line "\
                       <<data->Row()<<" has no type.";
                    logger->addWarning(war);                
                }
                
                if((element = (TiXmlElement*) data->FirstChild("port")))
                {
                    input.setPort(element->GetText());                  
                    input.setCarrier(element->Attribute("carrier"));
                }
                else
                {
                    OSTRINGSTREAM war;
                    war<<"Input data from "<<szFile<<" at line "\
                       <<data->Row()<<" has no port.";
                    logger->addWarning(war);                
                }
                
                if((element = (TiXmlElement*) data->FirstChild("description")))
                    input.setDescription(element->GetText());

                if((element = (TiXmlElement*) data->FirstChild("required")))
                    if(compareString(element->GetText(), "yes"))
                        input.setRequired(true);

                if((element = (TiXmlElement*) data->FirstChild("priority")))
                    if(compareString(element->GetText(), "yes"))
                        input.setPriority(true);
                
                module.addInput(input);
            } // end of input data          

        }

    /* retrieving broker*/
    TiXmlElement* element;
    if((element = (TiXmlElement*) root->FirstChild("deployer")))
    {
        module.setBroker(element->GetText());
        module.setNeedDeployer(true);
    }

    /* retrieving dependencies*/
    if(root->FirstChild("dependencies"))
        for(TiXmlElement* restag = root->FirstChild("dependencies")->FirstChildElement();
            restag; restag = restag->NextSiblingElement())
        {
            Computer computer;
            if(compareString(restag->Value(), "computer"))
            {
                Computer computer;
                computer.setXmlFile(szFile);
                for(TiXmlElement* comptag = restag->FirstChildElement();
                    comptag; comptag = comptag->NextSiblingElement())
                {      
                     /* retrieving name */
                    if(compareString(comptag->Value(), "name"))                               
                        computer.setName(comptag->GetText());

                    /* retrieving description */
                     if(compareString(comptag->Value(), "description"))                  
                        computer.setDescription(comptag->GetText());

                    // platform
                    if(compareString(comptag->Value(), "platform"))
                    {
                        Platform os;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("name")))
                            os.setName(element->GetText());               
                        if((element = (TiXmlElement*) comptag->FirstChild("distribution")))
                            os.setDistribution(element->GetText());                
                        if((element = (TiXmlElement*) comptag->FirstChild("release")))
                            os.setRelease(element->GetText()); 
                        computer.setPlatform(os);
                    } // end of platform tag
                
                    /*
                    //multiplatform
                    if(compareString(comptag->Value(), "multiplatform"))
                    {
                        MultiPlatform mltPlatform;
                        for(TiXmlElement* mptag = comptag->FirstChild("multiplatform")->FirstChildElement();
                            mptag; mptag = mptag->NextSiblingElement())
                        {
                            // platform
                            if(compareString(mptag->Value(), "platform"))
                            {
                                Platform os;
                                TiXmlElement* element;
                                if((element = (TiXmlElement*) mptag->FirstChild("name")))
                                    os.setName(element->GetText());               
                                if((element = (TiXmlElement*) mptag->FirstChild("distribution")))
                                    os.setDistribution(element->GetText());            
                                if((element = (TiXmlElement*) mptag->FirstChild("release")))
                                    os.setDistribution(element->GetText());
                                mltPlatform.addPlatform(os);
                            } 
                        }
                        module.addResource(mltPlatform);
                    }
                    // end of multiplatform tag 
                    */
                    // memory
                    if(compareString(comptag->Value(), "memory"))
                    {
                        Memory mem;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("total_space")))
                            mem.setTotalSpace((Capacity)atol(element->GetText()));               
                        if((element = (TiXmlElement*) comptag->FirstChild("free_space")))
                            mem.setFreeSpace((Capacity)atol(element->GetText()));                   
                        computer.setMemory(mem);                    
                    } // end of memory tag

                    // storage
                    if(compareString(comptag->Value(), "storage"))
                    {
                        Storage stg;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("total_space")))
                            stg.setTotalSpace((Capacity)atol(element->GetText()));               
                        if((element = (TiXmlElement*) comptag->FirstChild("free_space")))
                            stg.setFreeSpace((Capacity)atol(element->GetText()));                   
                        computer.setStorage(stg);
                    } // end of storage tag

                    // processor
                    if(compareString(comptag->Value(), "processor"))
                    {
                        Processor proc;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("architecture")))
                            proc.setArchitecture(element->GetText());
                        if((element = (TiXmlElement*) comptag->FirstChild("model")))
                            proc.setModel(element->GetText());
                        if((element = (TiXmlElement*) comptag->FirstChild("cores")))
                            proc.setCores((size_t)atoi(element->GetText()));               
                        if((element = (TiXmlElement*) comptag->FirstChild("siblings")))
                            proc.setSiblings((size_t)atoi(element->GetText()));                                           
                        if((element = (TiXmlElement*) comptag->FirstChild("frequency")))
                            proc.setFrequency(atof(element->GetText()));
                        computer.setProcessor(proc);
                    } // end of processor tag

                    // network
                    if(compareString(comptag->Value(), "network"))
                    {
                        Network net;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("ip4")))
                            net.setIP4(element->GetText());
                        if((element = (TiXmlElement*) comptag->FirstChild("ip6")))
                            net.setIP6(element->GetText());
                        if((element = (TiXmlElement*) comptag->FirstChild("mac")))
                            net.setMAC(element->GetText());
                        module.addResource(net);
                        computer.setNetwork(net);
                    } // end of network tag

                    // yarp_port
                    if(compareString(comptag->Value(), "yarp_port"))
                    {
                        ResYarpPort yport;
                        TiXmlElement* element = (TiXmlElement*) comptag->FirstChild("name");
                        if(element && element->GetText())
                        {
                            yport.setName(element->GetText());
                            yport.setPort(element->GetText());
                            computer.addPeripheral(yport);
                        }
                        else
                        {
                            OSTRINGSTREAM war;
                            war<<"yarp_port from "<<szFile<<" at line " <<comptag->Row()<<" has no name.";
                            logger->addWarning(war);
                        }                            
                    }

                    // gpu
                    if(compareString(comptag->Value(), "gpu"))
                    {
                        GPU gpu;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("name")))
                            gpu.setName(element->GetText());
                        if((element = (TiXmlElement*) comptag->FirstChild("capability")))
                            gpu.setCompCompatibility(element->GetText());
                        if((element = (TiXmlElement*) comptag->FirstChild("cores")))
                            gpu.setCores((size_t)atoi(element->GetText()));
                        if((element = (TiXmlElement*) comptag->FirstChild("frequency")))
                            gpu.setFrequency(atof(element->GetText()));
                        if((element = (TiXmlElement*) comptag->FirstChild("register_block")))
                            gpu.setResgisterPerBlock((size_t)atoi(element->GetText()));
                        if((element = (TiXmlElement*) comptag->FirstChild("thread_block")))
                            gpu.setThreadPerBlock((size_t)atoi(element->GetText()));
                        if((element = (TiXmlElement*) comptag->FirstChild("overlap")))
                        {
                            if(compareString(element->GetText(), "yes"))
                                gpu.setOverlap(true);
                            else
                                gpu.setOverlap(false);
                        }


                        // global memory
                        if(comptag->FirstChild("global_memory"))
                        {
                            TiXmlElement* element;
                            element = (TiXmlElement*) comptag->FirstChild("global_memory");
                            if((element = (TiXmlElement*) element->FirstChild("total_space")))
                                gpu.setGlobalMemory((Capacity)atol(element->GetText()));            
                        } // end of global memory tag

                        // shared memory
                        if(comptag->FirstChild("shared_memory"))
                        {
                            TiXmlElement* element;
                            element = (TiXmlElement*) comptag->FirstChild("shared_memory");
                            if((element = (TiXmlElement*) element->FirstChild("total_space")))
                                gpu.setSharedMemory((Capacity)atol(element->GetText()));            
                        } // end of shared memory tag

                        // constant memory
                        if(comptag->FirstChild("constant_memory"))
                        {
                            TiXmlElement* element;
                            element = (TiXmlElement*) comptag->FirstChild("constant_memory");
                            if((element = (TiXmlElement*) element->FirstChild("total_space")))
                                gpu.setConstantMemory((Capacity)atol(element->GetText()));            
                        } // end of shared memory tag
                        computer.addPeripheral(gpu);
                    } // end of gpu tag
                } // end of computer tag loop            
                module.addResource(computer);
            } //end of if computer tag
        }// end of dependecnies tag 

    return &module;
}
Пример #10
0
bool LoadPrefs()
{
    if (prefLoaded) // already attempted loading
        return true;

    char filepath[MAXPATHLEN];
    sprintf(filepath, "%s/%s", MPLAYER_DATADIR, PREF_FILE_NAME);

    TiXmlDocument doc;

    bool loadOkay = doc.LoadFile(filepath);
    if (loadOkay) {
        FixInvalidSettings();
        TiXmlHandle docu(&doc);
        TiXmlElement* settings = docu.FirstChildElement().Element();
        if (settings == NULL) {
            goto noheader;
        }
        TiXmlHandle handle(0);
        TiXmlElement* elem;
        handle = TiXmlHandle(settings);
        elem = handle.FirstChild("global").FirstChild().Element();
        for (elem; elem; elem = elem->NextSiblingElement()) {
            const char* elemName = elem->Value();
            if (strcmp(elemName, "exit") == 0) {
                XMPlayerCfg.exit_action = atoi(elem->Attribute("value"));
            } else if (strcmp(elemName, "language") == 0) {
                XMPlayerCfg.language = atoi(elem->Attribute("value"));
            }
        }
        elem = handle.FirstChild("filebrowser").FirstChild().Element();
        for (elem; elem; elem = elem->NextSiblingElement()) {
            const char* elemName = elem->Value();
            if (strcmp(elemName, "sort") == 0) {
                XMPlayerCfg.sort_order = atoi(elem->Attribute("value"));
            }
        }
        elem = handle.FirstChild("audio").FirstChild().Element();
        for (elem; elem; elem = elem->NextSiblingElement()) {
            const char* elemName = elem->Value();
            if (strcmp(elemName, "language") == 0) {
                sprintf(XMPlayerCfg.alang, elem->Attribute("value"));
                sprintf(XMPlayerCfg.alang_desc, elem->Attribute("desc"));
            } else if (strcmp(elemName, "volume") == 0) {
                XMPlayerCfg.volume = atoi(elem->Attribute("value"));
            } else if (strcmp(elemName, "softvol") == 0) {
                XMPlayerCfg.softvol = atoi(elem->Attribute("value"));
            }
        }
        elem = handle.FirstChild("video").FirstChild().Element();
        for (elem; elem; elem = elem->NextSiblingElement()) {
            const char* elemName = elem->Value();
            if (strcmp(elemName, "framedrop") == 0) {
                XMPlayerCfg.framedrop = atoi(elem->Attribute("value"));
            } else if (strcmp(elemName, "vsync") == 0) {
                XMPlayerCfg.vsync = atoi(elem->Attribute("value"));
            }
        }
        elem = handle.FirstChild("subtitles").FirstChild().Element();
        for (elem; elem; elem = elem->NextSiblingElement()) {
            const char* elemName = elem->Value();
            if (strcmp(elemName, "sub_color") == 0) {
                elem->Attribute("value", &XMPlayerCfg.subcolor);
            } else if (strcmp(elemName, "border_color") == 0) {
                elem->Attribute("value", &XMPlayerCfg.border_color);
            } else if (strcmp(elemName, "codepage") == 0) {
                sprintf(XMPlayerCfg.subcp, elem->Attribute("value"));
                sprintf(XMPlayerCfg.subcp_desc, elem->Attribute("desc"));
            } else if (strcmp(elemName, "language") == 0) {
                sprintf(XMPlayerCfg.sublang, elem->Attribute("value"));
                sprintf(XMPlayerCfg.sublang_desc, elem->Attribute("desc"));
            }
        }
        doc.Clear();
        prefLoaded = true;

        printf("[Preferences] Sucessfully loaded xmplayer.xml \n");
        return true;

    } else {
noheader:
        DefaultSettings();
        printf("[Preferences] Failed to load xmplayer.xml - Loading default settings \n");
        return false;
    }

}
Пример #11
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; 
		}
	}
}
Пример #12
0
int LoadScene(const char *filename)
{
    TiXmlDocument doc(filename);
    if ( ! doc.LoadFile() ) {
        printf("Failed to load the file \"%s\"\n", filename);
        return 0;
    }
    
    TiXmlElement *xml = doc.FirstChildElement("xml");
    if ( ! xml ) {
        printf("No \"xml\" tag found.\n");
        return 0;
    }
    
    TiXmlElement *scene = xml->FirstChildElement("scene");
    if ( ! scene ) {
        printf("No \"scene\" tag found.\n");
        return 0;
    }
    
    TiXmlElement *cam = xml->FirstChildElement("camera");
    if ( ! cam ) {
        printf("No \"camera\" tag found.\n");
        return 0;
    }
    
    nodeMtlList.clear();
    rootNode.Init();
    materials.DeleteAll();
    lights.DeleteAll();
    objList.Clear();
    textureList.Clear();
    LoadScene( scene );
    
    rootNode.ComputeChildBoundBox();
    
    // Assign materials
    int numNodes = nodeMtlList.size();
    for ( int i=0; i<numNodes; i++ ) {
        Material *mtl = materials.Find( nodeMtlList[i].mtlName );
        if ( mtl ) nodeMtlList[i].node->SetMaterial(mtl);
    }
    nodeMtlList.clear();
    
    // Load Camera
    camera.Init();
    camera.dir += camera.pos;
    TiXmlElement *camChild = cam->FirstChildElement();
    while ( camChild ) {
        if      ( COMPARE( camChild->Value(), "position"  ) ) ReadVector(camChild,camera.pos);
        else if ( COMPARE( camChild->Value(), "target"    ) ) ReadVector(camChild,camera.dir);
        else if ( COMPARE( camChild->Value(), "up"        ) ) ReadVector(camChild,camera.up);
        else if ( COMPARE( camChild->Value(), "fov"       ) ) ReadFloat (camChild,camera.fov);
        else if ( COMPARE( camChild->Value(), "width"     ) ) camChild->QueryIntAttribute("value", &camera.imgWidth);
        else if ( COMPARE( camChild->Value(), "height"    ) ) camChild->QueryIntAttribute("value", &camera.imgHeight);
        camChild = camChild->NextSiblingElement();
    }
    camera.dir -= camera.pos;
    camera.dir.Normalize();
    Point3 x = camera.dir ^ camera.up;
    camera.up = (x ^ camera.dir).GetNormalized();
    
    renderImage.Init( camera.imgWidth, camera.imgHeight );
    
    return 1;
}
Пример #13
0
void LoadLight(TiXmlElement *element)
{
    Light *light = NULL;
    
    // name
    const char* name = element->Attribute("name");
    printf("Light [");
    if ( name ) printf("%s",name);
    printf("]");
    
    // type
    const char* type = element->Attribute("type");
    if ( type ) {
        if ( COMPARE(type,"ambient") ) {
            printf(" - Ambient\n");
            AmbientLight *l = new AmbientLight();
            light = l;
            for ( TiXmlElement *child = element->FirstChildElement(); child!=NULL; child = child->NextSiblingElement() ) {
                if ( COMPARE( child->Value(), "intensity" ) ) {
                    Color c(1,1,1);
                    ReadColor( child, c );
                    l->SetIntensity(c);
                    printf("   intensity %f %f %f\n",c.r,c.g,c.b);
                }
            }
        } else if ( COMPARE(type,"direct") ) {
            printf(" - Direct\n");
            DirectLight *l = new DirectLight();
            light = l;
            for ( TiXmlElement *child = element->FirstChildElement(); child!=NULL; child = child->NextSiblingElement() ) {
                if ( COMPARE( child->Value(), "intensity" ) ) {
                    Color c(1,1,1);
                    ReadColor( child, c );
                    l->SetIntensity(c);
                    printf("   intensity %f %f %f\n",c.r,c.g,c.b);
                } else if ( COMPARE( child->Value(), "direction" ) ) {
                    Point3 v(1,1,1);
                    ReadVector( child, v );
                    l->SetDirection(v);
                    printf("   direction %f %f %f\n",v.x,v.y,v.z);
                }
            }
        } else if ( COMPARE(type,"point") ) {
            printf(" - Point\n");
            PointLight *l = new PointLight();
            light = l;
            for ( TiXmlElement *child = element->FirstChildElement(); child!=NULL; child = child->NextSiblingElement() ) {
                if ( COMPARE( child->Value(), "intensity" ) ) {
                    Color c(1,1,1);
                    ReadColor( child, c );
                    l->SetIntensity(c);
                    printf("   intensity %f %f %f\n",c.r,c.g,c.b);
                } else if ( COMPARE( child->Value(), "position" ) ) {
                    Point3 v(0,0,0);
                    ReadVector( child, v );
                    l->SetPosition(v);
                    printf("   position %f %f %f\n",v.x,v.y,v.z);
                }
            }
        } else {
            printf(" - UNKNOWN\n");
        }
    }
    
    if ( light ) {
        light->SetName(name);
        lights.push_back(light);
    }
    
}
Пример #14
0
void LoadMaterial(TiXmlElement *element)
{
    Material *mtl = NULL;
    
    // name
    const char* name = element->Attribute("name");
    printf("Material [");
    if ( name ) printf("%s",name);
    printf("]");
    
    // type
    const char* type = element->Attribute("type");
    if ( type ) {
        if ( COMPARE(type,"blinn") ) {
            printf(" - Blinn\n");
            MtlBlinn *m = new MtlBlinn();
            mtl = m;
            for ( TiXmlElement *child = element->FirstChildElement(); child!=NULL; child = child->NextSiblingElement() ) {
                Color c(1,1,1);
                float f=1;
                if ( COMPARE( child->Value(), "diffuse" ) ) {
                    ReadColor( child, c );
                    m->SetDiffuse(c);
                    printf("   diffuse %f %f %f\n",c.r,c.g,c.b);
                    m->SetDiffuseTexture( ReadTexture(child) );
                } else if ( COMPARE( child->Value(), "specular" ) ) {
                    ReadColor( child, c );
                    m->SetSpecular(c);
                    printf("   specular %f %f %f\n",c.r,c.g,c.b);
                    m->SetSpecularTexture( ReadTexture(child) );
                } else if ( COMPARE( child->Value(), "glossiness" ) ) {
                    ReadFloat( child, f );
                    m->SetGlossiness(f);
                    printf("   glossiness %f\n",f);
                } else if ( COMPARE( child->Value(), "reflection" ) ) {
                    ReadColor( child, c );
                    m->SetReflection(c);
                    printf("   reflection %f %f %f\n",c.r,c.g,c.b);
                    m->SetReflectionTexture( ReadTexture(child) );
                } else if ( COMPARE( child->Value(), "refraction" ) ) {
                    ReadColor( child, c );
                    m->SetRefraction(c);
                    ReadFloat( child, f, "index" );
                    m->SetRefractionIndex(f);
                    printf("   refraction %f %f %f (index %f)\n",c.r,c.g,c.b,f);
                    m->SetRefractionTexture( ReadTexture(child) );
                } else if ( COMPARE( child->Value(), "absorption" ) ) {
                    ReadColor( child, c );
                    m->SetAbsorption(c);
                    printf("   absorption %f %f %f\n",c.r,c.g,c.b);
                }
            }
        } else {
            printf(" - UNKNOWN\n");
        }
    }
    
    if ( mtl ) {
        mtl->SetName(name);
        materials.push_back(mtl);
    }
}
Пример #15
0
CSiteManagerItemData_Site* CSiteManager::GetSiteByPath(wxString sitePath)
{
	wxChar c = sitePath[0];
	if (c != '0' && c != '1')
	{
		wxMessageBox(_("Site path has to begin with 0 or 1."), _("Invalid site path"));
		return 0;
	}

	sitePath = sitePath.Mid(1);

	// We have to synchronize access to sitemanager.xml so that multiple processed don't write
	// to the same file or one is reading while the other one writes.
	CInterProcessMutex mutex(MUTEX_SITEMANAGER);

	CXmlFile file;
	TiXmlElement* pDocument = 0;

	if (c == '0')
		pDocument = file.Load(_T("sitemanager"));
	else
	{
		const wxString& defaultsDir = wxGetApp().GetDefaultsDir();
		if (defaultsDir == _T(""))
		{
			wxMessageBox(_("Site does not exist."), _("Invalid site path"));
			return 0;
		}
		wxFileName name(defaultsDir, _T("fzdefaults.xml"));
		pDocument = file.Load(name);
	}

	if (!pDocument)
	{
		wxMessageBox(file.GetError(), _("Error loading xml file"), wxICON_ERROR);

		return 0;
	}

	TiXmlElement* pElement = pDocument->FirstChildElement("Servers");
	if (!pElement)
	{
		wxMessageBox(_("Site does not exist."), _("Invalid site path"));
		return 0;
	}

	std::list<wxString> segments;
	if (!UnescapeSitePath(sitePath, segments))
	{
		wxMessageBox(_("Site path is malformed."), _("Invalid site path"));
		return 0;
	}

	TiXmlElement* pChild = GetElementByPath(pElement, segments);
	if (!pChild)
	{
		wxMessageBox(_("Site does not exist."), _("Invalid site path"));
		return 0;
	}

	TiXmlElement* pBookmark;
	if (!strcmp(pChild->Value(), "Bookmark"))
	{
		pBookmark = pChild;
		pChild = pChild->Parent()->ToElement();
	}
	else
		pBookmark = 0;

	CSiteManagerItemData_Site* data = ReadServerElement(pChild);

	if (!data)
	{
		wxMessageBox(_("Could not read server item."), _("Invalid site path"));
		return 0;
	}

	if (pBookmark)
	{
		TiXmlHandle handle(pBookmark);

		wxString localPath;
		CServerPath remotePath;
		TiXmlText* localDir = handle.FirstChildElement("LocalDir").FirstChild().Text();
		if (localDir)
			localPath = ConvLocal(localDir->Value());
		TiXmlText* remoteDir = handle.FirstChildElement("RemoteDir").FirstChild().Text();
		if (remoteDir)
			remotePath.SetSafePath(ConvLocal(remoteDir->Value()));
		if (!localPath.empty() && !remotePath.IsEmpty())
		{
			data->m_sync = GetTextElementBool(pBookmark, "SyncBrowsing", false);
		}
		else
			data->m_sync = false;

		data->m_localDir = localPath;
		data->m_remoteDir = remotePath;
	}

	return data;
}
// 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;
}
Пример #17
0
bool CSiteManager::GetBookmarks(wxString sitePath, std::list<wxString> &bookmarks)
{
	wxChar c = sitePath[0];
	if (c != '0' && c != '1')
		return false;

	sitePath = sitePath.Mid(1);

	// We have to synchronize access to sitemanager.xml so that multiple processed don't write
	// to the same file or one is reading while the other one writes.
	CInterProcessMutex mutex(MUTEX_SITEMANAGER);

	CXmlFile file;
	TiXmlElement* pDocument = 0;

	if (c == '0')
		pDocument = file.Load(_T("sitemanager"));
	else
	{
		const wxString& defaultsDir = wxGetApp().GetDefaultsDir();
		if (defaultsDir == _T(""))
			return false;
		pDocument = file.Load(wxFileName(defaultsDir, _T("fzdefaults.xml")));
	}

	if (!pDocument)
	{
		wxMessageBox(file.GetError(), _("Error loading xml file"), wxICON_ERROR);

		return false;
	}

	TiXmlElement* pElement = pDocument->FirstChildElement("Servers");
	if (!pElement)
		return false;

	std::list<wxString> segments;
	if (!UnescapeSitePath(sitePath, segments))
	{
		wxMessageBox(_("Site path is malformed."), _("Invalid site path"));
		return 0;
	}

	TiXmlElement* pChild = GetElementByPath(pElement, segments);
	if (!pChild || strcmp(pChild->Value(), "Server"))
		return 0;

	// Bookmarks
	for (TiXmlElement* pBookmark = pChild->FirstChildElement("Bookmark"); pBookmark; pBookmark = pBookmark->NextSiblingElement("Bookmark"))
	{
		TiXmlHandle handle(pBookmark);

		wxString name = GetTextElement_Trimmed(pBookmark, "Name");
		if (name.empty())
			continue;

		wxString localPath;
		CServerPath remotePath;
		TiXmlText* localDir = handle.FirstChildElement("LocalDir").FirstChild().Text();
		if (localDir)
			localPath = ConvLocal(localDir->Value());
		TiXmlText* remoteDir = handle.FirstChildElement("RemoteDir").FirstChild().Text();
		if (remoteDir)
			remotePath.SetSafePath(ConvLocal(remoteDir->Value()));

		if (localPath.empty() && remotePath.IsEmpty())
			continue;

		bookmarks.push_back(name);		
	}

	return true;
}
Пример #18
0
Tower::Tower(const string &towerName)
{
	//Default Initializers
	mTowerDirName = towerName;
	PspIO::lowerCase(mTowerDirName);

	mIsBuildable = true;
	mTowerName = NULL;
	mTowerDescription = NULL;
	mProjectileType = PT_Arrow;
	mHitsLand = false;
	mHitsFlyer = false;
	mTowerLength = 0;
	mMenuIcon = NULL;
	mTowerImg = NULL;
	mProjectileImg = NULL;
	mFireSound = NULL;
	mHitSound = NULL;

	char temp[256];
	sprintf(temp, "%s/Res/towers/%s/tower.xml", PspIO::getCurrentDirectory().c_str(), mTowerDirName.c_str());

	TiXmlDocument TowerXMLInput;
	TowerXMLInput.LoadFile(temp);

	if (TowerXMLInput.Error())
	{
		oslFatalError("Cannot open: %s", TowerXMLInput.ErrorDesc());
		return;
	}

	TiXmlElement *node = NULL;
	node = TowerXMLInput.FirstChildElement(); //head

	if (!node)
	{
		oslFatalError("No head node in: %s", temp);
		return;
	}

	node = node->FirstChildElement();

	while (node != NULL) //Read all XML file
	{
		string mCurrentLine = node->ValueStr();
		/*
		A função strdup() é usada em situações onde temos que alocar um espaço na memória para copiar determinada string.
		Sem utiliza-lá, teríamos que alocar o espaço antes com malloc(), para em seguida usar strncpy(), por exemplo, para copiar a string.
		A função retorna um ponteiro com a string já alocada (podendo ser liberado com free() depois de seu uso) em caso de sucesso,
		ou ENOMEM como erro caso a memória não tenha sida alocada por insuficiência.		
		*/
		if (mCurrentLine == "Name")
		{
			mTowerName = strdup(node->GetText());
		}
		else if (mCurrentLine == "Description")
		{
			mTowerDescription = strdup(node->GetText());
		}
		/*
		A função atoi() é usada para converter strings em números inteiros.
		*/
		else if (mCurrentLine == "TowerLength")
		{
			mTowerLength = atoi(node->GetText());
		}
		else if (mCurrentLine == "Capability")
		{
			const char* mAttributeText;

			mAttributeText = node->Attribute("HitsLand");
			if (mAttributeText != NULL && !strcmp(mAttributeText,"True")) //strcmp() return 0 if both string be the same.
			{
				mHitsLand = true;
			}

			mAttributeText = node->Attribute("HitsFlyers");
			if (mAttributeText != NULL && !strcmp(mAttributeText,"True")) //strcmp() return 0 if both string be the same.
			{
				mHitsFlyer = true;
			}
		}
		else if (mCurrentLine == "Projectile")
		{
			const char* ProjectileType = node->Attribute("Type");
			if (ProjectileType == NULL)
			{
				oslFatalError("No ProjectileType.");
				return;
			}
			//More Projectile Types goes here.
			if (!strcmp(ProjectileType, "Arrow"))
			{
				mProjectileType = PT_Arrow;
			}
			else if (!strcmp(ProjectileType, "Ice"))
			{
				mProjectileType = PT_Ice;
			}
			else if (!strcmp(ProjectileType, "Fire"))
			{
				mProjectileType = PT_Fire;
			}
			else if (!strcmp(ProjectileType, "Lightning"))
			{
				mProjectileType = PT_Lightning;
			}

			sprintf(temp, "/Res/towers/%s/%s", mTowerDirName.c_str(), node->Attribute("Sprite"));
			mProjectileImg = ProjectileInstance::LoadProjectileImage(mProjectileType, temp);
		}
		else if (mCurrentLine == "TowersLevels")
		{
			TiXmlElement *TowerLevelNode = node->FirstChildElement();
			while (TowerLevelNode != NULL) //read all Towers Levels
			{
				if (TowerLevelNode->ValueStr() != "TowersLevel")
				{
					oslFatalError("TowersLevel Error: %s",TowerLevelNode->Value());
					return;
				}
				mTowerVector.push_back(TowerInfo(TowerLevelNode)); //Insert a element in the end

				TowerLevelNode = TowerLevelNode->NextSiblingElement();
			}
		}
		else if (mCurrentLine == "TowerImg")
		{
			sprintf(temp, "/Res/towers/%s/%s", mTowerDirName.c_str(), node->Attribute("File"));
			mTowerImg = oslLoadImageFilePNG(temp, OSL_IN_RAM | OSL_SWIZZLED, OSL_PF_8888);

			mTowerImg->centerX = (mTowerImg->sizeX/2); //hotspot
			mTowerImg->centerY = (mTowerImg->sizeY/2); //hotspot

			node->QueryIntAttribute("Width", &mTowerWidth);
			node->QueryIntAttribute("Height", &mTowerHeight);
		}
		else if (mCurrentLine == "MenuIcon")
		{
			sprintf(temp, "/Res/towers/%s/%s", mTowerDirName.c_str(), node->Attribute("File"));
			mMenuIcon = oslLoadImageFilePNG(temp, OSL_IN_RAM | OSL_SWIZZLED, OSL_PF_8888);
		}
		else if (mCurrentLine == "FireSound")
		{
			sprintf(temp, "/Res/towers/%s/%s", mTowerDirName.c_str(), node->Attribute("File"));
			mFireSound = oslLoadSoundFileWAV (temp, OSL_FMT_NONE);
		}
		else if (mCurrentLine == "HitSound")
		{
			sprintf(temp, "/Res/towers/%s/%s", mTowerDirName.c_str(), node->Attribute("File"));
			mHitSound = oslLoadSoundFileWAV (temp, OSL_FMT_NONE);
		}
		else
		{
			oslFatalError("Bad node, not donout for you: %s",mCurrentLine.c_str());
			return;
		}
		node = node->NextSiblingElement();
	}
}
Пример #19
0
bool CSiteManager::ClearBookmarks(wxString sitePath)
{
	if (sitePath[0] != '0')
		return false;

	sitePath = sitePath.Mid(1);

	// We have to synchronize access to sitemanager.xml so that multiple processed don't write
	// to the same file or one is reading while the other one writes.
	CInterProcessMutex mutex(MUTEX_SITEMANAGER);

	CXmlFile file;
	TiXmlElement* pDocument = 0;

	pDocument = file.Load(_T("sitemanager"));

	if (!pDocument)
	{
		wxString msg = file.GetError() + _T("\n") + _("The bookmarks could not be cleared.");
		wxMessageBox(msg, _("Error loading xml file"), wxICON_ERROR);

		return false;
	}

	TiXmlElement* pElement = pDocument->FirstChildElement("Servers");
	if (!pElement)
		return false;

	std::list<wxString> segments;
	if (!UnescapeSitePath(sitePath, segments))
	{
		wxMessageBox(_("Site path is malformed."), _("Invalid site path"));
		return 0;
	}

	TiXmlElement* pChild = GetElementByPath(pElement, segments);
	if (!pChild || strcmp(pChild->Value(), "Server"))
	{
		wxMessageBox(_("Site does not exist."), _("Invalid site path"));
		return 0;
	}

	TiXmlElement *pBookmark = pChild->FirstChildElement("Bookmark");
	while (pBookmark)
	{
		pChild->RemoveChild(pBookmark);
		pBookmark = pChild->FirstChildElement("Bookmark");
	}

	wxString error;
	if (!file.Save(&error))
	{
		if (COptions::Get()->GetOptionVal(OPTION_DEFAULT_KIOSKMODE) == 2)
			return true;

		wxString msg = wxString::Format(_("Could not write \"%s\", the selected sites could not be exported: %s"), file.GetFileName().GetFullPath().c_str(), error.c_str());
		wxMessageBox(msg, _("Error writing xml file"), wxICON_ERROR);
	}

	return true;
}
Пример #20
0
void wxsProject::ReadConfiguration(TiXmlElement* element)
{
    TiXmlElement* SmithNode = element->FirstChildElement("wxsmith");
    if ( !SmithNode ) return;

    TiXmlDocument TempDoc;

    // Checking version
    if ( wxsVersionConverter::Get().DetectOldConfig(SmithNode,this) )
    {
        TiXmlElement* ConvertedSmithNode = wxsVersionConverter::Get().ConvertFromOldConfig(SmithNode,&TempDoc,this);
        if ( !ConvertedSmithNode )
        {
            for ( TiXmlNode* Node = SmithNode->FirstChild(); Node; Node=Node->NextSibling() )
            {
                m_UnknownConfig.InsertEndChild(*Node);
            }
            return;
        }
        else
        {
            SmithNode = ConvertedSmithNode;
            m_WasModifiedDuringLoad = true;
        }
    }

    const char* VersionStr = SmithNode->Attribute("version");
    int Version = VersionStr ? atoi(VersionStr) : 1;

    if ( Version > CurrentVersion )
    {
        // TODO: Show some dialog box that resources were created by newer version,
        //       store all configuration for later save and return
        return;
    }

    if ( Version < CurrentVersion )
    {
        SmithNode = wxsVersionConverter::Get().Convert(SmithNode,&TempDoc,this);
        if ( !SmithNode )
        {
            // TODO: Show some dialog box that resources were created by newer version,
            //       store all configuration for later save and return
            return;
        }
        else
        {
            m_WasModifiedDuringLoad = true;
        }
    }

    // Iterating through elements
    for ( TiXmlElement* Node = SmithNode->FirstChildElement(); Node; Node=Node->NextSiblingElement() )
    {
        wxString NodeValue = cbC2U(Node->Value());
        if ( NodeValue == _T("gui") )
        {
            wxString GUIName = cbC2U(Node->Attribute("name"));
            wxsGUI* NewGUI = wxsGUIFactory::Build(GUIName,this);
            if ( !NewGUI )
            {
                m_UnknownConfig.InsertEndChild(*Node);
            }
            else
            {
                delete m_GUI;
                m_GUI = NewGUI;
                if ( NewGUI )
                {
                    NewGUI->ReadConfig(Node);
                }
            }
        }
        else if ( NodeValue == _T("resources") )
        {
            for ( TiXmlElement* ResNode = Node->FirstChildElement(); ResNode; ResNode = ResNode->NextSiblingElement() )
            {
                wxString Type = cbC2U(ResNode->Value());
                wxsResource* Res = wxsResourceFactory::Build(Type,this);

                if ( Res )
                {
                    // Storing unknown Xml Element
                    if ( !Res->ReadConfig(ResNode) )
                    {
                        m_UnknownResources.InsertEndChild(*ResNode);
                        delete Res;
                    }
                    else
                    {
                        m_Resources.Add(Res);
                        Res->BuildTreeEntry(GetResourceTypeTreeId(Type));
                    }
                }
                else
                {
                    m_UnknownResources.InsertEndChild(*ResNode);
                }
            }
        }
        else
        {
            m_UnknownConfig.InsertEndChild(*Node);
        }
    }
}
Пример #21
0
Application* XmlAppLoader::parsXml(const char* szFile)
{
    app.clear();

    ErrorLogger* logger  = ErrorLogger::Instance();

    TiXmlDocument doc(szFile);
    if(!doc.LoadFile())
    {
        OSTRINGSTREAM err;
        err<<"Syntax error while loading "<<szFile<<" at line "\
           <<doc.ErrorRow()<<": ";
        err<<doc.ErrorDesc();
        logger->addError(err);
        return nullptr;
    }

    /* retrieving root element */
    TiXmlElement *root = doc.RootElement();
    if(!root)
    {
        OSTRINGSTREAM err;
        err<<"Syntax error while loading "<<szFile<<" . ";
        err<<"No root element.";
        logger->addError(err);
        return nullptr;
    }

    if(!compareString(root->Value(), "application"))
    {
        //OSTRINGSTREAM err;
        //err<<"File "<<szFile<<" has no tag <application>.";
        //logger->addError(err);
        return nullptr;
    }

    /* retrieving name */
    TiXmlElement* name = (TiXmlElement*) root->FirstChild("name");
    if(!name || !name->GetText())
    {
        OSTRINGSTREAM err;
        err<<"Module from "<<szFile<<" has no name.";
        logger->addError(err);
        //return NULL;
    }

    for(TiXmlElement* var = root->FirstChildElement("var"); var; var = var->NextSiblingElement())
    {
        if(var->Attribute("name") && var->GetText())
        {
            parser->addVariable(var->Attribute("name"), var->GetText());
        }
    }

    app.setXmlFile(szFile);

    if(name)
    {
        string strname = parser->parseText(name->GetText());
        for(unsigned int i=0; i<strname.size(); i++)
            if(strname[i] == ' ')
                strname[i] = '_';
        app.setName(strname.c_str());
    }

    /* retrieving description */
    TiXmlElement* desc;
    if((desc = (TiXmlElement*) root->FirstChild("description")))
        app.setDescription(parser->parseText(desc->GetText()).c_str());

    /* retrieving version */
    TiXmlElement* ver;
    if((ver = (TiXmlElement*) root->FirstChild("version")))
        app.setVersion(parser->parseText(ver->GetText()).c_str());

    /*
     * TODO: setting prefix of the main application is inactivated.
     * Check this should be supported in future or not!
     */
    /*
    //retrieving application prefix
    TiXmlElement* pref;
    if((pref = (TiXmlElement*) root->FirstChild("prefix")))
        app.setPrefix(pref->GetText());
    */

    /* retrieving authors information*/
    TiXmlElement* authors;
    if((authors = (TiXmlElement*) root->FirstChild("authors")))
        for(TiXmlElement* ath = authors->FirstChildElement(); ath;
                ath = ath->NextSiblingElement())
        {
            if(compareString(ath->Value(), "author"))
            {
                Author author;
                if(ath->GetText())
                    author.setName(parser->parseText(ath->GetText()).c_str());
                if(ath->Attribute("email"))
                    author.setEmail(ath->Attribute("email"));
                app.addAuthor(author);
            }
            else
            {
                OSTRINGSTREAM war;
                war<<"Unrecognized tag from "<<szFile<<" at line "\
                   <<ath->Row()<<".";
                logger->addWarning(war);
            }
        }

    /* retrieving resources information*/
    TiXmlElement* resources;
    if((resources = (TiXmlElement*) root->FirstChild("dependencies")))
        for(TiXmlElement* res = resources->FirstChildElement(); res;
                res = res->NextSiblingElement())
        {
            if(compareString(res->Value(), "port"))
            {
                if(res->GetText())
                {
                    ResYarpPort resource(parser->parseText(res->GetText()).c_str());
                    resource.setPort(parser->parseText(res->GetText()).c_str());
                    app.addResource(resource);
                }
            }
            else
            {
                OSTRINGSTREAM war;
                war<<"Unrecognized tag from "<<szFile<<" at line "\
                   <<res->Row()<<".";
                logger->addWarning(war);
            }
        }

    /* retrieving modules information*/
    typedef void (ModuleInterface::*setter)(const char*);

    vector<pair<const char*, setter> > modList;
    pair<const char*, setter>          pairNode;

    pairNode.first = "node";        pairNode.second = &ModuleInterface::setHost;        modList.push_back(pairNode);
    pairNode.first = "parameters";  pairNode.second = &ModuleInterface::setParam;       modList.push_back(pairNode);
    pairNode.first = "stdio";       pairNode.second = &ModuleInterface::setStdio;       modList.push_back(pairNode);
    pairNode.first = "workdir";     pairNode.second = &ModuleInterface::setWorkDir;     modList.push_back(pairNode);
    pairNode.first = "deployer";    pairNode.second = &ModuleInterface::setBroker;      modList.push_back(pairNode);
    pairNode.first = "prefix";      pairNode.second = &ModuleInterface::setPrefix;      modList.push_back(pairNode);
    pairNode.first = "environment"; pairNode.second = &ModuleInterface::setEnvironment; modList.push_back(pairNode);
    pairNode.first = "display";     pairNode.second = &ModuleInterface::setDisplay;     modList.push_back(pairNode);
    for(TiXmlElement* mod = root->FirstChildElement(); mod; mod = mod->NextSiblingElement())
    {
        if(compareString(mod->Value(), "module"))
        {
            TiXmlElement* element;
            if((element = (TiXmlElement*) mod->FirstChild("name")))
            {
                string                             elemText;
                const char*                        text;


                text = nullptr;
                if(element->GetText())
                {
                    elemText = parser->parseText(element->GetText());
                    text     = elemText.c_str();
                }

                ModuleInterface module(text);

                for(size_t i = 0; i < modList.size(); i++)
                {
                    if((element = (TiXmlElement*) mod->FirstChild(modList[i].first)))
                    {
                        text = nullptr;
                        if(element->GetText())
                        {
                            elemText = parser->parseText(element->GetText());
                            text     = elemText.c_str();
                        }

                        (module.*(modList[i].second))(text);
                    }
                }

                if((element = (TiXmlElement*) mod->FirstChild("rank")))
                {
                    if(element->GetText())
                    {
                        elemText = parser->parseText(element->GetText());
                        text     = elemText.c_str();
                    }

                    module.setRank(atoi(text));
                }

#ifdef WITH_GEOMETRY
                element = (TiXmlElement*) mod->FirstChild("geometry");
                if(element && element->GetText())
                {
                    yarp::os::Property prop(parser->parseText(element->GetText()).c_str());
                    GraphicModel model;
                    GyPoint pt;
                    if(prop.check("Pos"))
                    {
                        pt.x = prop.findGroup("Pos").find("x").asFloat64();
                        pt.y = prop.findGroup("Pos").find("y").asFloat64();
                        model.points.push_back(pt);
                        module.setModelBase(model);
                    }
                }
#endif
                /* retrieving resources information*/
                TiXmlElement* resources;
                if((resources = (TiXmlElement*) mod->FirstChild("dependencies")))
                {
                    for(TiXmlElement* res = resources->FirstChildElement(); res;
                            res = res->NextSiblingElement())
                    {
                        if(compareString(res->Value(), "port"))
                        {
                            if(res->GetText())
                            {
                                ResYarpPort resource(parser->parseText(res->GetText()).c_str());
                                resource.setPort(parser->parseText(res->GetText()).c_str());
                                if(res->Attribute("timeout"))
                                    resource.setTimeout(atof(res->Attribute("timeout")));
                                if(res->Attribute("request"))
                                    resource.setRequest(res->Attribute("request"));
                                if(res->Attribute("reply"))
                                    resource.setReply(res->Attribute("reply"));
                                module.addResource(resource);
                            }
                        }
                        else
                        {
                            OSTRINGSTREAM war;
                            war<<"Unrecognized tag from "<<szFile<<" at line "\
                               <<res->Row()<<".";
                            logger->addWarning(war);
                        }
                    }
                }

                /* retrieving resources information*/
                TiXmlElement* ensure;
                if((ensure = (TiXmlElement*) mod->FirstChild("ensure")))
                {
                    for(TiXmlElement* res = ensure->FirstChildElement(); res;
                            res = res->NextSiblingElement())
                    {
                        if(compareString(res->Value(), "wait"))
                        {
                            if (res->Attribute("when") && compareString(res->Attribute("when"), "start")) {
                                if(parser->parseText(res->GetText()).c_str())
                                    module.setPostExecWait(atof(parser->parseText(res->GetText()).c_str()));
                            }
                            else if (res->Attribute("when") && compareString(res->Attribute("when"), "stop")) {
                                if(parser->parseText(res->GetText()).c_str())
                                    module.setPostStopWait(atof(parser->parseText(res->GetText()).c_str()));
                            }
                            else if (res->Attribute("when") && strlen(res->Attribute("when"))) {
                                OSTRINGSTREAM war;
                                war << "Unrecognized value for 'when' property from " << szFile << " at line "<< res->Row() << ".";
                                logger->addWarning(war);
                            }
                            else {  // if "when" has not been specified, use setPostExecWait!
                                if(parser->parseText(res->GetText()).c_str())
                                    module.setPostExecWait(atof(parser->parseText(res->GetText()).c_str()));
                            }
                        }
                        else
                        {
                            OSTRINGSTREAM war;
                            war<<"Unrecognized tag from "<<szFile<<" at line "\
                               <<res->Row()<<".";
                            logger->addWarning(war);
                        }
                    }
                }
                /* retrieving portmaps */
                for(TiXmlElement* map = mod->FirstChildElement(); map;
                            map = map->NextSiblingElement())
                    if(compareString(map->Value(), "portmap"))
                    {
                        TiXmlElement* first;
                        TiXmlElement* second;
                        if((first=(TiXmlElement*) map->FirstChild("old")) &&
                           (second=(TiXmlElement*) map->FirstChild("new")) )
                        {
                            Portmap portmap(parser->parseText(first->GetText()).c_str(), parser->parseText(second->GetText()).c_str());
                            module.addPortmap(portmap);
                        }
                    }

                app.addImodule(module);
            }
            else
            {
                OSTRINGSTREAM war;
                war<<"Module from "<<szFile<<" at line "\
                   <<mod->Row()<<" has not name tag.";
                logger->addWarning(war);
            }

        }
    }

    /* retrieving embedded application information*/
    for(TiXmlElement* embApp = root->FirstChildElement(); embApp;
            embApp = embApp->NextSiblingElement())
    {
        if(compareString(embApp->Value(), "application"))
        {
            TiXmlElement* name;
            TiXmlElement* prefix;
            if((name=(TiXmlElement*) embApp->FirstChild("name")))
            {
                ApplicationInterface IApp(parser->parseText(name->GetText()).c_str());
                if((prefix=(TiXmlElement*) embApp->FirstChild("prefix")))
                    IApp.setPrefix(parser->parseText(prefix->GetText()).c_str());
#ifdef WITH_GEOMETRY
                TiXmlElement* element = (TiXmlElement*) embApp->FirstChild("geometry");
                if(element && element->GetText())
                {
                    yarp::os::Property prop(parser->parseText(element->GetText()).c_str());
                    GraphicModel model;
                    GyPoint pt;
                    if(prop.check("Pos"))
                    {
                        pt.x = prop.findGroup("Pos").find("x").asFloat64();
                        pt.y = prop.findGroup("Pos").find("y").asFloat64();
                        model.points.push_back(pt);
                        IApp.setModelBase(model);
                    }
                }
#endif
                app.addIapplication(IApp);
            }
            else
            {
                OSTRINGSTREAM war;
                war<<"Incomplete application tag from "<<szFile<<" at line "\
                   <<embApp->Row()<<". (no name)";
                logger->addWarning(war);
            }
        }
    }


    /* retrieving arbitrator information*/
    for(TiXmlElement* arb = root->FirstChildElement(); arb;
            arb = arb->NextSiblingElement())
    {
        if(compareString(arb->Value(), "arbitrator"))
        {
            TiXmlElement* port = (TiXmlElement*) arb->FirstChild("port");
            if(port && port->GetText())
            {
                Arbitrator arbitrator(parser->parseText(port->GetText()).c_str());

                // retrieving rules
                for(TiXmlElement* rule = arb->FirstChildElement(); rule;
                    rule = rule->NextSiblingElement())
                {
                    if(compareString(rule->Value(), "rule"))
                    {
                        if(rule->Attribute("connection"))
                            arbitrator.addRule(rule->Attribute("connection"), parser->parseText(rule->GetText()).c_str());
                    }
                }
#ifdef WITH_GEOMETRY
                TiXmlElement* geometry = (TiXmlElement*) arb->FirstChild("geometry");
                if(geometry && geometry->GetText())
                {
                    yarp::os::Property prop(parser->parseText(geometry->GetText()).c_str());
                    GraphicModel model;
                    if(prop.check("Pos"))
                    {
                        yarp::os::Bottle pos = prop.findGroup("Pos");
                        for(size_t i=1; i<pos.size(); i++)
                        {
                            GyPoint pt;
                            pt.x = pos.get(i).find("x").asFloat64();
                            pt.y = pos.get(i).find("y").asFloat64();
                            model.points.push_back(pt);
                        }
                        arbitrator.setModelBase(model);
                    }
                }
#endif
                app.addArbitrator(arbitrator);
            }
            else
            {
                OSTRINGSTREAM war;
                war<<"Incomplete arbitrator tag from "<<szFile<<" at line "\
                   <<arb->Row()<<".";
                logger->addWarning(war);
            }
        }
    }

    /* retrieving connections information*/
    for(TiXmlElement* cnn = root->FirstChildElement(); cnn;
            cnn = cnn->NextSiblingElement())
    {
        if(compareString(cnn->Value(), "connection"))
        {
            TiXmlElement* from = (TiXmlElement*) cnn->FirstChild("from");
            TiXmlElement* to = (TiXmlElement*) cnn->FirstChild("to");

            if(!from)
                from = (TiXmlElement*) cnn->FirstChild("output");
            if(!to)
                to = (TiXmlElement*) cnn->FirstChild("input");

            TiXmlElement* protocol;
            if(from && to)
            {
                string strCarrier;
                if((protocol=(TiXmlElement*) cnn->FirstChild("protocol")) &&
                    protocol->GetText())
                    strCarrier = parser->parseText(protocol->GetText()).c_str();
                Connection connection(parser->parseText(from->GetText()).c_str(),
                                    parser->parseText(to->GetText()).c_str(),
                                    strCarrier.c_str());

                // check if Qos is set for the connection
                if(cnn->Attribute("qos")) {
                    connection.setQosTo(cnn->Attribute("qos"));
                    connection.setQosFrom(cnn->Attribute("qos"));
                }

                if(from->Attribute("external") &&
                    compareString(from->Attribute("external"), "true"))
                {
                    connection.setFromExternal(true);
                    if(from->GetText())
                    {
                        ResYarpPort resource(parser->parseText(from->GetText()).c_str());
                        resource.setPort(parser->parseText(from->GetText()).c_str());
                        app.addResource(resource);
                    }
                }
                if(from->Attribute("qos"))
                    connection.setQosFrom(from->Attribute("qos"));
                if(to->Attribute("external") &&
                    compareString(to->Attribute("external"), "true"))
                {
                    if(to->GetText())
                    {
                        connection.setToExternal(true);
                        ResYarpPort resource(parser->parseText(to->GetText()).c_str());
                        resource.setPort(parser->parseText(to->GetText()).c_str());
                        app.addResource(resource);
                    }
                }
                if(to->Attribute("qos"))
                    connection.setQosTo(to->Attribute("qos"));

                //Connections which have the same port name in Port Resources
                // should also be set as external
                for(int i=0; i<app.resourcesCount(); i++)
                {
                    ResYarpPort res = app.getResourceAt(i);
                    if(compareString(res.getPort(), connection.from()))
                        connection.setFromExternal(true);
                    if(compareString(res.getPort(), connection.to()))
                        connection.setToExternal(true);
                }

                if(cnn->Attribute("id"))
                    connection.setId(cnn->Attribute("id"));

                if(cnn->Attribute("persist") &&
                        compareString(cnn->Attribute("persist"), "true"))
                    connection.setPersistent(true);

#ifdef WITH_GEOMETRY
                TiXmlElement* geometry = (TiXmlElement*) cnn->FirstChild("geometry");
                if(geometry && geometry->GetText())
                {
                    yarp::os::Property prop(parser->parseText(geometry->GetText()).c_str());
                    GraphicModel model;
                    if(prop.check("Pos"))
                    {
                        yarp::os::Bottle pos = prop.findGroup("Pos");
                        for(size_t i=1; i<pos.size(); i++)
                        {
                            GyPoint pt;
                            pt.x = pos.get(i).find("x").asFloat64();
                            pt.y = pos.get(i).find("y").asFloat64();
                            model.points.push_back(pt);
                        }
                        connection.setModelBase(model);
                    }
                }
#endif

                app.addConnection(connection);
            }
            else
            {
                OSTRINGSTREAM war;
                war<<"Incomplete connection tag from "<<szFile<<" at line "\
                   <<cnn->Row()<<".";
                logger->addWarning(war);
            }
        }
    }


    return &app;

}
Пример #22
0
void CWeatherJob::LoadLocalizedToken()
{
    // We load the english strings in to get our tokens

    // Try the strings PO file first
    CPODocument PODoc;
    if (PODoc.LoadFile("special://xbmc/language/English/strings.po"))
    {
        int counter = 0;

        while (PODoc.GetNextEntry())
        {
            if (PODoc.GetEntryType() != ID_FOUND)
                continue;

            uint32_t id = PODoc.GetEntryID();
            PODoc.ParseEntry(ISSOURCELANG);

            if (id > LOCALIZED_TOKEN_LASTID2) break;
            if ((LOCALIZED_TOKEN_FIRSTID  <= id && id <= LOCALIZED_TOKEN_LASTID)  ||
                    (LOCALIZED_TOKEN_FIRSTID2 <= id && id <= LOCALIZED_TOKEN_LASTID2) ||
                    (LOCALIZED_TOKEN_FIRSTID3 <= id && id <= LOCALIZED_TOKEN_LASTID3) ||
                    (LOCALIZED_TOKEN_FIRSTID4 <= id && id <= LOCALIZED_TOKEN_LASTID4))
            {
                if (!PODoc.GetMsgid().empty())
                {
                    m_localizedTokens.insert(make_pair(PODoc.GetMsgid(), id));
                    counter++;
                }
            }
        }

        CLog::Log(LOGDEBUG, "POParser: loaded %i weather tokens", counter);
        return;
    }

    CLog::Log(LOGDEBUG,
              "Weather: no PO string file available, to load English tokens, "
              "fallback to strings.xml file");

    // We load the tokens from the strings.xml file
    CStdString strLanguagePath = "special://xbmc/language/English/strings.xml";

    CXBMCTinyXML xmlDoc;
    if (!xmlDoc.LoadFile(strLanguagePath) || !xmlDoc.RootElement())
    {
        CLog::Log(LOGERROR, "Weather: unable to load %s: %s at line %d", strLanguagePath.c_str(), xmlDoc.ErrorDesc(), xmlDoc.ErrorRow());
        return;
    }

    CStdString strEncoding;
    XMLUtils::GetEncoding(&xmlDoc, strEncoding);

    TiXmlElement* pRootElement = xmlDoc.RootElement();
    if (pRootElement->Value() != CStdString("strings"))
        return;

    const TiXmlElement *pChild = pRootElement->FirstChildElement();
    while (pChild)
    {
        CStdString strValue = pChild->Value();
        if (strValue == "string")
        {   // Load new style language file with id as attribute
            const char* attrId = pChild->Attribute("id");
            if (attrId && !pChild->NoChildren())
            {
                int id = atoi(attrId);
                if ((LOCALIZED_TOKEN_FIRSTID  <= id && id <= LOCALIZED_TOKEN_LASTID)  ||
                        (LOCALIZED_TOKEN_FIRSTID2 <= id && id <= LOCALIZED_TOKEN_LASTID2) ||
                        (LOCALIZED_TOKEN_FIRSTID3 <= id && id <= LOCALIZED_TOKEN_LASTID3) ||
                        (LOCALIZED_TOKEN_FIRSTID4 <= id && id <= LOCALIZED_TOKEN_LASTID4))
                {
                    CStdString utf8Label;
                    if (strEncoding.IsEmpty()) // Is language file utf8?
                        utf8Label=pChild->FirstChild()->Value();
                    else
                        g_charsetConverter.stringCharsetToUtf8(strEncoding, pChild->FirstChild()->Value(), utf8Label);

                    if (!utf8Label.IsEmpty())
                        m_localizedTokens.insert(make_pair(utf8Label, id));
                }
            }
        }
        pChild = pChild->NextSiblingElement();
    }
}
Пример #23
0
void CWakeOnAccess::LoadFromXML()
{
    bool enabled = CSettings::GetInstance().GetBool(CSettings::SETTING_POWERMANAGEMENT_WAKEONACCESS);

    CXBMCTinyXML xmlDoc;
    if (!xmlDoc.LoadFile(GetSettingFile()))
    {
        if (enabled)
            CLog::Log(LOGNOTICE, "%s - unable to load:%s", __FUNCTION__, GetSettingFile().c_str());
        return;
    }

    TiXmlElement* pRootElement = xmlDoc.RootElement();
    if (strcmpi(pRootElement->Value(), "onaccesswakeup"))
    {
        CLog::Log(LOGERROR, "%s - XML file %s doesnt contain <onaccesswakeup>", __FUNCTION__, GetSettingFile().c_str());
        return;
    }

    m_entries.clear();

    CLog::Log(LOGNOTICE,"WakeOnAccess - Load settings :");

    SetEnabled(enabled);

    int tmp;
    if (XMLUtils::GetInt(pRootElement, "netinittimeout", tmp, 0, 5 * 60))
        m_netinit_sec = tmp;
    CLog::Log(LOGNOTICE,"  -Network init timeout : [%d] sec", m_netinit_sec);

    if (XMLUtils::GetInt(pRootElement, "netsettletime", tmp, 0, 5 * 1000))
        m_netsettle_ms = tmp;
    CLog::Log(LOGNOTICE,"  -Network settle time  : [%d] ms", m_netsettle_ms);

    const TiXmlNode* pWakeUp = pRootElement->FirstChildElement("wakeup");
    while (pWakeUp)
    {
        WakeUpEntry entry;

        std::string strtmp;
        if (XMLUtils::GetString(pWakeUp, "host", strtmp))
            entry.host = strtmp;

        if (XMLUtils::GetString(pWakeUp, "mac", strtmp))
            entry.mac = strtmp;

        if (entry.host.empty())
            CLog::Log(LOGERROR, "%s - Missing <host> tag or it's empty", __FUNCTION__);
        else if (entry.mac.empty())
            CLog::Log(LOGERROR, "%s - Missing <mac> tag or it's empty", __FUNCTION__);
        else
        {
            if (XMLUtils::GetInt(pWakeUp, "pingport", tmp, 0, USHRT_MAX))
                entry.ping_port = (unsigned short) tmp;

            if (XMLUtils::GetInt(pWakeUp, "pingmode", tmp, 0, USHRT_MAX))
                entry.ping_mode = (unsigned short) tmp;

            if (XMLUtils::GetInt(pWakeUp, "timeout", tmp, 10, 12 * 60 * 60))
                entry.timeout.SetDateTimeSpan (0, 0, 0, tmp);

            if (XMLUtils::GetInt(pWakeUp, "waitonline", tmp, 0, 10 * 60)) // max 10 minutes
                entry.wait_online1_sec = tmp;

            if (XMLUtils::GetInt(pWakeUp, "waitonline2", tmp, 0, 10 * 60)) // max 10 minutes
                entry.wait_online2_sec = tmp;

            if (XMLUtils::GetInt(pWakeUp, "waitservices", tmp, 0, 5 * 60)) // max 5 minutes
                entry.wait_services_sec = tmp;

            CLog::Log(LOGNOTICE,"  Registering wakeup entry:");
            CLog::Log(LOGNOTICE,"    HostName        : %s", entry.host.c_str());
            CLog::Log(LOGNOTICE,"    MacAddress      : %s", entry.mac.c_str());
            CLog::Log(LOGNOTICE,"    PingPort        : %d", entry.ping_port);
            CLog::Log(LOGNOTICE,"    PingMode        : %d", entry.ping_mode);
            CLog::Log(LOGNOTICE,"    Timeout         : %d (sec)", GetTotalSeconds(entry.timeout));
            CLog::Log(LOGNOTICE,"    WaitForOnline   : %d (sec)", entry.wait_online1_sec);
            CLog::Log(LOGNOTICE,"    WaitForOnlineEx : %d (sec)", entry.wait_online2_sec);
            CLog::Log(LOGNOTICE,"    WaitForServices : %d (sec)", entry.wait_services_sec);

            m_entries.push_back(entry);
        }

        pWakeUp = pWakeUp->NextSiblingElement("wakeup"); // get next one
    }
}
Пример #24
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;
}
Пример #25
0
//This function loads a map from the specified .tmx file
void Game::LoadMap(string filename)
{
	//Create our Root Document handle and open it up
	TiXmlDocument Root(filename.c_str());
	if (!Root.LoadFile()) throw std::runtime_error(string("Failed to open level file: ") + filename);

	//Get a handle to our first set of 'layer' data in the map. This could be anything from a tile/object layer to tileset info,
	//so we need to check what it is before we do anything with it.
	TiXmlElement *Layer = Root.FirstChildElement("map")->FirstChildElement();

	//Clear out any existing object data
	GameStorage->ClearAll();

	//Loop through all layers we can find in the map data
	while (Layer)
	{
		//Check for an object layer that has child elements. Currently this is the only kind we're interested in.
		if (string(Layer->Value()) == "objectgroup" && !Layer->NoChildren())
		{
			//Get our first object in this layer
			TiXmlElement *Object = Layer->FirstChildElement();
			//Get the name of our layer
			string name(Layer->Attribute("name"));
			ColourType colour;

			//Convert name to lower-case
			for (int i = 0; i < name.length(); i++)
			{
				name[i] = tolower(name[i]);
			}

			//Loop through all objects
			while (Object)
			{
				string type((Object->Attribute("type") != NULL) ? Object->Attribute("type") : "");

				//Depending on the type of this layer, spawn a certain type of object
				if (name == "red")
				{
					colour = COLOUR_RED;
				}
				else if (name == "blue")
				{
					colour = COLOUR_BLUE;
				}
				else if (name == "yellow")
				{
					colour = COLOUR_YELLOW;
				}
				else if (name == "white")
				{
					colour = COLOUR_WHITE;
				}
				else if (name == "player")
				{
					player.ReadPosition(Object);
				}
				else if (name == "exit")
				{
					exit.ReadPosition(Object);
				}

				if (name != "player" && name != "exit")
				{
					if (type == "" || type == "normal")
					{
						GameStorage->AddObject(GameObjectPointer(new ColourBox(Object, colour)));
					}
					else if (type == "moveable")
					{

					}
					else if (type == "moving")
					{
						GameStorage->AddObject(GameObjectPointer(new MovingColourBlock(Object, colour)));
					}
				}

				Object = Object->NextSiblingElement();
			}
		}

		Layer = Layer->NextSiblingElement();
	}

	ColouredObject::SetCurrentColour(COLOUR_RED);
}
Пример #26
0
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;
}
Пример #27
0
bool XMLScene::parseNode(TiXmlElement *curr_node, bool is_inside_dl) {

	char node_id[MAX_STRING_LEN];

	if (strdup(node_id, curr_node->Attribute("id")) == NULL) {
		printf("Error reading \"id\" attribute!\n");
		throw InvalidXMLException();
	}

	printf("id: %s\n", node_id);

	bool is_dl = false;
	string dl_node_id;
	if (curr_node->QueryBoolAttribute("displaylist", &is_dl) != TIXML_SUCCESS) {
		printf("No \"displaylist\" attribute\n");
	}

	if (is_dl) {
		printf("Node \"%s\" defined as a display list.\n", node_id);
		dl_node_id = Scene::getInstance()->findNextNameAvail(node_id);
		printf("dl_node_id: %s\n", dl_node_id.c_str());
	}

	Node *n;

	if (is_dl) {
		n = new DisplayList(dl_node_id);
	} else {
		n = new Node(node_id);
	}

	nodes_being_processed.push_back(node_id);

	printf("Processing transformations...\n");

	TiXmlElement *transf_block = NULL;
	if ((transf_block = curr_node->FirstChildElement("transforms")) == NULL) {
		printf("Could not find \"transforms\" block on %s node!\n", node_id);
		throw InvalidXMLException();
	}

	TiXmlElement *transf = NULL;
	while ((transf = (TiXmlElement*) transf_block->IterateChildren(transf))) {
		char t_type[MAX_STRING_LEN];
		if (strdup(t_type, transf->Value()) == NULL) {
			printf("Invalid transformation on node %s\n", node_id);
			throw InvalidXMLException();
		}
		if (strcmp(t_type, "translate") == 0) {
			char tmp_str[MAX_STRING_LEN];
			double t_x = 0, t_y = 0, t_z = 0;

			if (strdup(tmp_str, transf->Attribute("to")) == NULL) {
				printf("Error on translate transformation on node %s!\n", node_id);
				throw InvalidXMLException();
			}

			if (sscanf(tmp_str, "%lf %lf %lf", &t_x, &t_y, &t_z) != 3) {
				printf("Error parsing translate transformation on node %s!\n", node_id);
				throw InvalidXMLException();
			}

			n->addTranslate(t_x, t_y, t_z);

			printf("Translate\nto: (%f %f %f)\n", t_x, t_y, t_z);

		} else if (strcmp(t_type, "rotate") == 0) {
			char tmp_str[2];
			char r_axis = '\0';
			double r_angle;
			if (strdup(tmp_str, transf->Attribute("axis")) == NULL) {
				printf("Error on rotate transformation on node %s!\n", node_id);
				throw InvalidXMLException();
			}
			r_axis = tmp_str[0];

			if (transf->QueryDoubleAttribute("angle", &r_angle)) {
				printf("Error parsing rotate transformation on node %s!\n", node_id);
				throw InvalidXMLException();
			}

			n->addRotation(r_angle, r_axis);

			printf("Rotate\naxis: %c\nangle: %f\n", r_axis, r_angle);

		} else if (strcmp(t_type, "scale") == 0) {
			char tmp_str[MAX_STRING_LEN];
			double f_x = 0, f_y = 0, f_z = 0;

			if (strdup(tmp_str, transf->Attribute("factor")) == NULL) {
				printf("Error on scale transformation on node %s!\n", node_id);
				throw InvalidXMLException();
			}

			if (sscanf(tmp_str, "%lf %lf %lf", &f_x, &f_y, &f_z) != 3) {
				printf("Error parsing scale transformation on node %s!\n", node_id);
				throw InvalidXMLException();
			}

			n->addScale(f_x, f_y, f_z);

			printf("Scale\nfactor: (%f %f %f)\n", f_x, f_y, f_z);

		} else {
			printf("Invalid transformation on node %s\n", node_id);
			throw InvalidXMLException();
		}
	}

	TiXmlElement *appearance = NULL;
	if ((appearance = curr_node->FirstChildElement("appearanceref"))) {
		char app_id[MAX_STRING_LEN];
		if (strdup(app_id, appearance->Attribute("id")) == NULL) {
			printf("Error on \"appearanceref\" block on node %s!\n", node_id);
			throw InvalidXMLException();
		}

		n->setAppearance(app_id);
		app_stck.push(app_id);

		printf("Appearance\nid: %s\n", app_id);
	} else {
		app_stck.push(app_stck.top());
	}

	TiXmlElement *animation = NULL;
	if ((animation = curr_node->FirstChildElement("animationref"))) {
		if (is_inside_dl || is_dl) {
			printf("Animation defined in \"%s\" is inside a display list!\n", node_id);
			throw InvalidXMLException();
		}

		char ani_id[MAX_STRING_LEN];
		if (strdup(ani_id, animation->Attribute("id")) == NULL) {
			printf("Error on \"animationref\" block on node %s!\n", node_id);
			throw InvalidXMLException();
		}

		n->setAnimation(ani_id);

		printf("Animation\nid: %s\n", ani_id);
	} else {
		printf("No animation defined on node \"%s\".\n", node_id);
	}

	printf("Processing children...\n");

	TiXmlElement *children = NULL;

	if ((children = curr_node->FirstChildElement("children")) == NULL) {
		printf("Block \"children\" not found!\n");
		throw InvalidXMLException();
	}

	TiXmlElement *child = NULL;
	while ((child = (TiXmlElement *) children->IterateChildren(child))) {
		char child_type[MAX_STRING_LEN];
		strdup(child_type, child->Value());

		if (strcmp(child_type, "rectangle") == 0) {
			char tmp_str[MAX_STRING_LEN];
			double x1 = 0, x2 = 0, y1 = 0, y2 = 0;
			if (strdup(tmp_str, child->Attribute("xy1")) == NULL) {
				printf("Error reading \"xy1\" attribute!\n");
				throw InvalidXMLException();
			}
			if (sscanf(tmp_str, "%lf %lf", &x1, &y1) != 2) {
				printf("Error parsing \"xy1\" attribute!\n");
				throw InvalidXMLException();
			}

			if (strdup(tmp_str, child->Attribute("xy2")) == NULL) {
				printf("Error reading \"xy2\" attribute!\n");
				throw InvalidXMLException();
			}
			if (sscanf(tmp_str, "%lf %lf", &x2, &y2) != 2) {
				printf("Error parsing \"xy2\" attribute!\n");
				throw InvalidXMLException();
			}

			MyRectangle *rect = new MyRectangle(x1, y1, x2, y2);
			n->addPrimitive(rect);

			printf("Rectangle\nxy1: (%f,%f)\nxy2: (%f,%f)\n", x1, y1, x2, y2);

		} else if (strcmp(child_type, "triangle") == 0) {
			char tmp_str[MAX_STRING_LEN];
			double x1 = 0, x2 = 0, x3 = 0, y1 = 0, y2 = 0, y3 = 0, z1 = 0, z2 = 0, z3 = 0;
			if (strdup(tmp_str, child->Attribute("xyz1")) == NULL) {
				printf("Error reading \"xyz1\" attribute!\n");
				throw InvalidXMLException();
			}
			if (sscanf(tmp_str, "%lf %lf %lf", &x1, &y1, &z1) != 3) {
				printf("Error parsing \"xyz1\" attribute!\n");
				throw InvalidXMLException();
			}

			if (strdup(tmp_str, child->Attribute("xyz2")) == NULL) {
				printf("Error reading \"xyz2\" attribute!\n");
				throw InvalidXMLException();
			}
			if (sscanf(tmp_str, "%lf %lf %lf", &x2, &y2, &z2) != 3) {
				printf("Error parsing \"xyz2\" attribute!\n");
				throw InvalidXMLException();
			}

			if (strdup(tmp_str, child->Attribute("xyz3")) == NULL) {
				printf("Error reading \"xyz3\" attribute!\n");
				throw InvalidXMLException();
			}
			if (sscanf(tmp_str, "%lf %lf %lf", &x3, &y3, &z3) != 3) {
				printf("Error parsing \"xyz3\" attribute!\n");
				throw InvalidXMLException();
			}

			MyTriangle *tri = new MyTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3);
			n->addPrimitive(tri);

			printf("Triangle\nxyz1: (%f,%f,%f)\nxyz2: (%f,%f,%f)\nxyz3: (%f,%f,%f)\n", x1, y1, z1, x2, y2, z2, x3, y3,
					z3);

		} else if (strcmp(child_type, "cylinder") == 0) {
			double cyl_base = 0, cyl_top = 0, cyl_height = 0;
			unsigned int cyl_slices = 0, cyl_stacks = 0;

			if (child->QueryDoubleAttribute("base", &cyl_base) != TIXML_SUCCESS) {
				printf("Error parsing base attribute!\n");
				throw InvalidXMLException();
			}

			if (child->QueryDoubleAttribute("top", &cyl_top) != TIXML_SUCCESS) {
				printf("Error parsing slices attribute!\n");
				throw InvalidXMLException();
			}

			if (child->QueryDoubleAttribute("height", &cyl_height) != TIXML_SUCCESS) {
				printf("Error parsing slices attribute!\n");
				throw InvalidXMLException();
			}

			if (child->QueryUnsignedAttribute("slices", &cyl_slices) != TIXML_SUCCESS) {
				printf("Error parsing slices attribute!\n");
				throw InvalidXMLException();
			}

			if (child->QueryUnsignedAttribute("stacks", &cyl_stacks) != TIXML_SUCCESS) {
				printf("Error parsing stacks attribute!\n");
				throw InvalidXMLException();
			}

			MyCylinder *cyl = new MyCylinder(cyl_base, cyl_top, cyl_height, cyl_slices, cyl_stacks);
			n->addPrimitive(cyl);

			printf("Cylinder\nbase: %f\ntop: %f\nheight: %f\nslices: %d\nstacks: %d\n", cyl_base, cyl_top, cyl_height,
					cyl_slices, cyl_stacks);

		} else if (strcmp(child_type, "sphere") == 0) {
			double sph_rad = 0;
			unsigned int sph_slices = 0, sph_stacks = 0;

			if (child->QueryDoubleAttribute("radius", &sph_rad) != TIXML_SUCCESS) {
				printf("Error parsing radius attribute!\n");
			}

			if (child->QueryUnsignedAttribute("slices", &sph_slices) != TIXML_SUCCESS) {
				printf("Error parsing slices attribute!\n");
			}

			if (child->QueryUnsignedAttribute("stacks", &sph_stacks) != TIXML_SUCCESS) {
				printf("Error parsing stacks attribute!\n");
			}

			MySphere *sph = new MySphere(sph_rad, sph_slices, sph_stacks);
			n->addPrimitive(sph);

			printf("Sphere\nradius: %f\nslices: %d\nstacks: %d\n", sph_rad, sph_slices, sph_stacks);

		} else if (strcmp(child_type, "torus") == 0) {
			double tor_inner = 0, tor_out = 0;
			unsigned int tor_slices = 0, tor_loops = 0;

			if (child->QueryDoubleAttribute("inner", &tor_inner) != TIXML_SUCCESS) {
				printf("Error parsing inner attribute!\n");
			}

			if (child->QueryDoubleAttribute("outer", &tor_out) != TIXML_SUCCESS) {
				printf("Error parsing outer attribute!\n");
			}

			if (child->QueryUnsignedAttribute("slices", &tor_slices) != TIXML_SUCCESS) {
				printf("Error parsing slices attribute!\n");
			}

			if (child->QueryUnsignedAttribute("loops", &tor_loops) != TIXML_SUCCESS) {
				printf("Error parsing loops attribute!\n");
			}

			MyTorus *tor = new MyTorus(tor_inner, tor_out, tor_slices, tor_loops);
			n->addPrimitive(tor);

			printf("Torus\ninner: %f\nouter: %f\nslices: %d\nloops: %d\n", tor_inner, tor_out, tor_slices, tor_loops);
		} else if (strcmp(child_type, "plane") == 0) {
			int parts = 0;

			if (child->QueryIntAttribute("parts", &parts) != TIXML_SUCCESS) {
				printf("Error parsing \"parts\" attribute on plane!\n");
				throw InvalidXMLException();
			}

			if (parts <= 0) {
				printf("Invalid value on parts attribute of plane!\n");
				throw InvalidXMLException();
			}

			printf("Plane\nparts: %i\n", parts);

			Plane *p = new Plane(parts);
			n->addPrimitive(p);
		} else if (strcmp(child_type, "patch") == 0) {
			int order = 0;
			int parts_u = 0;
			int parts_v = 0;
			char compute[MAX_STRING_LEN];

			if (child->QueryIntAttribute("order", &order) != TIXML_SUCCESS) {
				printf("Error parsing \"order\" attribute on patch!\n");
				throw InvalidXMLException();
			}

			if (child->QueryIntAttribute("partsU", &parts_u) != TIXML_SUCCESS) {
				printf("Error parsing \"partsU\" attribute on patch!\n");
				throw InvalidXMLException();
			}

			if (child->QueryIntAttribute("partsV", &parts_v) != TIXML_SUCCESS) {
				printf("Error parsing \"partsV\" attribute on patch!\n");
				throw InvalidXMLException();
			}

			if (strdup(compute, child->Attribute("compute")) == NULL) {
				printf("Error parsing \"compute\" attribute on patch!\n");
				throw InvalidXMLException();
			}

			printf("Patch\norder: %d\npartsU: %d\npartsV: %d\ncompute: %s\n", order, parts_u, parts_v, compute);

			MyPatch *patch = new MyPatch(order, parts_u, parts_v, compute);
			n->addPrimitive(patch);

			TiXmlElement *ctrl_p = child->FirstChildElement("controlpoint");
			do {
				float x = 0;
				float y = 0;
				float z = 0;

				if (ctrl_p->QueryFloatAttribute("x", &x) != TIXML_SUCCESS) {
					printf("Error parsing \"x\" attribute on patch!\n");
					throw InvalidXMLException();
				}

				if (ctrl_p->QueryFloatAttribute("y", &y) != TIXML_SUCCESS) {
					printf("Error parsing \"y\" attribute on patch!\n");
					throw InvalidXMLException();
				}
				if (ctrl_p->QueryFloatAttribute("z", &z) != TIXML_SUCCESS) {
					printf("Error parsing \"z\" attribute on patch!\n");
					throw InvalidXMLException();
				}

				printf("controlpoint: (%f %f %f)\n", x, y, z);

				patch->addControlPoint(x, y, z);

			} while ((ctrl_p = ctrl_p->NextSiblingElement("controlpoint")) != NULL);
		} else if (strcmp(child_type, "waterline") == 0) {
			char heightmap[MAX_STRING_LEN];
			char texturemap[MAX_STRING_LEN];
			char vert_shader[MAX_STRING_LEN];
			char frag_shader[MAX_STRING_LEN];

			if (is_inside_dl || is_dl) {
				printf("Waterline defined in \"%s\" is inside a display list!\n", node_id);
				throw InvalidXMLException();
			}

			if (strdup(heightmap, child->Attribute("heightmap")) == NULL) {
				printf("Error parsing \"heightmap\" attribute of waterline!");
				throw InvalidXMLException();
			}

			if (strdup(texturemap, child->Attribute("texturemap")) == NULL) {
				printf("Error parsing \"texturemap\" attribute of waterline!");
				throw InvalidXMLException();
			}

			if (strdup(frag_shader, child->Attribute("fragmentshader")) == NULL) {
				printf("Error parsing \"fragmentshader\" attribute of waterline!");
				throw InvalidXMLException();
			}

			if (strdup(vert_shader, child->Attribute("vertexshader")) == NULL) {
				printf("Error parsing \"vertexshader\" attribute of waterline!");
				throw InvalidXMLException();
			}

			MyWaterLine *wl = new MyWaterLine(heightmap, texturemap, vert_shader, frag_shader);
			n->addPrimitive(wl);

		} else if (strcmp(child_type, "vehicle") == 0) {
			MyVehicle *v = new MyVehicle();
			n->addPrimitive(v);

		} else if (strcmp(child_type, "noderef") == 0) {
			char next_node_id[MAX_STRING_LEN];
			if (strdup(next_node_id, child->Attribute("id")) == NULL) {
				printf("Error reading noderef's id!\n");
				throw InvalidXMLException();
			}
			if (find(nodes_being_processed.begin(), nodes_being_processed.end(), next_node_id)
					!= nodes_being_processed.end()) {
				if (find(nodes_finished_processing.begin(), nodes_finished_processing.end(), next_node_id)
						!= nodes_finished_processing.end()) {
					printf("Node has already been processed.\n");
					string last_node_name = Scene::getInstance()->findLastNameAvail(next_node_id);
					if (Scene::getInstance()->getNode(last_node_name)->getType() != DISPLAY_LIST) { // normal node
						n->addRef(next_node_id);
					} else {
						TiXmlElement *next_node = NULL;
						if ((next_node = findChildByAttribute(graphElement, "id", next_node_id))) {
							printf("\n\n");
							parseNode(next_node, is_dl || is_inside_dl);
							n->addRef(Scene::getInstance()->findLastNameAvail(next_node_id));
						}
					}
					continue;
				} else {
					printf("Cyclic definition found in node \"%s\"", next_node_id);
					throw InvalidXMLException();
				}
			} else {
				TiXmlElement *next_node = NULL;
				if ((next_node = findChildByAttribute(graphElement, "id", next_node_id))) {
					printf("\n\n");
					parseNode(next_node, is_dl || is_inside_dl);
					string last_node_name = Scene::getInstance()->findLastNameAvail(next_node_id);
					if (Scene::getInstance()->getNode(last_node_name)->getType() == DISPLAY_LIST) {
						n->addRef(last_node_name);
					} else {
						n->addRef(next_node_id);
					}

				} else {
					printf("Node %s does not exist!\n", next_node_id);
					throw InvalidXMLException();
				}
			}
		} else {
			printf("Invalid block inside children of node %s\n", node_id);
			throw InvalidXMLException();
		}
	}
	printf("Finished processing %s node children.\n\n", node_id);

	if (is_dl) {
		Scene::getInstance()->addNode(dl_node_id, n);
	} else {
		Scene::getInstance()->addNode(node_id, n);
	}
	printf("closing %s\n", node_id);
	n->closeDefinition(app_stck);
	printf("closed %s\n", node_id);
	app_stck.pop();
	nodes_finished_processing.push_back(node_id);
	return true;
}
Пример #28
0
bool CSiteManager::Load(TiXmlElement *pElement, CSiteManagerXmlHandler* pHandler)
{
	wxASSERT(pElement);
	wxASSERT(pHandler);

	for (TiXmlElement* pChild = pElement->FirstChildElement(); pChild; pChild = pChild->NextSiblingElement())
	{
		if (!strcmp(pChild->Value(), "Folder"))
		{
			wxString name = GetTextElement_Trimmed(pChild);
			if (name.empty())
				continue;

			const bool expand = GetTextAttribute(pChild, "expanded") != _T("0");
			if (!pHandler->AddFolder(name, expand))
				return false;
			Load(pChild, pHandler);
			if (!pHandler->LevelUp())
				return false;
		}
		else if (!strcmp(pChild->Value(), "Server"))
		{
			CSiteManagerItemData_Site* data = ReadServerElement(pChild);

			if (data)
			{
				pHandler->AddSite(data);

				// Bookmarks
				for (TiXmlElement* pBookmark = pChild->FirstChildElement("Bookmark"); pBookmark; pBookmark = pBookmark->NextSiblingElement("Bookmark"))
				{
					TiXmlHandle handle(pBookmark);

					wxString name = GetTextElement_Trimmed(pBookmark, "Name");
					if (name.empty())
						continue;

					CSiteManagerItemData* data = new CSiteManagerItemData(CSiteManagerItemData::BOOKMARK);

					TiXmlText* localDir = handle.FirstChildElement("LocalDir").FirstChild().Text();
					if (localDir)
						data->m_localDir = GetTextElement(pBookmark, "LocalDir");

					TiXmlText* remoteDir = handle.FirstChildElement("RemoteDir").FirstChild().Text();
					if (remoteDir)
						data->m_remoteDir.SetSafePath(ConvLocal(remoteDir->Value()));

					if (data->m_localDir.empty() && data->m_remoteDir.IsEmpty())
					{
						delete data;
						continue;
					}

					if (!data->m_localDir.empty() && !data->m_remoteDir.IsEmpty())
						data->m_sync = GetTextElementBool(pBookmark, "SyncBrowsing", false);

					pHandler->AddBookmark(name, data);
				}

				if (!pHandler->LevelUp())
					return false;
			}
		}
	}

	return true;
}
Пример #29
0
bool CConfigManager::AnalyseConfigFile()
{
	TiXmlDocument doc;
	doc.LoadFile(m_strConfigFile.c_str());
	
	TiXmlElement* pRoot = doc.RootElement();
	const char* szRoot = pRoot->Value();
	if(strcmp("system", szRoot) != 0)
		return false;


	for (TiXmlElement* pChiled = pRoot->FirstChildElement(); pChiled != NULL; pChiled = pChiled->NextSiblingElement())
	{
		const char* szValue = pChiled->Value();
		if(strcmp(Software, szValue) == 0)
		{
			m_strAppVer = pChiled->Attribute(Ver);
			m_strSotfUrl = pChiled->Attribute(URL);
		}
		else if(strcmp(Configur, szValue) == 0)
		{
			m_strConfigVer = pChiled->Attribute(Ver);
		}
		else if(strcmp(Globle, szValue) == 0)
		{
			m_strHeight = pChiled->Attribute(Height);
			m_strWidth = pChiled->Attribute(Width);
			string strAdverCount = pChiled->Attribute(AdverCount);
			m_nAdverCount = atoi(strAdverCount.c_str());
		}
		else if(strcmp(Sever, szValue) == 0)
		{
			m_strIp = pChiled->Attribute(IP);
			m_strPort = pChiled->Attribute(Port);
		}
		else if(strcmp(Notice, szValue) == 0)
		{
			m_strNoticeDir = pChiled->Attribute(Dir);
		}
		else if(strcmp(Template, szValue) == 0)
		{
			m_strTempVer = pChiled->Attribute(Ver);
			m_strTemplatePath = pChiled->Attribute(Dir);
		}
		else if(strcmp(Adver, szValue) == 0)
		{
			m_Adver.AnalyseAdver(pChiled);
		}
		else if(strcmp(BusStop, szValue) == 0)
		{
			m_Busstop.AnalyseBusStop(pChiled);
		}
		else if(strcmp(Picture, szValue) == 0)
		{
			m_strPictrueDir = pChiled->Attribute(Dir);
		}
		else if(strcmp(Default, szValue) == 0)
		{
			m_strDefaultPath = pChiled->Attribute(Dir);
		}
		else if(strcmp(Volume, szValue) == 0)
		{
			m_strVolumeDir = pChiled->Attribute(Dir);
		}
	}

	return true;
}
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;
}