Tileset::Tileset() { TiXmlDocument doc; // chargement des propriétés if (!doc.LoadFile(TILES_DEFINITION)) { DIE("can't load tiles definition '%s' (tinyxml: %s)", TILES_DEFINITION, doc.ErrorDesc()); } TiXmlHandle handle(&doc); handle = handle.FirstChildElement(); TiXmlNode* node = handle.FirstChildElement("definitions").FirstChildElement().Node(); while (node != NULL) { TiXmlElement* elem = node->ToElement(); std::string effect_name = elem->Attribute("effect"); Tile::Effect effect = Tile::DEFAULT; if (effect_name == "hole") { effect = Tile::HOLE; } else if (effect_name == "water") { effect = Tile::WATER; } else if (effect_name == "block") { effect = Tile::BLOCK; } else if (effect_name == "teleport") { effect = Tile::TELEPORT; } std::istringstream tiles(elem->GetText()); int tile_id; while (tiles.good()) { tiles >> tile_id; specials_[tile_id] = effect; } node = node->NextSibling(); } // tiles animées int from_id, to_id; TiXmlElement* elem = handle.FirstChildElement("animated").FirstChildElement().Element(); while (elem != NULL) { bool ok = true; ok &= (elem->QueryIntAttribute("from", &from_id) == TIXML_SUCCESS); ok &= (elem->QueryIntAttribute("to", &to_id) == TIXML_SUCCESS); if (ok) { animated_[from_id] = to_id; } else { puts("warning: invalid animated tiles (ignored)"); } elem = elem->NextSiblingElement(); } timer_ = 0.f; }
bool CEdl::ReadBeyondTV(const CStdString& strMovie) { Clear(); CStdString beyondTVFilename(URIUtils::ReplaceExtension(strMovie, URIUtils::GetExtension(strMovie) + ".chapters.xml")); if (!CFile::Exists(beyondTVFilename)) return false; TiXmlDocument xmlDoc; if (!xmlDoc.LoadFile(beyondTVFilename)) { CLog::Log(LOGERROR, "%s - Could not load Beyond TV file: %s. %s", __FUNCTION__, beyondTVFilename.c_str(), xmlDoc.ErrorDesc()); return false; } if (xmlDoc.Error()) { CLog::Log(LOGERROR, "%s - Could not parse Beyond TV file: %s. %s", __FUNCTION__, beyondTVFilename.c_str(), xmlDoc.ErrorDesc()); return false; } TiXmlElement *pRoot = xmlDoc.RootElement(); if (!pRoot || strcmp(pRoot->Value(), "cutlist")) { CLog::Log(LOGERROR, "%s - Invalid Beyond TV file: %s. Expected root node to be <cutlist>", __FUNCTION__, beyondTVFilename.c_str()); return false; } bool bValid = true; TiXmlElement *pRegion = pRoot->FirstChildElement("Region"); while (bValid && pRegion) { TiXmlElement *pStart = pRegion->FirstChildElement("start"); TiXmlElement *pEnd = pRegion->FirstChildElement("end"); if (pStart && pEnd && pStart->FirstChild() && pEnd->FirstChild()) { /* * Need to divide the start and end times by a factor of 10,000 to get msec. * E.g. <start comment="00:02:44.9980867">1649980867</start> * * Use atof so doesn't overflow 32 bit float or integer / long. * E.g. <end comment="0:26:49.0000009">16090090000</end> * * Don't use atoll even though it is more correct as it isn't natively supported by * Visual Studio. * * GetText() returns 0 if there were any problems and will subsequently be rejected in AddCut(). */ Cut cut; cut.start = (int64_t)(atof(pStart->GetText()) / 10000); cut.end = (int64_t)(atof(pEnd->GetText()) / 10000); cut.action = COMM_BREAK; bValid = AddCut(cut); } else bValid = false; pRegion = pRegion->NextSiblingElement("Region"); } if (!bValid) { CLog::Log(LOGERROR, "%s - Invalid Beyond TV file: %s. Clearing any valid commercial breaks found.", __FUNCTION__, beyondTVFilename.c_str()); Clear(); return false; } else if (HasCut()) { CLog::Log(LOGDEBUG, "%s - Read %"PRIuS" commercial breaks from Beyond TV file: %s", __FUNCTION__, m_vecCuts.size(), beyondTVFilename.c_str()); return true; } else { CLog::Log(LOGDEBUG, "%s - No commercial breaks found in Beyond TV file: %s", __FUNCTION__, beyondTVFilename.c_str()); return false; } }
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(); } }
bool CGUIWindow::LoadXML(const CStdString &strPath, const CStdString &strLowerPath) { TiXmlDocument xmlDoc; if ( !xmlDoc.LoadFile(strPath) && !xmlDoc.LoadFile(CStdString(strPath).ToLower()) && !xmlDoc.LoadFile(strLowerPath)) { CLog::Log(LOGERROR, "unable to load:%s, Line %d\n%s", strPath.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); SetID(WINDOW_INVALID); return false; } return Load(xmlDoc); }
bool mitk::SceneIO::SaveScene( DataStorage::SetOfObjects::ConstPointer sceneNodes, const DataStorage* storage, const std::string& filename) { if (!sceneNodes) { MITK_ERROR << "No set of nodes given. Not possible to save scene."; return false; } if (!storage) { MITK_ERROR << "No data storage given. Not possible to save scene."; // \TODO: Technically, it would be possible to save the nodes without their relation return false; } if ( filename.empty() ) { MITK_ERROR << "No filename given. Not possible to save scene."; return false; } try { m_FailedNodes = DataStorage::SetOfObjects::New(); m_FailedProperties = PropertyList::New(); // start XML DOM TiXmlDocument document; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "UTF-8", "" ); // TODO what to write here? encoding? standalone would mean that we provide a DTD somewhere... document.LinkEndChild( decl ); TiXmlElement* version = new TiXmlElement("Version"); version->SetAttribute("Writer", __FILE__ ); version->SetAttribute("Revision", "$Revision: 17055 $" ); version->SetAttribute("FileVersion", 1 ); document.LinkEndChild(version); //DataStorage::SetOfObjects::ConstPointer sceneNodes = storage->GetSubset( predicate ); if ( sceneNodes.IsNull() ) { MITK_WARN << "Saving empty scene to " << filename; } else { if ( sceneNodes->size() == 0 ) { MITK_WARN << "Saving empty scene to " << filename; } MITK_INFO << "Storing scene with " << sceneNodes->size() << " objects to " << filename; m_WorkingDirectory = CreateEmptyTempDirectory(); if (m_WorkingDirectory.empty()) { MITK_ERROR << "Could not create temporary directory. Cannot create scene files."; return false; } ProgressBar::GetInstance()->AddStepsToDo( sceneNodes->size() ); // find out about dependencies typedef std::map< DataNode*, std::string > UIDMapType; typedef std::map< DataNode*, std::list<std::string> > SourcesMapType; UIDMapType nodeUIDs; // for dependencies: ID of each node SourcesMapType sourceUIDs; // for dependencies: IDs of a node's parent nodes UIDGenerator nodeUIDGen("OBJECT_"); for (DataStorage::SetOfObjects::const_iterator iter = sceneNodes->begin(); iter != sceneNodes->end(); ++iter) { DataNode* node = iter->GetPointer(); if (!node) continue; // unlikely event that we get a NULL pointer as an object for saving. just ignore // generate UIDs for all source objects DataStorage::SetOfObjects::ConstPointer sourceObjects = storage->GetSources( node ); for ( mitk::DataStorage::SetOfObjects::const_iterator sourceIter = sourceObjects->begin(); sourceIter != sourceObjects->end(); ++sourceIter ) { if ( std::find( sceneNodes->begin(), sceneNodes->end(), *sourceIter ) == sceneNodes->end() ) continue; // source is not saved, so don't generate a UID for this source // create a uid for the parent object if ( nodeUIDs[ *sourceIter ].empty() ) { nodeUIDs[ *sourceIter ] = nodeUIDGen.GetUID(); } // store this dependency for writing sourceUIDs[ node ].push_back( nodeUIDs[*sourceIter] ); } if ( nodeUIDs[ node ].empty() ) { nodeUIDs[ node ] = nodeUIDGen.GetUID(); } } // write out objects, dependencies and properties for (DataStorage::SetOfObjects::const_iterator iter = sceneNodes->begin(); iter != sceneNodes->end(); ++iter) { DataNode* node = iter->GetPointer(); if (node) { TiXmlElement* nodeElement = new TiXmlElement("node"); std::string filenameHint( node->GetName() ); filenameHint = itksys::SystemTools::MakeCindentifier(filenameHint.c_str()); // escape filename <-- only allow [A-Za-z0-9_], replace everything else with _ // store dependencies UIDMapType::iterator searchUIDIter = nodeUIDs.find(node); if ( searchUIDIter != nodeUIDs.end() ) { // store this node's ID nodeElement->SetAttribute("UID", searchUIDIter->second.c_str() ); } SourcesMapType::iterator searchSourcesIter = sourceUIDs.find(node); if ( searchSourcesIter != sourceUIDs.end() ) { // store all source IDs for ( std::list<std::string>::iterator sourceUIDIter = searchSourcesIter->second.begin(); sourceUIDIter != searchSourcesIter->second.end(); ++sourceUIDIter ) { TiXmlElement* uidElement = new TiXmlElement("source"); uidElement->SetAttribute("UID", sourceUIDIter->c_str() ); nodeElement->LinkEndChild( uidElement ); } } // store basedata if ( BaseData* data = node->GetData() ) { //std::string filenameHint( node->GetName() ); bool error(false); TiXmlElement* dataElement( SaveBaseData( data, filenameHint, error ) ); // returns a reference to a file if (error) { m_FailedNodes->push_back( node ); } // store basedata properties PropertyList* propertyList = data->GetPropertyList(); if (propertyList && !propertyList->IsEmpty() ) { TiXmlElement* baseDataPropertiesElement( SavePropertyList( propertyList, filenameHint + "-data") ); // returns a reference to a file dataElement->LinkEndChild( baseDataPropertiesElement ); } nodeElement->LinkEndChild( dataElement ); } // store all renderwindow specific propertylists const RenderingManager::RenderWindowVector& allRenderWindows( RenderingManager::GetInstance()->GetAllRegisteredRenderWindows() ); for ( RenderingManager::RenderWindowVector::const_iterator rw = allRenderWindows.begin(); rw != allRenderWindows.end(); ++rw) { if (vtkRenderWindow* renderWindow = *rw) { std::string renderWindowName( mitk::BaseRenderer::GetInstance(renderWindow)->GetName() ); BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(renderWindow); PropertyList* propertyList = node->GetPropertyList(renderer); if ( propertyList && !propertyList->IsEmpty() ) { TiXmlElement* renderWindowPropertiesElement( SavePropertyList( propertyList, filenameHint + "-" + renderWindowName) ); // returns a reference to a file renderWindowPropertiesElement->SetAttribute("renderwindow", renderWindowName); nodeElement->LinkEndChild( renderWindowPropertiesElement ); } } } // don't forget the renderwindow independent list PropertyList* propertyList = node->GetPropertyList(); if ( propertyList && !propertyList->IsEmpty() ) { TiXmlElement* propertiesElement( SavePropertyList( propertyList, filenameHint + "-node") ); // returns a reference to a file nodeElement->LinkEndChild( propertiesElement ); } document.LinkEndChild( nodeElement ); } else { MITK_WARN << "Ignoring NULL node during scene serialization."; } ProgressBar::GetInstance()->Progress(); } // end for all nodes } // end if sceneNodes if ( !document.SaveFile( m_WorkingDirectory + Poco::Path::separator() + "index.xml" ) ) { MITK_ERROR << "Could not write scene to " << m_WorkingDirectory << Poco::Path::separator() << "index.xml" << "\nTinyXML reports '" << document.ErrorDesc() << "'"; return false; } else { try { Poco::File deleteFile( filename.c_str() ); if (deleteFile.exists()) { deleteFile.remove(); } // create zip at filename std::ofstream file( filename.c_str(), std::ios::binary | std::ios::out); if (!file.good()) { MITK_ERROR << "Could not open a zip file for writing: '" << filename << "'"; } else { Poco::Zip::Compress zipper( file, true ); Poco::Path tmpdir( m_WorkingDirectory ); zipper.addRecursive( tmpdir ); zipper.close(); } try { Poco::File deleteDir( m_WorkingDirectory ); deleteDir.remove(true); // recursive } catch(...) { MITK_ERROR << "Could not delete temporary directory " << m_WorkingDirectory; return false; // ok? } } catch(std::exception& e) { MITK_ERROR << "Could not create ZIP file from " << m_WorkingDirectory << "\nReason: " << e.what(); return false; } return true; } } catch(std::exception& e) { MITK_ERROR << "Caught exception during saving temporary files to disk. Error description: '" << e.what() << "'"; return false; } }
void Map::ParseText(const string &text) { // Create a tiny xml document and use it to parse the text. TiXmlDocument doc; doc.Parse(text.c_str()); // Check for parsing errors. if (doc.Error()) { has_error = true; error_code = TMX_PARSING_ERROR; error_text = doc.ErrorDesc(); return; } TiXmlNode *mapNode = doc.FirstChild("map"); TiXmlElement* mapElem = mapNode->ToElement(); // Read the map attributes. mapElem->Attribute("version", &version); mapElem->Attribute("width", &width); mapElem->Attribute("height", &height); mapElem->Attribute("tilewidth", &tile_width); mapElem->Attribute("tileheight", &tile_height); // Read the orientation std::string orientationStr = mapElem->Attribute("orientation"); if (!orientationStr.compare("orthogonal")) { orientation = TMX_MO_ORTHOGONAL; } else if (!orientationStr.compare("isometric")) { orientation = TMX_MO_ISOMETRIC; } else if (!orientationStr.compare("staggered")) { orientation = TMX_MO_STAGGERED; } const TiXmlNode *node = mapElem->FirstChild(); int zOrder = 0; while( node ) { // Read the map properties. if( strcmp( node->Value(), "properties" ) == 0 ) { properties.Parse(node); } // Iterate through all of the tileset elements. if( strcmp( node->Value(), "tileset" ) == 0 ) { // Allocate a new tileset and parse it. Tileset *tileset = new Tileset(); tileset->Parse(node->ToElement()); // Add the tileset to the list. tilesets.push_back(tileset); } // Iterate through all of the layer elements. if( strcmp( node->Value(), "layer" ) == 0 ) { // Allocate a new layer and parse it. Layer *layer = new Layer(this); layer->Parse(node); layer->SetZOrder( zOrder ); ++zOrder; // Add the layer to the list. layers.push_back(layer); } // Iterate through all of the imagen layer elements. if( strcmp( node->Value(), "imagelayer" ) == 0 ) { // Allocate a new layer and parse it. ImageLayer *imageLayer = new ImageLayer(this); imageLayer->Parse(node); imageLayer->SetZOrder( zOrder ); ++zOrder; // Add the layer to the list. image_layers.push_back(imageLayer); } // Iterate through all of the objectgroup elements. if( strcmp( node->Value(), "objectgroup" ) == 0 ) { // Allocate a new object group and parse it. ObjectGroup *objectGroup = new ObjectGroup(); objectGroup->Parse(node); objectGroup->SetZOrder( zOrder ); ++zOrder; // Add the object group to the list. object_groups.push_back(objectGroup); } node = node->NextSibling(); } }
bool CSavestate::Deserialize(const std::string& path) { Reset(); TiXmlDocument xmlFile; if (!xmlFile.LoadFile(path)) { CLog::Log(LOGERROR, "Failed to open %s: %s", path.c_str(), xmlFile.ErrorDesc()); return false; } TiXmlElement* pElement = xmlFile.RootElement(); if (!pElement || pElement->NoChildren() || pElement->ValueStr() != SAVESTATE_XML_ROOT) { CLog::Log(LOGERROR, "Can't find root <%s> tag", SAVESTATE_XML_ROOT); return false; } // Path if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_PATH, m_path)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_PATH); return false; } // Type std::string type; if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_TYPE, type)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_TYPE); return false; } m_type = CSavestateTranslator::TranslateType(type); if (m_type == SAVETYPE::UNKNOWN) { CLog::Log(LOGERROR, "Invalid savestate type: %s", type.c_str()); return false; } // Slot if (m_type == SAVETYPE::SLOT) { if (!XMLUtils::GetInt(pElement, SAVESTATE_FIELD_SLOT, m_slot)) { CLog::Log(LOGERROR, "Savestate has type \"%s\" but no <%s> element!", type.c_str(), SAVESTATE_FIELD_TYPE); return false; } if (m_slot < 0) { CLog::Log(LOGERROR, "Invalid savestate slot: %d", m_slot); return false; } } // Label (optional) XMLUtils::GetString(pElement, SAVESTATE_FIELD_LABEL, m_label); // Size long size; if (!XMLUtils::GetLong(pElement, SAVESTATE_FIELD_SIZE, size)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_SIZE); return false; } if (size < 0) { CLog::Log(LOGERROR, "Invalid savestate size: %ld", size); return false; } m_size = size; // Game client if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_GAMECLIENT, m_gameClient)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_GAMECLIENT); return false; } // Game path if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_GAME_PATH, m_gamePath)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_GAME_PATH); return false; } // Game CRC if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_GAME_CRC, m_gameCRC)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_GAME_CRC); return false; } // Playtime (frames) long playtimeFrames; if (!XMLUtils::GetLong(pElement, SAVESTATE_FIELD_FRAMES, playtimeFrames)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_FRAMES); return false; } if (playtimeFrames < 0) { CLog::Log(LOGERROR, "Invalid savestate frame count: %ld", playtimeFrames); return false; } m_size = playtimeFrames; // Playtime (wall clock) float playtimeWallClock; if (!XMLUtils::GetFloat(pElement, SAVESTATE_FIELD_WALLCLOCK, playtimeWallClock)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_WALLCLOCK); return false; } m_playtimeWallClock = playtimeWallClock; // Timestamp std::string timestamp; if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_TIMESTAMP, timestamp)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_TIMESTAMP); return false; } if (!m_timestamp.SetFromDBDateTime(timestamp)) { CLog::Log(LOGERROR, "Invalid savestate timestamp: %s", timestamp.c_str()); return false; } // Thumbnail if (!XMLUtils::GetString(pElement, SAVESTATE_FIELD_THUMBNAIL, m_thumbnail)) { CLog::Log(LOGERROR, "Savestate has no <%s> element", SAVESTATE_FIELD_THUMBNAIL); return false; } return true; }
bool CLangInfo::Load(const CStdString& strFileName) { SetDefaults(); TiXmlDocument xmlDoc; if (!xmlDoc.LoadFile(strFileName)) { CLog::Log(LOGERROR, "unable to load %s: %s at line %d", strFileName.c_str(), xmlDoc.ErrorDesc(), xmlDoc.ErrorRow()); return false; } TiXmlElement* pRootElement = xmlDoc.RootElement(); CStdString strValue = pRootElement->Value(); if (strValue != CStdString("language")) { CLog::Log(LOGERROR, "%s Doesn't contain <language>", strFileName.c_str()); return false; } const TiXmlNode *pCharSets = pRootElement->FirstChild("charsets"); if (pCharSets && !pCharSets->NoChildren()) { const TiXmlNode *pGui = pCharSets->FirstChild("gui"); if (pGui && !pGui->NoChildren()) { CStdString strForceUnicodeFont = ((TiXmlElement*) pGui)->Attribute("unicodefont"); if (strForceUnicodeFont.Equals("true")) m_defaultRegion.m_forceUnicodeFont=true; m_defaultRegion.m_strGuiCharSet=pGui->FirstChild()->Value(); } const TiXmlNode *pSubtitle = pCharSets->FirstChild("subtitle"); if (pSubtitle && !pSubtitle->NoChildren()) m_defaultRegion.m_strSubtitleCharSet=pSubtitle->FirstChild()->Value(); } const TiXmlNode *pDVD = pRootElement->FirstChild("dvd"); if (pDVD && !pDVD->NoChildren()) { const TiXmlNode *pMenu = pDVD->FirstChild("menu"); if (pMenu && !pMenu->NoChildren()) m_defaultRegion.m_strDVDMenuLanguage=pMenu->FirstChild()->Value(); const TiXmlNode *pAudio = pDVD->FirstChild("audio"); if (pAudio && !pAudio->NoChildren()) m_defaultRegion.m_strDVDAudioLanguage=pAudio->FirstChild()->Value(); const TiXmlNode *pSubtitle = pDVD->FirstChild("subtitle"); if (pSubtitle && !pSubtitle->NoChildren()) m_defaultRegion.m_strDVDSubtitleLanguage=pSubtitle->FirstChild()->Value(); } const TiXmlNode *pRegions = pRootElement->FirstChild("regions"); if (pRegions && !pRegions->NoChildren()) { const TiXmlElement *pRegion=pRegions->FirstChildElement("region"); while (pRegion) { CRegion region(m_defaultRegion); region.m_strName=pRegion->Attribute("name"); if (region.m_strName.IsEmpty()) region.m_strName="N/A"; const TiXmlNode *pDateLong=pRegion->FirstChild("datelong"); if (pDateLong && !pDateLong->NoChildren()) region.m_strDateFormatLong=pDateLong->FirstChild()->Value(); const TiXmlNode *pDateShort=pRegion->FirstChild("dateshort"); if (pDateShort && !pDateShort->NoChildren()) region.m_strDateFormatShort=pDateShort->FirstChild()->Value(); const TiXmlElement *pTime=pRegion->FirstChildElement("time"); if (pTime && !pTime->NoChildren()) { region.m_strTimeFormat=pTime->FirstChild()->Value(); region.m_strMeridiemSymbols[MERIDIEM_SYMBOL_AM]=pTime->Attribute("symbolAM"); region.m_strMeridiemSymbols[MERIDIEM_SYMBOL_PM]=pTime->Attribute("symbolPM"); } const TiXmlNode *pTempUnit=pRegion->FirstChild("tempunit"); if (pTempUnit && !pTempUnit->NoChildren()) region.SetTempUnit(pTempUnit->FirstChild()->Value()); const TiXmlNode *pSpeedUnit=pRegion->FirstChild("speedunit"); if (pSpeedUnit && !pSpeedUnit->NoChildren()) region.SetSpeedUnit(pSpeedUnit->FirstChild()->Value()); const TiXmlNode *pTimeZone=pRegion->FirstChild("timezone"); if (pTimeZone && !pTimeZone->NoChildren()) region.SetTimeZone(pTimeZone->FirstChild()->Value()); m_regions.insert(PAIR_REGIONS(region.m_strName, region)); pRegion=pRegion->NextSiblingElement("region"); } const CStdString& strName=g_guiSettings.GetString("locale.country"); SetCurrentRegion(strName); } const TiXmlNode *pTokens = pRootElement->FirstChild("sorttokens"); if (pTokens && !pTokens->NoChildren()) { const TiXmlNode *pToken = pTokens->FirstChild("token"); while (pToken) { if (pToken->FirstChild() && pToken->FirstChild()->Value()) { g_advancedSettings.m_vecTokens.push_back(CStdString(pToken->FirstChild()->Value()) + " "); g_advancedSettings.m_vecTokens.push_back(CStdString(pToken->FirstChild()->Value()) + "."); } pToken = pToken->NextSibling(); } } return true; }
KmlPastebufferType Kml::ParsePasteBuffer() { if( !wxTheClipboard->IsOpened() ) if( ! wxTheClipboard->Open() ) return KML_PASTE_INVALID; wxTextDataObject data; wxTheClipboard->GetData( data ); kmlText = data.GetText(); wxTheClipboard->Close(); if( kmlText.Find( _T("<kml") ) == wxNOT_FOUND ) return KML_PASTE_INVALID; TiXmlDocument doc; if( ! doc.Parse( kmlText.mb_str( wxConvUTF8 ), 0, TIXML_ENCODING_UTF8 ) ) { wxLogError( wxString( doc.ErrorDesc(), wxConvUTF8 ) ); return KML_PASTE_INVALID; } if( 0 != strncmp( doc.RootElement()->Value(), "kml", 3 ) ) return KML_PASTE_INVALID; TiXmlHandle docHandle( doc.RootElement() ); // We may or may not have a <document> depending on what the user copied. TiXmlElement* placemark = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).ToElement(); if( ! placemark ) { placemark = docHandle.FirstChild( "Placemark" ).ToElement(); } if( ! placemark ) { wxString msg( _T("KML Parser found no <Placemark> tag in the KML.") ); wxLogMessage( msg ); return KML_PASTE_INVALID; } int pointCounter = 0; wxString name; for( ; placemark; placemark=placemark->NextSiblingElement() ) { TiXmlElement* e = placemark->FirstChildElement( "name" ); if( e ) name = wxString( e->GetText(),wxConvUTF8 ); pointCounter++; } if( pointCounter == 1 ) { // Is it a single waypoint? TiXmlNode* element = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).FirstChild( "Point" ).ToNode(); if( ! element ) element = docHandle.FirstChild( "Placemark" ).FirstChild( "Point" ).ToNode(); if( element ) return ParseOnePlacemarkPoint( element, name ); // Is it a dumb <LineString> track? element = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).FirstChild( "LineString" ).ToNode(); if( ! element ) element = docHandle.FirstChild( "Placemark" ).FirstChild( "LineString" ).ToNode(); if( element ) return ParseTrack( element, name ); // Is it a smart extended <gx:track> track? element = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).FirstChild( "gx:Track" ).ToNode(); if( ! element ) element = docHandle.FirstChild( "Placemark" ).FirstChild( "gx:Track" ).ToNode(); if( element ) return ParseTrack( element, name ); wxString msg( _T("KML Parser found a single <Placemark> in the KML, but no useable data in it.") ); wxLogMessage( msg ); return KML_PASTE_INVALID; } // Here we go with a full route. parsedRoute = new Route(); bool foundPoints = false; bool foundTrack = false; TiXmlElement* element = docHandle.FirstChild( "Document" ).FirstChild( "name" ).ToElement(); if( element ) parsedRoute->m_RouteNameString = wxString( element->GetText(), wxConvUTF8 ); RoutePoint* rp = NULL; placemark = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).ToElement(); for( ; placemark; placemark=placemark->NextSiblingElement() ) { TiXmlNode* n = placemark->FirstChild( "Point" ); if( n ) { if( ParseOnePlacemarkPoint( n->ToElement(), name ) == KML_PASTE_WAYPOINT ) { parsedRoute->AddPoint( new RoutePoint( parsedRoutePoint ) ); delete parsedRoutePoint; parsedRoutePoint = 0; foundPoints = true; } } n = placemark->FirstChild( "LineString" ); if( n ) { ParseTrack( n->ToElement(), name ); foundTrack = true; } n = placemark->FirstChild( "gx:Track" ); if( n ) { ParseTrack( n->ToElement(), name ); foundTrack = true; } } if( foundPoints && parsedRoute->GetnPoints() < 2 ) { wxString msg( _T("KML Parser did not find enough <Point>s to make a route.") ); wxLogMessage( msg ); foundPoints = false; } if( foundPoints && ! foundTrack ) return KML_PASTE_ROUTE; if( foundPoints && foundTrack ) return KML_PASTE_ROUTE_TRACK; if( ! foundPoints && foundTrack ) return KML_PASTE_TRACK; return KML_PASTE_INVALID; }
bool CButtonTranslator::LoadKeymap(const CStdString &keymapPath) { TiXmlDocument xmlDoc; CLog::Log(LOGINFO, "Loading %s", keymapPath.c_str()); if (!xmlDoc.LoadFile(keymapPath)) { CLog::Log(LOGERROR, "Error loading keymap: %s, Line %d\n%s", keymapPath.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; } TiXmlElement* pRoot = xmlDoc.RootElement(); CStdString strValue = pRoot->Value(); if ( strValue != "keymap") { CLog::Log(LOGERROR, "%s Doesn't contain <keymap>", keymapPath.c_str()); return false; } // run through our window groups TiXmlNode* pWindow = pRoot->FirstChild(); while (pWindow) { if (pWindow->Type() == TiXmlNode::ELEMENT) { int windowID = WINDOW_INVALID; const char *szWindow = pWindow->Value(); if (szWindow) { if (strcmpi(szWindow, "global") == 0) windowID = -1; else windowID = TranslateWindow(szWindow); } MapWindowActions(pWindow, windowID); } pWindow = pWindow->NextSibling(); } return true; }
void mitk::PlanarFigureWriter::GenerateData() { m_Success = false; if (!m_WriteToMemory && m_FileName.empty()) { MITK_ERROR << "Could not write planar figures. File name is invalid"; throw std::invalid_argument("file name is empty"); } TiXmlDocument document; auto decl = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc.... document.LinkEndChild( decl ); auto version = new TiXmlElement("Version"); version->SetAttribute("Writer", __FILE__ ); version->SetAttribute("CVSRevision", "$Revision: 17055 $" ); version->SetAttribute("FileVersion", 1 ); document.LinkEndChild(version); /* create xml element for each input */ for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i ) { // Create root element for this PlanarFigure InputType::Pointer pf = this->GetInput( i ); if (pf.IsNull()) continue; auto pfElement = new TiXmlElement("PlanarFigure"); pfElement->SetAttribute("type", pf->GetNameOfClass()); document.LinkEndChild(pfElement); if ( pf->GetNumberOfControlPoints() == 0 ) continue; //PlanarFigure::VertexContainerType* vertices = pf->GetControlPoints(); //if (vertices == NULL) // continue; // Serialize property list of PlanarFigure mitk::PropertyList::Pointer propertyList = pf->GetPropertyList(); mitk::PropertyList::PropertyMap::const_iterator it; for ( it = propertyList->GetMap()->begin(); it != propertyList->GetMap()->end(); ++it ) { // Create seralizer for this property const mitk::BaseProperty* prop = it->second; std::string serializerName = std::string( prop->GetNameOfClass() ) + "Serializer"; std::list< itk::LightObject::Pointer > allSerializers = itk::ObjectFactoryBase::CreateAllInstance( serializerName.c_str() ); if ( allSerializers.size() != 1 ) { // No or too many serializer(s) found, skip this property continue; } mitk::BasePropertySerializer* serializer = dynamic_cast< mitk::BasePropertySerializer* >( allSerializers.begin()->GetPointer() ); if ( serializer == nullptr ) { // Serializer not valid; skip this property } auto keyElement = new TiXmlElement( "property" ); keyElement->SetAttribute( "key", it->first ); keyElement->SetAttribute( "type", prop->GetNameOfClass() ); serializer->SetProperty( prop ); TiXmlElement* valueElement = nullptr; try { valueElement = serializer->Serialize(); } catch (...) { } if ( valueElement == nullptr ) { // Serialization failed; skip this property continue; } // Add value to property element keyElement->LinkEndChild( valueElement ); // Append serialized property to property list pfElement->LinkEndChild( keyElement ); } // Serialize control points of PlanarFigure auto controlPointsElement = new TiXmlElement("ControlPoints"); pfElement->LinkEndChild(controlPointsElement); for (unsigned int i = 0; i < pf->GetNumberOfControlPoints(); i++) { auto vElement = new TiXmlElement("Vertex"); vElement->SetAttribute("id", i); vElement->SetDoubleAttribute("x", pf->GetControlPoint(i)[0]); vElement->SetDoubleAttribute("y", pf->GetControlPoint(i)[1]); controlPointsElement->LinkEndChild(vElement); } auto geoElement = new TiXmlElement("Geometry"); const PlaneGeometry* planeGeo = dynamic_cast<const PlaneGeometry*>(pf->GetPlaneGeometry()); if (planeGeo != nullptr) { // Write parameters of IndexToWorldTransform of the PlaneGeometry typedef mitk::Geometry3D::TransformType TransformType; const TransformType* affineGeometry = planeGeo->GetIndexToWorldTransform(); const TransformType::ParametersType& parameters = affineGeometry->GetParameters(); auto vElement = new TiXmlElement( "transformParam" ); for ( unsigned int i = 0; i < affineGeometry->GetNumberOfParameters(); ++i ) { std::stringstream paramName; paramName << "param" << i; vElement->SetDoubleAttribute( paramName.str().c_str(), parameters.GetElement( i ) ); } geoElement->LinkEndChild( vElement ); // Write bounds of the PlaneGeometry typedef mitk::Geometry3D::BoundsArrayType BoundsArrayType; const BoundsArrayType& bounds = planeGeo->GetBounds(); vElement = new TiXmlElement( "boundsParam" ); for ( unsigned int i = 0; i < 6; ++i ) { std::stringstream boundName; boundName << "bound" << i; vElement->SetDoubleAttribute( boundName.str().c_str(), bounds.GetElement( i ) ); } geoElement->LinkEndChild( vElement ); // Write spacing and origin of the PlaneGeometry Vector3D spacing = planeGeo->GetSpacing(); Point3D origin = planeGeo->GetOrigin(); geoElement->LinkEndChild(this->CreateXMLVectorElement("Spacing", spacing)); geoElement->LinkEndChild(this->CreateXMLVectorElement("Origin", origin)); pfElement->LinkEndChild(geoElement); } } if(m_WriteToMemory) { // Declare a printer TiXmlPrinter printer; // attach it to the document you want to convert in to a std::string document.Accept(&printer); // Create memory buffer and print tinyxmldocument there... m_MemoryBufferSize = printer.Size() + 1; m_MemoryBuffer = new char[m_MemoryBufferSize]; strcpy(m_MemoryBuffer,printer.CStr()); } else { if (document.SaveFile( m_FileName) == false) { MITK_ERROR << "Could not write planar figures to " << m_FileName << "\nTinyXML reports '" << document.ErrorDesc() << "'"; throw std::ios_base::failure("Error during writing of planar figure xml file."); } } m_Success = true; }
void CSlingboxFile::LoadSettings(const CStdString& strHostname) { // Load default settings m_sSlingboxSettings.strHostname = strHostname; m_sSlingboxSettings.iVideoWidth = 320; m_sSlingboxSettings.iVideoHeight = 240; m_sSlingboxSettings.iVideoResolution = (int)CSlingbox::RESOLUTION320X240; m_sSlingboxSettings.iVideoBitrate = 704; m_sSlingboxSettings.iVideoFramerate = 30; m_sSlingboxSettings.iVideoSmoothing = 50; m_sSlingboxSettings.iAudioBitrate = 64; m_sSlingboxSettings.iIFrameInterval = 10; m_sSlingboxSettings.uiCodeChannelUp = 0; m_sSlingboxSettings.uiCodeChannelDown = 0; for (unsigned int i = 0; i < 10; i++) m_sSlingboxSettings.uiCodeNumber[i] = 0; // Check if a SlingboxSettings.xml file exists CStdString slingboxXMLFile = g_settings.GetUserDataItem("SlingboxSettings.xml"); if (!CFile::Exists(slingboxXMLFile)) { CLog::Log(LOGNOTICE, "No SlingboxSettings.xml file (%s) found - using default settings", slingboxXMLFile.c_str()); return; } // Load the XML file TiXmlDocument slingboxXML; if (!slingboxXML.LoadFile(slingboxXMLFile)) { CLog::Log(LOGERROR, "%s - Error loading %s - line %d\n%s", __FUNCTION__, slingboxXMLFile.c_str(), slingboxXML.ErrorRow(), slingboxXML.ErrorDesc()); return; } // Check to make sure layout is correct TiXmlElement * pRootElement = slingboxXML.RootElement(); if (!pRootElement || strcmpi(pRootElement->Value(), "slingboxsettings") != 0) { CLog::Log(LOGERROR, "%s - Error loading %s - no <slingboxsettings> node found", __FUNCTION__, slingboxXMLFile.c_str()); return; } // Success so far CLog::Log(LOGNOTICE, "Loaded SlingboxSettings.xml from %s", slingboxXMLFile.c_str()); // Search for the first settings that specify no hostname or match our hostname TiXmlElement *pElement; for (pElement = pRootElement->FirstChildElement("slingbox"); pElement; pElement = pElement->NextSiblingElement("slingbox")) { if (pElement->Attribute("hostname") == NULL || !m_sSlingboxSettings.strHostname.CompareNoCase(pElement->Attribute("hostname"))) { // Load setting values XMLUtils::GetInt(pElement, "width", m_sSlingboxSettings.iVideoWidth, 0, 640); XMLUtils::GetInt(pElement, "height", m_sSlingboxSettings.iVideoHeight, 0, 480); XMLUtils::GetInt(pElement, "videobitrate", m_sSlingboxSettings.iVideoBitrate, 50, 8000); XMLUtils::GetInt(pElement, "framerate", m_sSlingboxSettings.iVideoFramerate, 1, 30); XMLUtils::GetInt(pElement, "smoothing", m_sSlingboxSettings.iVideoSmoothing, 0, 100); XMLUtils::GetInt(pElement, "audiobitrate", m_sSlingboxSettings.iAudioBitrate, 16, 96); XMLUtils::GetInt(pElement, "iframeinterval", m_sSlingboxSettings.iIFrameInterval, 1, 30); // Load any button code values TiXmlElement * pCodes = pElement->FirstChildElement("buttons"); if (pCodes) { XMLUtils::GetHex(pCodes, "channelup", m_sSlingboxSettings.uiCodeChannelUp); XMLUtils::GetHex(pCodes, "channeldown", m_sSlingboxSettings.uiCodeChannelDown); XMLUtils::GetHex(pCodes, "zero", m_sSlingboxSettings.uiCodeNumber[0]); XMLUtils::GetHex(pCodes, "one", m_sSlingboxSettings.uiCodeNumber[1]); XMLUtils::GetHex(pCodes, "two", m_sSlingboxSettings.uiCodeNumber[2]); XMLUtils::GetHex(pCodes, "three", m_sSlingboxSettings.uiCodeNumber[3]); XMLUtils::GetHex(pCodes, "four", m_sSlingboxSettings.uiCodeNumber[4]); XMLUtils::GetHex(pCodes, "five", m_sSlingboxSettings.uiCodeNumber[5]); XMLUtils::GetHex(pCodes, "six", m_sSlingboxSettings.uiCodeNumber[6]); XMLUtils::GetHex(pCodes, "seven", m_sSlingboxSettings.uiCodeNumber[7]); XMLUtils::GetHex(pCodes, "eight", m_sSlingboxSettings.uiCodeNumber[8]); XMLUtils::GetHex(pCodes, "nine", m_sSlingboxSettings.uiCodeNumber[9]); } break; } } // Prepare our resolution enum mapping array const struct { unsigned int uiWidth; unsigned int uiHeight; CSlingbox::Resolution eEnum; } m_resolutionMap[11] = { {0, 0, CSlingbox::NOVIDEO}, {128, 96, CSlingbox::RESOLUTION128X96}, {160, 120, CSlingbox::RESOLUTION160X120}, {176, 120, CSlingbox::RESOLUTION176X120}, {224, 176, CSlingbox::RESOLUTION224X176}, {256, 192, CSlingbox::RESOLUTION256X192}, {320, 240, CSlingbox::RESOLUTION320X240}, {352, 240, CSlingbox::RESOLUTION352X240}, {320, 480, CSlingbox::RESOLUTION320X480}, {640, 240, CSlingbox::RESOLUTION640X240}, {640, 480, CSlingbox::RESOLUTION640X480} }; // See if the specified resolution matches something in our mapping array and // setup things accordingly for (unsigned int i = 0; i < 11; i++) { if (m_sSlingboxSettings.iVideoWidth == (int)m_resolutionMap[i].uiWidth && m_sSlingboxSettings.iVideoHeight == (int)m_resolutionMap[i].uiHeight) { m_sSlingboxSettings.iVideoResolution = (int)m_resolutionMap[i].eEnum; return; } } // If it didn't match anything setup safe defaults CLog::Log(LOGERROR, "%s - Defaulting to 320x240 resolution due to invalid " "resolution specified in SlingboxSettings.xml for Slingbox: %s", __FUNCTION__, m_sSlingboxSettings.strHostname.c_str()); m_sSlingboxSettings.iVideoWidth = 320; m_sSlingboxSettings.iVideoHeight = 240; m_sSlingboxSettings.iVideoResolution = (int)CSlingbox::RESOLUTION320X240; }
void ThingTypeManager::loadXml(const std::string& file) { try { if(!isOtbLoaded()) stdext::throw_exception("OTB must be loaded before XML"); TiXmlDocument doc; doc.Parse(g_resources.readFileContents(file).c_str()); if(doc.Error()) stdext::throw_exception(stdext::format("failed to parse '%s': '%s'", file, doc.ErrorDesc())); TiXmlElement* root = doc.FirstChildElement(); if(!root || root->ValueTStr() != "items") stdext::throw_exception("invalid root tag name"); for(TiXmlElement *element = root->FirstChildElement(); element; element = element->NextSiblingElement()) { if(unlikely(element->ValueTStr() != "item")) continue; uint16 id = element->readType<uint16>("id"); if(id != 0) { std::vector<std::string> s_ids = stdext::split(element->Attribute("id"), ";"); for(const std::string& s : s_ids) { std::vector<int32> ids = stdext::split<int32>(s, "-"); if(ids.size() > 1) { int32 i = ids[0]; while(i <= ids[1]) parseItemType(i++, element); } else parseItemType(atoi(s.c_str()), element); } } else { std::vector<int32> begin = stdext::split<int32>(element->Attribute("fromid"), ";"); std::vector<int32> end = stdext::split<int32>(element->Attribute("toid"), ";"); if(begin[0] && begin.size() == end.size()) { size_t size = begin.size(); for(size_t i = 0; i < size; ++i) while(begin[i] <= end[i]) parseItemType(begin[i]++, element); } } } doc.Clear(); m_xmlLoaded = true; g_logger.debug("items.xml read successfully."); } catch(std::exception& e) { g_logger.error(stdext::format("Failed to load '%s' (XML file): %s", file, e.what())); } }
bool CMediaManager::LoadSources() { // clear our location list m_locations.clear(); // load xml file... TiXmlDocument xmlDoc; if ( !xmlDoc.LoadFile( MEDIA_SOURCES_XML ) ) return false; TiXmlElement* pRootElement = xmlDoc.RootElement(); if ( !pRootElement || strcmpi(pRootElement->Value(), "mediasources") != 0) { CLog::Log(LOGERROR, "Error loading %s, Line %d (%s)", MEDIA_SOURCES_XML, xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; } // load the <network> block TiXmlNode *pNetwork = pRootElement->FirstChild("network"); if (pNetwork) { TiXmlElement *pLocation = pNetwork->FirstChildElement("location"); while (pLocation) { CNetworkLocation location; pLocation->Attribute("id", &location.id); if (pLocation->FirstChild()) { location.path = pLocation->FirstChild()->Value(); m_locations.push_back(location); } pLocation = pLocation->NextSiblingElement("location"); } } return true; }
bool MantisBot::CheckForGoogleCodeChanges(const __ConfigProject& conf) { char tmp[HTTP_BUFFER_SIZE]; std::string buffer; ssize_t len; // Download the feed from the specified Google Code URL HTTPClient http(m_config.data.googlecode.address, m_httpGoogleCodeAddr, m_httpGoogleCodeBindAddr, false); http.Connect(conf.path); http.Send(); if (!http.Ok()) return false; if (http.ResponseStatus() != 200) { printf("Unable to connect to the web page (%s%s): %d %s\n", m_config.data.googlecode.address, conf.path, http.ResponseStatus(), http.StatusText()); return false; } // Grab the feed data HTTPStream& stream = http.GetStream(); if (!stream.Ok()) return false; while (stream.Eof() == false) { len = stream.Read(tmp, HTTP_BUFFER_SIZE); if ( len > 0 ) buffer.append(tmp, len); } // We got the feed, now start processing it's XML contents TiXmlDocument xml; TiXmlNode *feed, *node; xml.Parse(buffer.c_str()); if (xml.Error()) { printf("Unable to parse XML feed in %s: %s\n", xml.Value(), xml.ErrorDesc()); return false; } feed = xml.FirstChild("feed"); if (!feed) return false; node = feed->FirstChild("entry"); // Loop through the entry nodes size_t index; int currentId, newestId = -1; std::string strAuthor, strDescription, strLink; const char *attr; while (node) { TiXmlNode *data = node->FirstChild("title"); if (!data) return false; TiXmlElement *elem = data->ToElement (); if (!elem) return false; std::string strText = elem->GetText (); // Revision index = strText.find("Revision ") + 9; currentId = atoi(strText.substr(index, strText.find(":",index) - index).c_str()); // Description index = strText.find(":",index) + 2; strDescription = strText.substr(index); TrimSpaces(strDescription); // Author data = node->FirstChild("author"); if (!data) return false; data = data->FirstChild("name"); if (!data) return false; elem = data->ToElement (); if (!elem) return false; strAuthor = elem->GetText (); // Link data = node->FirstChild("link"); if (!data) return false; elem = data->ToElement (); if (!elem) return false; attr = elem->Attribute ("href"); if (!attr) return false; strLink = std::string ( attr ); // First entry will always be the newest if (newestId == -1) { newestId = currentId; // If this is our first run, store the newest entry id if ( m_lastGoogleCodeId.find(conf.alias) == m_lastGoogleCodeId.end() ) m_lastGoogleCodeId[conf.alias] = newestId; } // If this entry is newer than the last stored id if (currentId > m_lastGoogleCodeId[conf.alias]) { // This is a new entry SendTextToChannels( IRCText( "[%U%s%U] %C02%Br%d%B%C %C12(%s)%C %C10%s%C %C03-%C " "%C14%s%C", conf.alias, currentId, strAuthor.c_str (), strDescription.c_str (), strLink.c_str () ) ); if ( conf.autofix ) CheckForAutofixIssue ( strAuthor, strDescription, strLink ); } // Advance to next sibling node = node->NextSiblingElement (); } m_lastGoogleCodeId[conf.alias] = newestId; return true; }
void EntityFactory::LoadUnits(const char* filename) { TiXmlDocument doc; if (!doc.LoadFile(filename)) { DIE("can't open units definition %s\n%s", filename, doc.ErrorDesc()); } TiXmlHandle handle(&doc); const char* p = NULL; MediaManager& media = MediaManager::GetInstance(); TiXmlElement* elem = handle.FirstChildElement().FirstChildElement().Element(); while (elem != NULL) { // unit id int id; if (elem->QueryIntAttribute("id", &id) != TIXML_SUCCESS) { DIE("unit id is missing"); } UnitPattern* unit = &units_[id]; // name p = elem->Attribute("name"); if (p == NULL) { printf("warning: unit '%d' doesn't have 'name' attribute\n", id); p = DEFAULT_NAME; } unit->name = p; // health points int hp; if (elem->QueryIntAttribute("hp", &hp) != TIXML_SUCCESS) { printf("warning: unit '%d' doesn't have 'hp' attribute\n", id); hp = DEFAULT_HP; } unit->hp = hp; // speed int speed; if (elem->QueryIntAttribute("speed", &speed) != TIXML_SUCCESS) { printf("warning: unit '%d' doesn't have 'speed' attribute\n", id); speed = DEFAULT_SPEED; } unit->speed = speed; // animations p = elem->Attribute("animation"); if (p == NULL) { printf("warning: unit '%d' doesn't have 'animation' attribute\n", id); p = DEFAULT_ANIMATION; } unit->image = &media.GetImage(p); std::string anim_name(p); anim_name += "_walk_up"; unit->anim[Entity::UP] = &media.GetAnimation(anim_name.c_str()); anim_name = p; anim_name += "_walk_down"; unit->anim[Entity::DOWN] = &media.GetAnimation(anim_name.c_str()); anim_name = p; anim_name += "_walk_left"; unit->anim[Entity::LEFT] = &media.GetAnimation(anim_name.c_str()); anim_name = p; anim_name += "_walk_right"; unit->anim[Entity::RIGHT] = &media.GetAnimation(anim_name.c_str()); // weapon (optional) p = elem->Attribute("weapon"); // TODO: utiliser des strings pour identifier les objets, vérifier que la string est valide, ou NULL if (p != NULL) { unit->item = p; } else { unit->item.clear(); } elem = elem->NextSiblingElement(); } }
bool WorkspaceLoader::Open(const wxString& filename, wxString& Title) { TiXmlDocument doc; if (!TinyXML::LoadDocument(filename, &doc)) return false; // ProjectManager* pMan = Manager::Get()->GetProjectManager(); // LogManager* pMsg = Manager::Get()->GetLogManager(); if (!GetpMan() || !GetpMsg()) return false; // BUG: Race condition. to be fixed by Rick. // If I click close AFTER pMan and pMsg are calculated, // I get a segfault. // I modified classes projectmanager and logmanager, // so that when self==NULL, they do nothing // (constructors, destructors and static functions excempted from this) // This way, we'll use the *manager::Get() functions to check for nulls. TiXmlElement* root = doc.FirstChildElement("CodeBlocks_workspace_file"); if (!root) { // old tag root = doc.FirstChildElement("Code::Blocks_workspace_file"); if (!root) { GetpMsg()->DebugLog(_T("Not a valid Code::Blocks workspace file...")); return false; } } TiXmlElement* wksp = root->FirstChildElement("Workspace"); if (!wksp) { GetpMsg()->DebugLog(_T("No 'Workspace' element in file...")); return false; } Title = cbC2U(wksp->Attribute("title")); // Conversion to unicode is automatic (see wxString::operator= ) TiXmlElement* proj = wksp->FirstChildElement("Project"); if (!proj) { GetpMsg()->DebugLog(_T("Workspace file contains no projects...")); return false; } // first loop to load projects while (proj) { if(Manager::isappShuttingDown() || !GetpMan() || !GetpMsg()) return false; wxString projectFilename = UnixFilename(cbC2U(proj->Attribute("filename"))); if (projectFilename.IsEmpty()) { GetpMsg()->DebugLog(_T("'Project' node exists, but no filename?!?")); } else { wxFileName fname(projectFilename); wxFileName wfname(filename); fname.MakeAbsolute(wfname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR)); int active = 0; int ret = proj->QueryIntAttribute("active", &active); switch (ret) { case TIXML_SUCCESS: if (active == 1) { cbProject* pProject = GetpMan()->LoadProject(fname.GetFullPath(), true); // activate it if(!pProject) { cbMessageBox(_("Unable to open ") + projectFilename, _("Opening WorkSpace") + filename, wxICON_WARNING); } } break; case TIXML_WRONG_TYPE: GetpMsg()->DebugLog(F(_T("Error %s: %s"), doc.Value(), doc.ErrorDesc())); GetpMsg()->DebugLog(_T("Wrong attribute type (expected 'int')")); break; default: cbProject* pProject = GetpMan()->LoadProject(fname.GetFullPath(), false); // don't activate it if(!pProject) { cbMessageBox(_("Unable to open ") + projectFilename, _("Opening WorkSpace") + filename, wxICON_WARNING); } break; } } proj = proj->NextSiblingElement("Project"); } // second loop to setup dependencies proj = wksp->FirstChildElement("Project"); while (proj) { cbProject* thisprj = 0; wxString projectFilename = UnixFilename(cbC2U(proj->Attribute("filename"))); if (projectFilename.IsEmpty()) { GetpMsg()->DebugLog(_T("'Project' node exists, but no filename?!?")); thisprj = 0; } else { wxFileName fname(projectFilename); wxFileName wfname(filename); fname.MakeAbsolute(wfname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR)); thisprj = Manager::Get()->GetProjectManager()->IsOpen(fname.GetFullPath()); } if (thisprj) { TiXmlElement* dep = proj->FirstChildElement("Depends"); while (dep) { wxFileName fname(UnixFilename(cbC2U(dep->Attribute("filename")))); wxFileName wfname(filename); fname.MakeAbsolute(wfname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR)); cbProject* depprj = Manager::Get()->GetProjectManager()->IsOpen(fname.GetFullPath()); if (depprj) Manager::Get()->GetProjectManager()->AddProjectDependency(thisprj, depprj); dep = dep->NextSiblingElement("Depends"); } } proj = proj->NextSiblingElement("Project"); } return true; }