예제 #1
0
CConfiguration::CConfiguration(QWidget*       canvasWidget,
                               const QString& configFile)
   : m_CanvasWidget(canvasWidget),
     m_DisplaySizeX(0),
     m_DisplaySizeY(0)
{
   m_Nodes.setAutoDelete(true);

   QDomDocument doc("ScenarioSetup");
   QFile file(configFile);
   if(!file.open(QIODevice::ReadOnly)) {
      throw ELoadFileException();
   }

   QString errorMessage;
   int errorLine;
   if(!doc.setContent(&file , true , &errorMessage, &errorLine)) {
      file.close();
      throw EXMLSyntaxException(errorMessage, errorLine);
   }
   file.close();

   QDomNode currentNode = doc.documentElement().firstChild();
   while(!currentNode.isNull()) {
      if(QDomNode::ElementNode == currentNode.nodeType()) {
         if(currentNode.toElement().tagName() == QString(g_RefreshTimeTag)) {
            m_RefreshTime = currentNode.toElement().text().toInt();
         }
         else if(currentNode.toElement().tagName() == QString(g_ListenPortTag)) {
            m_ListenPort = currentNode.toElement().text().toInt();
         }
         else if(currentNode.toElement().tagName() == QString(g_ResolutionXTag)) {
            m_DisplaySizeX = currentNode.toElement().text().toInt();
         }
         else if(currentNode.toElement().tagName() == QString(g_ResolutionYTag)) {
            m_DisplaySizeY = currentNode.toElement().text().toInt();
         }
         else if(currentNode.toElement().tagName() == QString(g_ProtocolColorTag)) {
            QDomAttr Attribute = currentNode.toElement().attributeNode(QString(g_ProtocolColorIDTag));
            if(!Attribute.isNull()) {
               m_ColorMap[Attribute.value().toInt()] = currentNode.toElement().text();
            }
         }
         else if(currentNode.toElement().tagName() == QString(g_BackgroundImageTag)) {
            m_BackgroundImageName = currentNode.toElement().text();
         }
         else if(currentNode.toElement().tagName() == QString(g_CaptionTag)) {
            m_Caption = currentNode.toElement().text();
         }
         else if((currentNode.toElement().tagName() == QString(g_NodeTag)) ||
                 (currentNode.toElement().tagName() == QString(g_RSPNodeTag))) {
            CNode* node = createNode(currentNode.toElement());
            m_Nodes.append(node);
            m_NodesMap[node->getUniqueID()] = node;
         }
         else {
            QMessageBox::critical(0, "Error!", "Found unknown tag in config file: " +
                                  currentNode.toElement().tagName());
         }
      }
      currentNode = currentNode.nextSibling();
   }

   m_NetworkListener = new CNetworkListener(m_ListenPort, m_NodesMap);
}
void CSwordModuleInfo::buildIndex() {
	wchar_t wcharBuffer[BT_MAX_LUCENE_FIELD_LENGTH + 1];

	//we don't want the linked entries indexed again
	module()->setSkipConsecutiveLinks(true);

	m_cancelIndexing = false;

	//Without this we don't get strongs, lemmas, etc
	backend()->setFilterOptions ( CBTConfig::getFilterOptionDefaults() );
	//make sure we reset all important filter options which influcence the plain filters.
	backend()->setOption( CSwordModuleInfo::strongNumbers,  false );
	backend()->setOption( CSwordModuleInfo::morphTags,  false );
	backend()->setOption( CSwordModuleInfo::morphSegmentation,  false );
	backend()->setOption( CSwordModuleInfo::footnotes,  false );
	backend()->setOption( CSwordModuleInfo::headings,  false );
	backend()->setOption( CSwordModuleInfo::scriptureReferences,  false );
	backend()->setOption( CSwordModuleInfo::redLetterWords,  false );

	// do not use any stop words
	const TCHAR* stop_words[]  = { NULL };
	lucene::analysis::standard::StandardAnalyzer an( (const TCHAR**)stop_words );
	QString index = getModuleStandardIndexLocation();

	QDir dir("/");
	dir.mkpath( getGlobalBaseIndexLocation() );
	dir.mkpath( getModuleBaseIndexLocation() );
	dir.mkpath( getModuleStandardIndexLocation() );

	if (lucene::index::IndexReader::indexExists(index.toAscii().constData())) {
		if (lucene::index::IndexReader::isLocked(index.toAscii().constData()) ) {
			lucene::index::IndexReader::unlock(index.toAscii().constData());
		}
	}

	boost::scoped_ptr<lucene::index::IndexWriter> writer( new lucene::index::IndexWriter(index.toAscii().constData(), &an, true) ); //always create a new index
	writer->setMaxFieldLength(BT_MAX_LUCENE_FIELD_LENGTH);
	writer->setUseCompoundFile(true); //merge segments into a single file
	writer->setMinMergeDocs(1000);

	*m_module = sword::TOP;
	unsigned long verseLowIndex = m_module->Index();
	*m_module = sword::BOTTOM;
	unsigned long verseHighIndex = m_module->Index();

	//verseLowIndex is not 0 in all cases (i.e. NT-only modules)
	unsigned long verseIndex = verseLowIndex + 1;
	unsigned long verseSpan = verseHighIndex - verseLowIndex;

	//Index() is not implemented properly for lexicons, so we use a
	//workaround.
	if (type() == CSwordModuleInfo::Lexicon){
		verseIndex = 0;
		verseLowIndex = 0;
		verseSpan = ((CSwordLexiconModuleInfo*)this)->entries()->size();
	}

	emit indexingProgress(0);

	sword::SWKey* key = m_module->getKey();
	//VerseKey for bibles
	sword::VerseKey* vk = dynamic_cast<sword::VerseKey*>(key);

	if (vk) {
		// we have to be sure to insert the english key into the index, otherwise we'd be in trouble if the language changes
		vk->setLocale("en_US");
		//If we have a verse based module, we want to include the pre-chapter etc. headings in the search
		vk->Headings(1);
	}

	//holds UTF-8 data and is faster than QString.
	QByteArray textBuffer;

	// we start with the first module entry, key is automatically updated
	// because key is a pointer to the modules key
	m_module->setSkipConsecutiveLinks(true);
	for (*m_module = sword::TOP; !(m_module->Error()) && !m_cancelIndexing; (*m_module)++) {

		//If it is a sword-heading, store in buffer and index later in Verse X:1
		if (vk) {
			if (vk->Verse() == 0) {
				textBuffer.append( m_module->StripText() );
				continue;
			}
		}

		boost::scoped_ptr<lucene::document::Document> doc(new lucene::document::Document());

		//index the key
		lucene_utf8towcs(wcharBuffer, key->getText(), BT_MAX_LUCENE_FIELD_LENGTH);
		//doc->add(*lucene::document::Field::UnIndexed((const TCHAR*)_T("key"), (const TCHAR*)wcharBuffer));
		doc->add(*(new lucene::document::Field((const TCHAR*)_T("key"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_YES | lucene::document::Field::INDEX_NO)));
		// index the main text
		//at this point we have to make sure we disabled the strongs and the other options
		//so the plain filters won't include the numbers somehow.
		lucene_utf8towcs(wcharBuffer, (const char*) textBuffer.append(m_module->StripText()), BT_MAX_LUCENE_FIELD_LENGTH);
		//doc->add(*lucene::document::Field::UnStored((const TCHAR*)_T("content"), (const TCHAR*)wcharBuffer));
		doc->add(*(new lucene::document::Field((const TCHAR*)_T("content"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
		textBuffer.resize(0); //clean up

		// index attributes
		sword::AttributeList::iterator attListI;
		sword::AttributeValue::iterator attValueI;
		// Footnotes
		for (attListI = m_module->getEntryAttributes()["Footnote"].begin();
				attListI != m_module->getEntryAttributes()["Footnote"].end();
				attListI++) {
			lucene_utf8towcs(wcharBuffer, attListI->second["body"], BT_MAX_LUCENE_FIELD_LENGTH);
			//doc->add(*lucene::document::Field::UnStored((const TCHAR*)_T("footnote"), wcharBuffer));
			doc->add(*(new lucene::document::Field((const TCHAR*)_T("footnote"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
		} // for attListI

		// Headings
		for (attValueI = m_module->getEntryAttributes()["Heading"]["Preverse"].begin();
				attValueI != m_module->getEntryAttributes()["Heading"]["Preverse"].end();
				attValueI++) {
			lucene_utf8towcs(wcharBuffer, attValueI->second, BT_MAX_LUCENE_FIELD_LENGTH);
			//doc->add(*lucene::document::Field::UnStored((const TCHAR*)_T("heading"), wcharBuffer));
			doc->add(*(new lucene::document::Field((const TCHAR*)_T("heading"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
		} // for attValueI

		// Strongs/Morphs
		for (attListI = m_module->getEntryAttributes()["Word"].begin();
				attListI != m_module->getEntryAttributes()["Word"].end();
				attListI++) {
			// for each attribute
			if (attListI->second["LemmaClass"] == "strong") {
				lucene_utf8towcs(wcharBuffer, attListI->second["Lemma"], BT_MAX_LUCENE_FIELD_LENGTH);
				//doc->add(*lucene::document::Field::UnStored((const TCHAR*)_T("strong"), wcharBuffer));
				doc->add(*(new lucene::document::Field((const TCHAR*)_T("strong"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
				//qWarning("Adding strong %s", attListI->second["Lemma"].c_str());
			}
			if (attListI->second.find("Morph") != attListI->second.end()) {
				lucene_utf8towcs(wcharBuffer, attListI->second["Morph"], BT_MAX_LUCENE_FIELD_LENGTH);
				//doc->add(*lucene::document::Field::UnStored((const TCHAR*)_T("morph"), wcharBuffer));
				doc->add(*(new lucene::document::Field((const TCHAR*)_T("morph"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
			}
		} // for attListI

		writer->addDocument(doc.get());
		//Index() is not implemented properly for lexicons, so we use a
		//workaround.
		if (type() == CSwordModuleInfo::Lexicon){
			verseIndex++;
		}
		else{
			verseIndex = m_module->Index();
		}

		if (verseIndex % 200 == 0) {
			int indexingProgressValue;
			if (verseSpan == 0) { //prevent division by zero
				//m_indexingProgress.setValue( QVariant(0) );
				indexingProgressValue = 0;
			} else {
				//m_indexingProgress.setValue( QVariant((int)((100*(verseIndex-verseLowIndex))/(verseHighIndex-verseLowIndex))) );
				indexingProgressValue = (int)((100*(verseIndex-verseLowIndex)) / (verseSpan));
			}
			//m_indexingProgress.activate();
			emit indexingProgress(indexingProgressValue);
		}
	}

	if (!m_cancelIndexing)
	{
		writer->optimize();
	}
	writer->close();

	if (m_cancelIndexing){
		deleteIndexForModule(name());
		m_cancelIndexing = false;
	}
	else
	{
		QSettings module_config(getModuleBaseIndexLocation() + QString("/bibletime-index.conf"), QSettings::IniFormat);
		if (hasVersion()) module_config.setValue("module-version", config(CSwordModuleInfo::ModuleVersion) );
		module_config.setValue("index-version", INDEX_VERSION );
	}
}
예제 #3
0
void EmoteDB::load()
{
    if (mLoaded)
        return;

    mLastEmote = 0;

    EmoteSprite *unknownSprite = new EmoteSprite;
    unknownSprite->sprite = AnimatedSprite::load("error.xml");
    unknownSprite->name = "unknown";
    mUnknown.sprites.push_back(unknownSprite);

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

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

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

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

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

        EmoteInfo *currentInfo = new EmoteInfo;

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

    mLoaded = true;
}
예제 #4
0
파일: rotation.C 프로젝트: nmoran/DoQO
/*! \brief This function reads the input file containing the details of the transformation being used.*/
int read_rotation_information(struct parameter_struct *parameters){
	string filename(parameters->rotation_info_file);
	PetscErrorCode ierr;
	
	//open rotation file as xml document.
	TiXmlDocument doc(filename);
	bool loadOkay = doc.LoadFile();
	if ( !loadOkay ) 
	{
		PetscPrintf(PETSC_COMM_WORLD,"Could not load rotation info file '%s'. Error='%s'. Exiting.\n", parameters->rotation_info_file, doc.ErrorDesc() );
		return 1;
	}
	TiXmlHandle docHandle(&doc);
	
	//find ROTATION_OP tag.
	
	parameters->number_rotation_sectors = 1;
	
	TiXmlElement* parent_element = docHandle.FirstChild("ROTATION_OPS").Element(); 	
	if ( parent_element) 
	  {
	    if (parent_element->Attribute("number") == NULL ) 
	      { 
		PetscPrintf(PETSC_COMM_WORLD,"You must specify the number of rotation operators.\n");
		return 1;
	      }
	    parameters->number_rotation_ops = atoi(parent_element->Attribute("number"));
	    
	    ierr = PetscMalloc(parameters->number_rotation_ops *sizeof(struct rotation_information), &parameters->rotation_info); CHKERRQ(ierr);
	    
	    for ( int rot_idx = 0 ; rot_idx < parameters->number_rotation_ops ; rot_idx ++ ) 
	      {
			TiXmlElement* element = docHandle.FirstChild("ROTATION_OPS").Child("ROTATION_OP", rot_idx).Element(); //tags surrounding the mapping. Has attribute "number" which contains the 
														  //number of times the rotation op can be applied before getting back to the start.
			TiXmlElement* element2;
			if ( element) 
			{	
				if (element->Attribute("number") == NULL ) { 
					PetscPrintf(PETSC_COMM_WORLD,"You must specify a number attribute to the rotation operation.\n");
					return 1;
				}

				parameters->rotation_info[rot_idx].num_sectors = atoi(element->Attribute("number"));
				parameters->rotation_info[rot_idx].num_relevant_sectors = parameters->rotation_info[rot_idx].num_sectors;
				parameters->number_rotation_sectors *= parameters->rotation_info[rot_idx].num_sectors;
				
				ierr = PetscMalloc( parameters->rotation_info[rot_idx].num_sectors * sizeof(PetscScalar),&parameters->rotation_info[rot_idx].phases);CHKERRQ(ierr);
				
				//allocate space for the mapping masks.
				ierr = PetscMalloc( parameters->rotation_info[rot_idx].num_sectors * sizeof(uPetscInt*),&parameters->rotation_info[rot_idx].mapping_masks);CHKERRQ(ierr);
				for ( int i = 0 ; i < parameters->rotation_info[rot_idx].num_sectors ; i++ ) {
					ierr = PetscMalloc(parameters->number_particles * sizeof(uPetscInt), &parameters->rotation_info[rot_idx].mapping_masks[i]);CHKERRQ(ierr);
				}
				
				//applying 0 rotations will give the same stage so add masks that do not move any particles.
				for ( int i = 0 ; i < parameters->number_particles ; i++ ) {
					parameters->rotation_info[rot_idx].mapping_masks[0][i] = ((uPetscInt)1) << i;
				}
				
				//read in the mappings to position 1 which is a single rotation with the op.
				for ( int i = 0 ; i < parameters->number_particles ; i++ ) {
					element2 = docHandle.FirstChild("ROTATION_OPS").Child("ROTATION_OP", rot_idx).Child("MAPPING",i).Element();
					if ( element2 ) {
						parameters->rotation_info[rot_idx].mapping_masks[1][atoi(element2->Attribute("to"))-1] = ((uPetscInt)1) << (atoi(element2->Attribute("from"))-1);
					} else {
						PetscPrintf(PETSC_COMM_WORLD,"Mapping %d does not exist.\n",i);
						return 1;
					}
				}
				
				//Now iterate this rotation to fill in the masks for the other possible mutiples of the rotation.
				for ( int i = 2 ; i < parameters->rotation_info[rot_idx].num_sectors ; i++ ) {
					for ( int j = 0 ; j < parameters->number_particles ; j++ ) {
						parameters->rotation_info[rot_idx].mapping_masks[i][j] = parameters->rotation_info[rot_idx].mapping_masks[1][log2_uPetscInt(parameters->rotation_info[rot_idx].mapping_masks[i-1][j])];
					}
				}
												
				//print out the mapping for each number of rotations that can be applied. For debugging purposes. 
				/*for (int i = 0 ; i < parameters->rotation_info.num_sectors ; i++ ) {
					PetscPrintf(PETSC_COMM_WORLD,"Applying %d rotations:\n",i);
					for ( int j = 0 ; j < parameters->number_particles ; j++ ) {
						PetscPrintf(PETSC_COMM_WORLD,"Site %d moved to site %d.\n",j,(int)log2_uPetscInt(parameters->rotation_info.mapping_masks[i][j]));
					}
				}*/
				
				parameters->rotation_info[rot_idx].sector_modulo = 1;
				parameters->rotation_info[rot_idx].sector_divisor = 1;
				for ( int j = 0 ; j <= rot_idx ; j++ )
				{
					parameters->rotation_info[rot_idx].sector_modulo *= parameters->rotation_info[j].num_sectors;
					if ( j <  rot_idx) parameters->rotation_info[rot_idx].sector_divisor *= parameters->rotation_info[j].num_sectors;
				}
				
				
			} else {
				PetscPrintf(PETSC_COMM_WORLD,"No ROTATION_OP %d tag in rotation info file.\n",rot_idx);
				return 1;
			}
	      }
	  } 
	else 
	  {
	    PetscPrintf(PETSC_COMM_WORLD,"No ROTATION_OPS tag in rotation info file.\n");
	    return 1;
	  }
	return 0;
}
예제 #5
0
 Data next() {
     Document doc(_cursor->next());
     return make_pair(_sorter->extractKey(doc), doc);
 }
예제 #6
0
int		load_db_init(t_db_info *db_info, t_cfg *cfg)
{
  std::string	gamepath(std::string(cfg->GamePath) + std::string(cfg->Game));
  TiXmlDocument doc(gamepath.c_str());
  const char	*buf;
  int		int_buf;
  int		i;
  char		err_msg[BUF_SIZE];
  
  if (doc.LoadFile() == false)
    {
      char	*err = "Failed to load game database file: ";
      strcpy(err_msg, err);
      strcat(err_msg, gamepath.c_str());
      //send_error_trap(err_msg, 1);
      return (put_error(err_msg));
    }
  puts("\n<load_db_init>");
  TiXmlElement* elm_root = doc.FirstChildElement("root");
  if (elm_root)
    {
      TiXmlElement* elm_head = elm_root->FirstChildElement("head");
      if (elm_head)
	{
	  TiXmlElement* elm_version = elm_head->FirstChildElement("version");
	  if (elm_version)
	    {
	      if ((buf = elm_version->Attribute("db_name")) == NULL)
		return(put_error("DB is imcomplete: db_name"));
	      strcpy(db_info->game, (char*)buf);
	      printf("Game: [%s]\n", db_info->game);
	      
	      if ((buf = elm_version->Attribute("db_verion")) == NULL)
		return(put_error("DB is imcomplete: db_verion"));
	      strcpy(db_info->version, (char*)buf);
	      printf("version: [%s]\n", db_info->version);
	    }
	  else
	    return(put_error("DB as not members name <version> in <head>"));
	}
      else
	return(put_error("DB as not members name <head> in <root>"));

      TiXmlElement* elm_races = elm_root->FirstChildElement("races");
      if (elm_races)
	{
	  TiXmlElement* elm_race = elm_races->FirstChildElement("race");
	  if (elm_race)
	    {
	      if ((buf = elm_race->Attribute("name")) == NULL)
		return(put_error("DB is imcomplete: race name"));
	      strcpy(db_info->races[0], (char*)buf);
	      printf("race[0]: [%s]\n", db_info->races[0]);
	    }
	  else
	    return(put_error("DB as not members name <race> in <races>"));
	  for (i = 1; elm_race = elm_race->NextSiblingElement("race"); i++)
	    {
	      if ((buf = elm_race->Attribute("name")) == NULL)
		return(put_error("DB is imcomplete: race name"));
	      strcpy(db_info->races[i], (char*)buf);
	      printf("race[%i]: [%s]\n", i, db_info->races[i]);
	    }
	  db_info->races[i][0] = 0;
	}	  
      else
	return(put_error("DB as not members name <races> in <head>"));

      TiXmlElement* elm_maps = elm_root->FirstChildElement("maps");
      if (elm_maps)
	{
	   TiXmlElement* elm_map = elm_maps->FirstChildElement("map");
	  if (elm_map)
	    {
	      if ((buf = elm_map->Attribute("name")) == NULL)
		return(put_error("DB is imcomplete: map name"));
	      strcpy(db_info->map_def[0].name, (char*)buf);
	      printf("map[0]: [%s]", db_info->map_def[0].name);

	      if ((elm_map->QueryIntAttribute((const char*)"max_players", &int_buf))
		  != TIXML_SUCCESS)
		return(put_error("DB is imcomplete: map max_players"));
	      db_info->map_def[0].max_players = int_buf;
	      printf(" max_players: [%i]\n", db_info->map_def[0].max_players);
	      
	    }
	  else
	    return(put_error("DB as not members name <map> in <maps>"));
	  for (i = 1; elm_map = elm_map->NextSiblingElement("map"); i++)
	    {
	      if ((buf = elm_map->Attribute("name")) == NULL)
		return(put_error("DB is imcomplete: map name"));
	      strcpy(db_info->map_def[i].name, (char*)buf);
	      printf("map[%i]: [%s]", i, db_info->map_def[i].name);
	   
	      if ((elm_map->QueryIntAttribute((const char*)"max_players", &int_buf))
		  != TIXML_SUCCESS)
		return(put_error("DB is imcomplete: map max_players"));
	      db_info->map_def[i].max_players = int_buf;
	      printf(" max_players: [%i]\n", db_info->map_def[i].max_players);
	    }
	  db_info->map_def[i].name[0] = 0;
	  db_info->map_def[i].max_players = 0;
	}
      else
	return(put_error("DB as not members name <maps> in <root>"));
    }
  else
    return(put_error("DB as not members name <root>"));
  puts("</load_db_init>\n");
  return (0);
}
예제 #7
0
	RenderContext* RenderContext::LoadXML(const char* xmlFileNamePtr, const char* indentifier)
	{
		TiXmlDocument doc((ContentManager::theContentPath + xmlFileNamePtr).c_str());

		if(!doc.LoadFile())
		{
			InternalOutput::GetReference().Error(
				"Failed to load %s, does the file exist?\n", xmlFileNamePtr);
			return 0;
		}

		TiXmlHandle hDoc(&doc);
		TiXmlElement* elementPtr;
		TiXmlHandle hRoot(0);

		elementPtr = hDoc.FirstChildElement().Element();
		if( !elementPtr )
		{
			InternalOutput::GetReference().Error(
				"Failed to load %s, is the file empty?\n", xmlFileNamePtr);
			return 0;
		}

		std::string rootName = elementPtr->Value();

		if( strcmp(rootName.c_str(), "GDRenderContext") != 0 )
		{
			InternalOutput::GetReference().Error(
				"Failed to load %s, missing a GDRenderContext element\n", 
				xmlFileNamePtr);
			return 0;
		}

		TiXmlElement* pMaterialElement = elementPtr->FirstChildElement("Material");

		std::string materialString;
		std::string shaderEffectString;
		std::string techniqueString;
		std::string vertexFormatString;
		std::string castShadowString;
		std::string renderStyleString;

		if( pMaterialElement != 0 )
		{
			if(pMaterialElement->GetText() != 0)
				materialString = pMaterialElement->GetText();
		}

		// Error check for old Effect based shader usage
		TiXmlElement* pEffectElement = elementPtr->FirstChildElement("Effect");
		if(nullptr == pEffectElement )
		{
			InternalOutput::GetReference().Error(
				"Failed to load %s, missing Effect element", xmlFileNamePtr);
			return 0;
		}
		shaderEffectString = pEffectElement->GetText();

		TiXmlElement* pTechniqueElement = elementPtr->FirstChildElement("Technique");

		if( pTechniqueElement != 0 )
		{
			if( pTechniqueElement->GetText() != 0 )
				techniqueString = pTechniqueElement->GetText();
		}

		if( techniqueString.length() == 0 )
			techniqueString = "Basic";

		TiXmlElement* pVertexFormatElement = elementPtr->FirstChildElement("VertexFormat");

		if( pVertexFormatElement == 0 )
		{
			InternalOutput::GetReference().Error(
				"Failed to load %s, missing a VertexFormat element\n", xmlFileNamePtr);
			return 0;
		}

		vertexFormatString = pVertexFormatElement->GetText();

		bool isDeferredPointLightContext = false;
		TiXmlElement* pPointLightTechnique = elementPtr->FirstChildElement("PointLightTechnique");
		if( pPointLightTechnique != 0 )
		{
			if( pPointLightTechnique->GetText() != 0 )
			{
				std::string technique = pPointLightTechnique->GetText();
				if( technique.length() != 0 )
					isDeferredPointLightContext = true;
			}

		}	
		bool isDeferredDirLightContext = false;
		TiXmlElement* pDirLightTechnique = elementPtr->FirstChildElement("DirLightTechnique");
		if( pDirLightTechnique != 0 )
		{
			if( pDirLightTechnique->GetText() != 0 )
			{
				std::string technique = pDirLightTechnique->GetText();
				if( technique.length() != 0 )
					isDeferredDirLightContext = true;
			}
		}
		bool isDeferredSpotLightContext = false;
		TiXmlElement* pSpotLightTechnique = elementPtr->FirstChildElement("SpotLightTechnique");
		if( pSpotLightTechnique != 0 )
		{
			if( pSpotLightTechnique->GetText() != 0 )
			{
				std::string technique = pSpotLightTechnique->GetText();
				if( technique.length() != 0 )
					isDeferredSpotLightContext = true;
			}
		}

		bool castShadows = false;
		TiXmlElement* pCastShadowsEle = elementPtr->FirstChildElement("CastShadows");
		if( pCastShadowsEle != 0 )
		{
			castShadows = true;

			if( pCastShadowsEle->GetText() != 0 )
			{
				if( strlen( pCastShadowsEle->GetText() ) != 0 &&
					(_stricmp( pCastShadowsEle->GetText(), "false") == 0 ||
					strcmp( pCastShadowsEle->GetText(), "0" ) == 0 ) )
				{
					castShadows = false;
				}
			}
		}

		TiXmlElement* pRenderStyleElement = elementPtr->FirstChildElement("RenderStyle");

		renderStyleString = pRenderStyleElement->GetText();

		RenderContext* pRenderContext = 0;

		if( materialString.length() != 0 )
		{
			RenderContextWithTexture* pRcWithTex = new RenderContextWithTexture;
			pRenderContext = pRcWithTex;

			if( strcmp( vertexFormatString.c_str(), "VERTEX_POS" ) == 0 )
			{
				pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPositionRenderFunc;
				pRcWithTex->vertexFormat = eVERTEX_POS;
			}
			else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSCOLOR" ) == 0 )
			{
				pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPositionRenderFunc;
				pRcWithTex->vertexFormat = eVERTEX_POSCOLOR;
			}
			else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSTEX" ) == 0 )
			{
				pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPositionUVRenderFunc;
				pRcWithTex->vertexFormat = eVERTEX_POSTEX;
			}
			else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTEX" ) == 0 )
			{
				pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPosNormalUVRenderFunc;
				pRcWithTex->vertexFormat = eVERTEX_POSNORMTEX;
			}
			else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTANTEX" ) == 0 )
			{
				pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPosNormalTangentUVRenderFunc;
				pRcWithTex->vertexFormat = eVERTEX_POSNORMTANTEX;
			}
			else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSBONEWEIGHTNORMTEX" ) == 0 )
			{
				pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPosBoneWeightNormalUVRenderFunc;
				pRcWithTex->vertexFormat = eVERTEX_POSBONEWEIGHTNORMTEX;
			}
			else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSBONEWEIGHTNORMTANTEX" ) == 0 )
			{
				pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPosBoneWeightNormalTanUVRenderFunc;
				pRcWithTex->vertexFormat = eVERTEX_POSBONEWEIGHTNORMTANTEX;
			}
		}
		else
		{
			pRenderContext = new RenderContext;

			if( "TRANSPARENT" == renderStyleString )
			{
				if( strcmp( vertexFormatString.c_str(), "VERTEX_POS" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextTransparentPositionRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POS;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSCOLOR" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextTransparentPositionColorRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSCOLOR;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSTEX" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextTransparentPositionUVRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSTEX;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTEX" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextTransparentPosNormalUVRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSNORMTEX;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTANTEX" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextTransparentPosNormalTangentUVRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSNORMTANTEX;
				}
			}
			else
			{
				if( strcmp( vertexFormatString.c_str(), "VERTEX_POS" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextPositionRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POS;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSCOLOR" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextPositionColorRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSCOLOR;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSTEX" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextPositionUVRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSTEX;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTEX" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextPosNormalUVRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSNORMTEX;
				}
				else if (strcmp(vertexFormatString.c_str(), "VERTEX_POSNORMTEXNOCULL") == 0)
				{
					pRenderContext->RenderFunc = ContextPosNormalUVNoCullRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSNORMTEX;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTANTEX" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextPosNormalTangentUVRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSNORMTANTEX;
				}
				else if (strcmp(vertexFormatString.c_str(), "VERTEX_POSNORMTANTEXNOCULL") == 0)
				{
					pRenderContext->RenderFunc = ContextPosNormalTangentUVNoCullRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSNORMTANTEX;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSBONEWEIGHTNORMTEX" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextPosBoneWeightNormalUVRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSBONEWEIGHTNORMTEX;
				}
				else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSBONEWEIGHTNORMTANTEX" ) == 0 )
				{
					pRenderContext->RenderFunc = ContextPosBoneWeightNormalTanUVRenderFunc;
					pRenderContext->vertexFormat = eVERTEX_POSBONEWEIGHTNORMTANTEX;
				}
			}
		}

		if( materialString.length() != 0 )
		{
			//std::string materialFilePath = "Resources/GDAssets";
			//materialFilePath += materialString;

			//ContentHandle<RenderMaterial> matHandle = ContentManager::LoadXML<RenderMaterial>(materialFilePath.c_str());
		}

		pRenderContext->castShadows = castShadows;

		// Set up shaders
		if(!pRenderContext->CreateEffect((string("ShaderEffects/") + shaderEffectString).c_str()))
		{
			InternalOutput::GetReference().Error(
				"Failed to load %s, shader effect, %s, failed to load\n", xmlFileNamePtr, 
				shaderEffectString.c_str());
		}

		ShaderTechnique *techPtr = nullptr;

		pRenderContext->SetRenderStageTechnique(elementPtr, "GBufferTechnique", xmlFileNamePtr, 
			RenderContext::RS_GBUFFER);

		pRenderContext->SetRenderStageTechnique(elementPtr, "DepthCameraTechnique", xmlFileNamePtr, 
			RenderContext::RS_DEPTH_CAMERA);

		pRenderContext->SetRenderStageTechnique(elementPtr, "DepthSpotLightTechnique", xmlFileNamePtr, 
			RenderContext::RS_DEPTH_SPT_LIGHT);

		TiXmlElement* pDepthPointLightTechnique = elementPtr->FirstChildElement("DepthPointLightTechnique");
		if( pDepthPointLightTechnique != 0 )
		{
			if( pDepthPointLightTechnique->GetText() != 0 )
			{
				std::string technique = pDepthPointLightTechnique->GetText();
				if( technique.length() != 0 )
				{
					ShaderTechnique *techPtr = pRenderContext->effectPtr.GetContent()->GetTechniqueByName(
						technique.c_str());
					if(!techPtr)
					{
						InternalOutput::GetReference().Error(
							"Context %s specifies %s, but the technique does not exist in the shader\n", 
							xmlFileNamePtr, "DepthPointLightTechnique");

					}
					pRenderContext->SetRenderStageTechnique( 
						RenderStage(RenderContext::RS_DEPTH_PNT_LIGHT), techPtr);
				}
			}
		}

		pRenderContext->SetRenderStageTechnique(elementPtr, "DepthDirectionalLightTechnique", xmlFileNamePtr, 
			RenderContext::RS_DEPTH_DIR_LIGHT);

		pRenderContext->SetRenderStageTechnique(elementPtr, "UnlitTechnique", xmlFileNamePtr, 
			RenderContext::RS_UNLIT);

		pRenderContext->SetRenderStageTechnique(elementPtr, "TransparencyTechnique", xmlFileNamePtr, 
			RenderContext::RS_TRANSPARENT);

		pRenderContext->SetRenderStageTechnique(elementPtr, "GUITechnique", xmlFileNamePtr, 
			RenderContext::RS_GUI);

		if( isDeferredPointLightContext )
		{
			std::string technique = pPointLightTechnique->GetText();
			if( technique.length() != 0 )
				pRenderContext->SetRenderStageTechnique( RenderContext::RS_PNT_LIGHT, 
					pRenderContext->effectPtr.GetContent()->GetTechniqueByName(technique.c_str() ));
		}

		if( isDeferredDirLightContext )
		{
			std::string technique = pDirLightTechnique->GetText();
			if( technique.length() != 0 )
				pRenderContext->SetRenderStageTechnique( RenderContext::RS_DIR_LIGHT, 
					pRenderContext->effectPtr.GetContent()->GetTechniqueByName(technique.c_str() ));
		}

		if( isDeferredSpotLightContext )
		{
			std::string technique = pSpotLightTechnique->GetText();
			if( technique.length() != 0 )
				pRenderContext->SetRenderStageTechnique( RenderContext::RS_SPT_LIGHT, 
					pRenderContext->effectPtr.GetContent()->GetTechniqueByName(technique.c_str() ));
		}

		////////////////////////////////////////////////////////////////////////////////////
		// Layout verification
		//LayoutVerification((string("ShaderEffects/") + shaderEffectString).c_str(), vertexFormatString);
		
		// End layout verification

		if( pRenderContext->GetRenderStageTechnique( RenderContext::RS_TRANSPARENT ) != 0 )
			pRenderContext->CreateRenderSet( true, RenderSetSorted::ZSortSmaller );
		else
			pRenderContext->CreateRenderSet();

		return pRenderContext;
	}
예제 #8
0
void XMLPreferences::loadPreferences(const QString& filename, 
				     PrefSectionDict& dict)
{
  QDomDocument doc(seqPrefName);
  QFile f(filename);
  if (!f.open(IO_ReadOnly))
  {
    qWarning("Unable to open file: %s!", 
	     (const char*)filename);
    return;
  }

  QString errorMsg;
  int errorLine = 0;
  int errorColumn = 0;
  if (!doc.setContent(&f, false, &errorMsg, &errorLine, &errorColumn))
  {
    qWarning("Error processing file: %s!\n\t %s on line %d in column %d!", 
	     (const char*)filename, 
	     (const char*)errorMsg, errorLine, errorColumn);
    f.close();
    return;
  }

  // do more processing here
 QDomElement docElem = doc.documentElement();
 DomConvenience conv(doc);
 QDomNodeList sectionList, propertyList;
 PreferenceDict* sectionDict;
 CommentDict* commentSectionDict;
 QString comment;
 QString* commentVal;
 QDomElement section;
 QDomElement property;
 QString sectionName;
 QString propertyName;
 QDomNode n;
 QDomElement valueElement;
 bool foundValue;

 sectionList = doc.elementsByTagName("section");
 for (uint i = 0; i < sectionList.length(); i++)
 {
   section = sectionList.item(i).toElement();
   if (!section.hasAttribute("name"))
   {
     qWarning("section without name!");
     continue;
   }

   sectionName = section.attribute("name");

   // see if the section exists in the dictionary
   sectionDict = dict.find(sectionName);

   // if not, then create it
   if (sectionDict == NULL)
   {
     // create the new preference dictionary
     sectionDict = new PreferenceDict(preferenceHashSize);

     // make sure the dictionary deletes removed properties
     sectionDict->setAutoDelete(true);

     // insert the preference dictionary into the section
     dict.insert(sectionName, sectionDict);
   }

   // see if comment section exists in the dictionary
   commentSectionDict = m_commentSections.find(sectionName);

   // if not, then create it
   if (commentSectionDict == NULL)
   {
     // create the new preference dictionary
     commentSectionDict = new CommentDict(preferenceHashSize);

     // make sure the dictionary deletes removed properties
     commentSectionDict->setAutoDelete(true);

     // insert the preference dictionary into the section
     m_commentSections.insert(sectionName, commentSectionDict);
   }

   propertyList = section.elementsByTagName("property");
   
   for (uint j = 0; j < propertyList.length(); j++)
   {
     property = propertyList.item(j).toElement();
     if (!property.hasAttribute("name"))
     {
       qWarning("property in section '%s' without name! Ignoring!",
		(const char*)sectionName);
       continue;
     }

     propertyName = property.attribute("name");

     foundValue = false;

     QVariant value;
     // iterate over the nodes under the property
     for (n = property.firstChild(); !n.isNull(); n = n.nextSibling())
     {
       if (!n.isElement())
	 continue;

       valueElement = n.toElement();

       if (valueElement.tagName() == "comment")
       {
	 // get comment if any
	 comment = valueElement.text();

	 // if there is a comment, cache it
         if (!comment.isEmpty())
         {
	   commentVal = commentSectionDict->find(propertyName);
	   
	   if (commentVal != NULL)
	     *commentVal = comment;
	   else
	     commentSectionDict->insert(propertyName, 
					new QString(comment));
	 }

	 continue;
       }

       if (!conv.elementToVariant(valueElement, value))
       {
	 qWarning("property '%s' in section '%s' with bogus value in tag '%s'!"
		  " Ignoring!",
		  (const char*)propertyName, (const char*)sectionName,
		  (const char*)valueElement.tagName());
	 
	 continue;
       }

       // found the value
       foundValue = true;
       
       // insert value into the section dictionary
       sectionDict->insert(propertyName, new QVariant(value));
       
       break;
     }

#if 0 // ZBTEMP : Support properties without values to get comments?
     if (!foundValue)
     {
       qWarning("property '%s' in section '%s' without value! Ignoring!",
		(const char*)propertyName, (const char*)sectionName);
       continue;
     }
#endif
   }
 }

  // close the file
  f.close();

#if 1 // ZBTEMP
  printf("Loaded preferences file: %s!\n", (const char*)filename);
#endif
}
예제 #9
0
static bool loadDetailsFromXML(const QString &filename, FileDetails *details)
{
    QDomDocument doc("mydocument");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return false;

    if (!doc.setContent(&file))
    {
        file.close();
        return false;
    }
    file.close();

    QString docType = doc.doctype().name();

    if (docType == "MYTHARCHIVEITEM")
    {
        QDomNodeList itemNodeList = doc.elementsByTagName("item");
        QString type, dbVersion;

        if (itemNodeList.count() < 1)
        {
            LOG(VB_GENERAL, LOG_ERR,
                "Couldn't find an 'item' element in XML file");
            return false;
        }

        QDomNode n = itemNodeList.item(0);
        QDomElement e = n.toElement();
        type = e.attribute("type");
        dbVersion = e.attribute("databaseversion");
        if (type == "recording")
        {
            QDomNodeList nodeList = e.elementsByTagName("recorded");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'recorded' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                        details->title = e.text();

                    if (e.tagName() == "subtitle")
                        details->subtitle = e.text();

                    if (e.tagName() == "starttime")
                        details->startTime = MythDate::fromString(e.text());

                    if (e.tagName() == "description")
                        details->description = e.text();
                }
                n = n.nextSibling();
            }

            // get channel info
            n = itemNodeList.item(0);
            e = n.toElement();
            nodeList = e.elementsByTagName("channel");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'channel' element in XML file");
                details->chanID = "";
                details->chanNo = "";
                details->chanName = "";
                details->callsign =  "";
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            details->chanID = e.attribute("chanid");
            details->chanNo = e.attribute("channum");
            details->chanName = e.attribute("name");
            details->callsign =  e.attribute("callsign");
            return true;
        }
        else if (type == "video")
        {
            QDomNodeList nodeList = e.elementsByTagName("videometadata");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'videometadata' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                    {
                        details->title = e.text();
                        details->subtitle = "";
                        details->startTime = QDateTime();
                    }

                    if (e.tagName() == "plot")
                    {
                        details->description = e.text();
                    }
                }
                n = n.nextSibling();
            }

            details->chanID = "N/A";
            details->chanNo = "N/A";
            details->chanName = "N/A";
            details->callsign = "N/A";

            return true;
        }
    }

    return false;
}
예제 #10
0
void AProProject::parseFile()
{
    if(fileName.isEmpty())
    {
        QMessageBox::warning(0,"Erreur","Le projet spécifié n'existe pas !");
        return;
    }
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(0,"Erreur","Le projet spécifié n'existe pas !");
        return;
    }
    QDomDocument doc("projet");
    if (!doc.setContent(&file))
        return;

    file.close();

    QDomElement root = doc.documentElement();
    if (root.tagName()!="aproject")
        return;

    version = root.attribute("version","");
    if (version != APROJECT_CURRENT_VERSION)
        return;

    QDomNode n = root.firstChild();
    while(!n.isNull())
    {
        QDomElement e = n.toElement();
        if (!e.isNull())
        {
            if (e.tagName()=="config")
            {
                name = e.attribute("name","");
            }
            else if (e.tagName()=="files")
            {
                if (e.attribute("type","") == "src")
                {
                    QDomNode n2 = e.firstChild();
                    while (!n2.isNull())
                    {
                        QDomElement e2 = n2.toElement();
                        if (!e2.isNull())
                        {
                            QString src = e2.attribute("src","");
                            Sources.append(src);
                        }
                        n2 = n2.nextSibling();
                    }
                }

                if (e.attribute("type","") == "header")
                {
                    QDomNode n2 = e.firstChild();
                    while (!n2.isNull())
                    {
                        QDomElement e2 = n2.toElement();
                        if (!e2.isNull())
                        {
                            QString h = e2.attribute("src","");
                            Headers.append(h);
                        }
                        n2 = n2.nextSibling();
                    }
                }
            }
        }
        n = n.nextSibling();
    }
}
예제 #11
0
void QgsLayerStylingWidget::setLayer( QgsMapLayer *layer )
{
  if ( layer == mCurrentLayer )
    return;

  if ( mCurrentLayer )
  {
    disconnect( mCurrentLayer, SIGNAL( styleChanged() ), this, SLOT( updateCurrentWidgetLayer() ) );
  }

  if ( !layer || !layer->isSpatial() )
  {
    mLayerCombo->setLayer( nullptr );
    mStackedWidget->setCurrentIndex( mNotSupportedPage );
    mLastStyleXml.clear();
    mCurrentLayer = nullptr;
    return;
  }

  bool sameLayerType = false;
  if ( mCurrentLayer )
  {
    sameLayerType =  mCurrentLayer->type() == layer->type();
  }

  mCurrentLayer = layer;

  mUndoWidget->setUndoStack( layer->undoStackStyles() );

  connect( mCurrentLayer, SIGNAL( styleChanged() ), this, SLOT( updateCurrentWidgetLayer() ) );

  int lastPage = mOptionsListWidget->currentIndex().row();
  mOptionsListWidget->blockSignals( true );
  mOptionsListWidget->clear();
  mUserPages.clear();
  if ( layer->type() == QgsMapLayer::VectorLayer )
  {
    QListWidgetItem* symbolItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/symbology.svg" ), QString() );
    symbolItem->setData( Qt::UserRole, Symbology );
    symbolItem->setToolTip( tr( "Symbology" ) );
    mOptionsListWidget->addItem( symbolItem );
    QListWidgetItem* labelItem = new QListWidgetItem( QgsApplication::getThemeIcon( "labelingSingle.svg" ), QString() );
    labelItem->setData( Qt::UserRole, VectorLabeling );
    labelItem->setToolTip( tr( "Labels" ) );
    mOptionsListWidget->addItem( labelItem );
  }
  else if ( layer->type() == QgsMapLayer::RasterLayer )
  {
    QListWidgetItem* symbolItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/symbology.svg" ), QString() );
    symbolItem->setData( Qt::UserRole, Symbology );
    symbolItem->setToolTip( tr( "Symbology" ) );
    mOptionsListWidget->addItem( symbolItem );
    QListWidgetItem* transparencyItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/transparency.png" ), QString() );
    transparencyItem->setToolTip( tr( "Transparency" ) );
    transparencyItem->setData( Qt::UserRole, RasterTransparency );
    mOptionsListWidget->addItem( transparencyItem );

    if ( static_cast<QgsRasterLayer*>( layer )->dataProvider()->capabilities() & QgsRasterDataProvider::Size )
    {
      QListWidgetItem* histogramItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/histogram.png" ), QString() );
      histogramItem->setData( Qt::UserRole, RasterHistogram );
      mOptionsListWidget->addItem( histogramItem );
      histogramItem->setToolTip( tr( "Histogram" ) );
    }
  }

  Q_FOREACH ( QgsMapLayerConfigWidgetFactory* factory, mPageFactories )
  {
    if ( factory->supportsStyleDock() && factory->supportsLayer( layer ) )
    {
      QListWidgetItem* item =  new QListWidgetItem( factory->icon(), QString() );
      item->setToolTip( factory->title() );
      mOptionsListWidget->addItem( item );
      int row = mOptionsListWidget->row( item );
      mUserPages[row] = factory;
    }
  }
  QListWidgetItem* historyItem = new QListWidgetItem( QgsApplication::getThemeIcon( "mActionHistory.svg" ), QString() );
  historyItem->setData( Qt::UserRole, History );
  historyItem->setToolTip( tr( "History" ) );
  mOptionsListWidget->addItem( historyItem );
  mOptionsListWidget->blockSignals( false );

  if ( sameLayerType )
  {
    mOptionsListWidget->setCurrentRow( lastPage );
  }
  else
  {
    mOptionsListWidget->setCurrentRow( 0 );
  }

  mStackedWidget->setCurrentIndex( 1 );

  QString errorMsg;
  QDomDocument doc( "style" );
  mLastStyleXml = doc.createElement( "style" );
  doc.appendChild( mLastStyleXml );
  mCurrentLayer->writeStyle( mLastStyleXml, doc, errorMsg );
}
예제 #12
0
//---------------------------------------------------------------------------
void TLevWrt::Load_Level(const char *fn)
{
// этот кусок кода пожаловал сюда прямиком из myRiseOfAtlantis :)
// -> с некоторыми изменениями, конечно :)
	const char *pfile = "file", *pobject = "object", *plock = "lock",
                   *pbackground = "background", *psunp = "sun p";
	const char *elementName, *type, *path, *xp, *yp;
	float xpos, ypos;

	TiXmlDocument doc(fn);
	doc.LoadFile();
	TiXmlElement* root = doc.FirstChildElement("level");
	TiXmlElement* element = root->FirstChildElement();

	while (element != NULL)
{
	elementName = element->Value();
	if (stricmp(elementName, pfile) == 0)//file
	{
		TiXmlAttribute* fattr = element->FirstAttribute();//first attribute
		if (fattr)
		{
			type = fattr->Value();
			TiXmlAttribute* sattr = fattr->Next();//second attribute
			path = sattr->Value();
			xp = NULL;
			yp = NULL;
                if (stricmp(type, pbackground) == 0)
                {
                  ObjType0->Text = type;
                  FilePath0->Text = path;
                } else
                if (stricmp(type, plock) == 0)
                {
                  ObjType7->Text = type;
                  FilePath7->Text = path;
                } else
                if (strstr(type, psunp) != NULL)
                {
                   String s = path;
                   char *c = s.c_str();
                   Make_Objects(c);
                } else
                for (int i = 0; i <= 7; i++)
                {
                String comp_name = compObjType + IntToStr(i);
                TComponent* comp = FindComponent(comp_name);
                TComboBox* box = dynamic_cast<TComboBox*>(comp);
                if (box->Text == "")
                {
                 box->Text = type;
                 String comp_name2 = compFilePath + IntToStr(i);
                 TComponent* comp2 = FindComponent(comp_name2);
                 TEdit* edit = dynamic_cast<TEdit*>(comp2);
                 edit->Text = path;
                break;
                }
                }
		element = element->NextSiblingElement();
		}
	} else
	if (stricmp(elementName, pobject) == 0)//object
	{
		TiXmlAttribute* fattr = element->FirstAttribute();//first attribute
		if (fattr)
		{
			type = fattr->Value();
			TiXmlAttribute* sattr = fattr->Next();//second attribute
			xp = sattr->Value();
			TiXmlAttribute* tattr = sattr->Next();//third attribute
			yp = tattr->Value();
			if (xp != NULL)
			{
			xpos = atof(xp);
			}
			if (yp != NULL)
			{
			ypos = atof(yp);
			}
                        for (int i = 1; i <= 121; i++)
                        {
                         String comp_name = compPanel + IntToStr(i);
                         TComponent* comp = FindComponent(comp_name);
                         TPanel* panel = dynamic_cast<TPanel*>(comp);
                         if ((panel->Left == xpos) && (panel->Top == ypos))
                         {
                          if (stricmp(type, plock) == 0)
                          {
                           panel->Color = clBlack;
                           panel->Font->Color = clWhite;
                          } else
                          if (stricmp(type, pbackground) == 0)
                          {
                           break;
                          } else {
                          panel->Caption = type;
                          panel->Color = clWhite;
                          }
                         }
			}
		element = element->NextSiblingElement();
		}
	}
}
}
예제 #13
0
PView *GMSH_TriangulatePlugin::execute(PView *v)
{
  int iView = (int)TriangulateOptions_Number[0].def;

  PView *v1 = getView(iView, v);
  if(!v1) return v;
  PViewData *data1 = v1->getData();

  if(data1->hasMultipleMeshes()){
    Msg::Error("Triangulate plugin cannot be applied to multi-mesh views");
    return v1;
  }

  // create list of points with associated data
  std::vector<MVertex*> points;
  int numSteps = data1->getNumTimeSteps();
  for(int ent = 0; ent < data1->getNumEntities(0); ent++){
    for(int ele = 0; ele < data1->getNumElements(0, ent); ele++){
      if(data1->skipElement(0, ent, ele)) continue;
      if(data1->getNumNodes(0, ent, ele) != 1) continue;
      int numComp = data1->getNumComponents(0, ent, ele);
      double x, y, z;
      data1->getNode(0, ent, ele, 0, x, y, z);
      PointData *p = new PointData(x, y, z, numComp * numSteps);
      for(int step = 0; step < numSteps; step++)
        for(int comp = 0; comp < numComp; comp++)
          data1->getValue(step, ent, ele, 0, comp, p->v[3 + numComp * step + comp]);
      points.push_back(p);
    }
  }

  if(points.size() < 3){
    Msg::Error("Need at least 3 points to triangulate");
    for(unsigned int i = 0; i < points.size(); i++)
      delete points[i];
    return v1;
  }

  // project points onto plane
  discreteFace *s = new discreteFace
    (GModel::current(), GModel::current()->getNumFaces() + 1);
  s->computeMeanPlane(points);
  double plan[3][3];
  s->getMeanPlaneData(plan);
  for(unsigned int i = 0; i < points.size(); i++) project(points[i], plan);
  delete s;

  // get lc
  SBoundingBox3d bbox;
  for(unsigned int i = 0; i < points.size(); i++) bbox += points[i]->point();
  double lc = norm(SVector3(bbox.max(), bbox.min()));

  // build a point record structure for the divide and conquer algorithm
  DocRecord doc(points.size());
  for(unsigned int i = 0; i < points.size(); i++){
    double XX = CTX::instance()->mesh.randFactor * lc * (double)rand() / (double)RAND_MAX;
    double YY = CTX::instance()->mesh.randFactor * lc * (double)rand() / (double)RAND_MAX;
    doc.points[i].where.h = points[i]->x() + XX;
    doc.points[i].where.v = points[i]->y() + YY;
    doc.points[i].adjacent = NULL;
    doc.points[i].data = (void*)points[i];
  }

  // triangulate
  doc.MakeMeshWithPoints();

  // create output (using unperturbed data)
  PView *v2 = new PView();
  PViewDataList *data2 = getDataList(v2);
  for(int i = 0; i < doc.numTriangles; i++){
    PointData *p[3];
    p[0] = (PointData*)doc.points[doc.triangles[i].a].data;
    p[1] = (PointData*)doc.points[doc.triangles[i].b].data;
    p[2] = (PointData*)doc.points[doc.triangles[i].c].data;
    int numComp = 0;
    std::vector<double> *vec = 0;
    if((int)p[0]->v.size() == 3 + 9 * numSteps &&
       (int)p[1]->v.size() == 3 + 9 * numSteps &&
       (int)p[2]->v.size() == 3 + 9 * numSteps){
      numComp = 9; data2->NbTT++; vec = &data2->TT;
    }
    else if((int)p[0]->v.size() == 3 + 3 * numSteps &&
            (int)p[1]->v.size() == 3 + 3 * numSteps &&
            (int)p[2]->v.size() == 3 + 3 * numSteps){
      numComp = 3; data2->NbVT++; vec = &data2->VT;
    }
    else{
      numComp = 1; data2->NbST++; vec = &data2->ST;
    }
    for(int nod = 0; nod < 3; nod++) vec->push_back(p[nod]->v[0]);
    for(int nod = 0; nod < 3; nod++) vec->push_back(p[nod]->v[1]);
    for(int nod = 0; nod < 3; nod++) vec->push_back(p[nod]->v[2]);
    for(int step = 0; step < numSteps; step++)
      for(int nod = 0; nod < 3; nod++)
        for(int comp = 0; comp < numComp; comp++)
          vec->push_back(p[nod]->v[3 + numComp * step + comp]);
  }

  for(unsigned int i = 0; i < points.size(); i++)
    delete points[i];

  for(int i = 0; i < data1->getNumTimeSteps(); i++)
    data2->Time.push_back(data1->getTime(i));
  data2->setName(data1->getName() + "_Triangulate");
  data2->setFileName(data1->getName() + "_Triangulate.pos");
  data2->finalize();

  return v2;
}
예제 #14
0
bool StringReplacerProc::init(KConfig* c, const QString& configGroup){
    //kDebug() << "StringReplacerProc::init: Running";
    QString wordsFilename =
        KGlobal::dirs()->saveLocation( "data" ,QLatin1String( "kttsd/stringreplacer/" ), false );
    if ( wordsFilename.isEmpty() ) return false;
    wordsFilename += configGroup;
    KConfigGroup config( c, configGroup );
    wordsFilename = config.readEntry( "WordListFile", wordsFilename );

    // Open existing word list.
    QFile file( wordsFilename );
    if ( !file.open( QIODevice::ReadOnly ) )
    {
        //kDebug() << "StringReplacerProc::init: couldn't open file " << wordsFilename;
        return false;
    }
    QDomDocument doc( QLatin1String( "" ) );
    if ( !doc.setContent( &file ) ) {
        //kDebug() << "StringReplacerProc::init: couldn't get xml from file " << wordsFilename;
        file.close();
        return false;
    }
    file.close();

    // Clear list.
    m_matchList.clear();
    m_substList.clear();

    // Name setting.
    // QDomNodeList nameList = doc.elementsByTagName( "name" );
    // QDomNode nameNode = nameList.item( 0 );
    // m_widget->nameLineEdit->setText( nameNode.toElement().text() );

    // Language Codes setting.  List may be single element of comma-separated values,
    // or multiple elements.
    m_languageCodeList.clear();
    QDomNodeList languageList = doc.elementsByTagName( QLatin1String( "language-code" ) );
    for ( int ndx=0; ndx < languageList.count(); ++ndx )
    {
        QDomNode languageNode = languageList.item( ndx );
        m_languageCodeList += languageNode.toElement().text().split( QLatin1Char(','), QString::SkipEmptyParts);
    }

    // AppId.  Apply this filter only if DCOP appId of application that queued
    // the text contains this string.  List may be single element of comma-separated values,
    // or multiple elements.
    m_appIdList.clear();
    QDomNodeList appIdList = doc.elementsByTagName( QLatin1String( "appid" ) );
    for ( int ndx=0; ndx < appIdList.count(); ++ndx )
    {
        QDomNode appIdNode = appIdList.item( ndx );
        m_appIdList += appIdNode.toElement().text().split( QLatin1Char( ',' ), QString::SkipEmptyParts);
    }

    // Word list.
    QDomNodeList wordList = doc.elementsByTagName(QLatin1String( "word" ) );
    const int wordListCount = wordList.count();
    for (int wordIndex = 0; wordIndex < wordListCount; ++wordIndex)
    {
        QDomNode wordNode = wordList.item(wordIndex);
        QDomNodeList propList = wordNode.childNodes();
        QString wordType;
        QString matchCase = QLatin1String( "No" ); // Default for old (v<=3.5.3) config files with no <case/>.
        QString match;
        QString subst;
        const int propListCount = propList.count();
        for (int propIndex = 0; propIndex < propListCount; ++propIndex)
        {
            QDomNode propNode = propList.item(propIndex);
            QDomElement prop = propNode.toElement();
            if (prop.tagName() == QLatin1String( "type" )) wordType = prop.text();
            if (prop.tagName() == QLatin1String( "case" )) matchCase = prop.text();
            if (prop.tagName() == QLatin1String( "match" ))
            {
                match = prop.text();
                cdataUnescape( &match );
            }
            if (prop.tagName() == QLatin1String( "subst" ))
            {
                subst = prop.text();
                cdataUnescape( &subst );
            }
        }
        // Build Regular Expression for each word's match string.
        QRegExp rx;
        rx.setCaseSensitivity(matchCase == QLatin1String( "Yes" )?Qt::CaseInsensitive:Qt::CaseSensitive);
        if ( wordType == QLatin1String( "Word" ) )
        {
                // TODO: Does \b honor strange non-Latin1 encodings?
            rx.setPattern( QLatin1String( "\\b" ) + match + QLatin1String( "\\b" ) );
        }
        else
        {
            rx.setPattern( match );
        }
            // Add Regular Expression to list (if valid).
        if ( rx.isValid() )
        {
            m_matchList.append( rx );
            m_substList.append( subst );
        }
    }
    return true;
}
예제 #15
0
/*! Reads the entire interface from a file, looking for keywords 
	inside the file. Loads the size of the dof space, all eg's
	(which define the size of the eg space), any normalization
	factors (optional) and the origin of the eg space (optional).

	The size of the dof space must be loaded before any eg's, 
	origin, etc can be loaded; is must also match the number of
	dof's in this robot.
*/
int
EigenGraspInterface::readFromFile(QString filename)
{
    //open xml file at "filename"
    	bool ok;
    	QString fileType = filename.section('.',-1,-1);
	QString xmlFilename;
	if (fileType == "xml"){
		//the file itself is XML
		xmlFilename = filename;
	} else {
	    	QTWARNING("Could not open " + xmlFilename);
		DBGA("Old non-xml file format is no longer supported");
		return 0;
	}

    	//load the graspit specific information in XML format or fail
	TiXmlDocument doc(xmlFilename);
	if(doc.LoadFile()==false){
		DBGA("Failed to open EG file: " << filename.latin1());
		QTWARNING("Could not open " + xmlFilename);
		return 0;
	}
    //get the dimensions
	int numDims = 0;
	QString valueStr;
	clear();
	TiXmlElement* root = doc.RootElement();
    	if(root == NULL){
		DBGA("The "<<filename.toStdString()<<" file must contain a root tag named EigenGrasps.");
		return 0;
	} else{
		valueStr = root->Attribute("dimensions");
		numDims = valueStr.toDouble(&ok); if (!ok) {DBGA("ERROR: Dimension should contain a number.");return 0;}
		if (numDims <= 0) {
		    	DBGA("invalid number of dimensions in EigenGrasps tag in file: "<<filename.toStdString());
			return 0;
		}
	}

    //get the list of EG's 
	std::list<const TiXmlElement*> elementList = findAllXmlElements(root, "EG");
	int numEG = countXmlElements(root, "EG");
	if (numEG < 1) {
		DBGA("Number of Eigengrasps specified: " << numEG);
		return 0;
	}
	std::list<const TiXmlElement*>::iterator p = elementList.begin();
	while(p!=elementList.end()){
		EigenGrasp *newGrasp = new EigenGrasp(numDims);
	    	if (!newGrasp->readFromXml(*p++)) return 0;
		newGrasp->normalize();
		mGrasps.push_back(newGrasp);
	}


    //get the orgin and process (if none setsimpleorgin)
	elementList = findAllXmlElements(root, "ORIGIN");
	int numORG = countXmlElements(root, "ORIGIN");
	if (!numORG) {
	    	DBGA("No EG origin found; using automatic origin");
		mOrigin = new EigenGrasp(numDims);
		setSimpleOrigin();
	}
	else if(numORG==1)
	{
		mOrigin = new EigenGrasp(numDims);
		if (!mOrigin->readFromXml(*(elementList.begin()))){ return 0;}
		checkOrigin();
	}
	else
	{
	    	DBGA("Multiple Origins specified in Eigen Grasp file.");
		return 0;
	}

    //get the norm and process (if none set to all 1's)
	elementList = findAllXmlElements(root, "NORM");
	int numNORM = countXmlElements(root, "NORM");
	if (!numNORM) {
		DBGA("No normalization data found; using factors of 1.0");
		mNorm = new EigenGrasp(numDims);
		mNorm->setOnes();
	}
	else if(numNORM==1)
	{
		mNorm = new EigenGrasp(numDims);
		if (!mNorm->readFromXml(*(elementList.begin()))){ return 0;}
		DBGA("EG Normalization data loaded from file");
	}
	else
	{
	    	DBGA("Multiple Normals specified in Eigen Grasp file.");
	    	return 0;
	}

	eSize = mGrasps.size();
	DBGA("Read " << eSize << " eigengrasps from EG file");

	computeProjectionMatrices();
	setMinMax();
	return 1;
}
예제 #16
0
 void TinyXMLParser::parseXMLFile(XMLHandler& handler, const String& filename, const String& schemaName, const String& resourceGroup)
 {
   TinyXMLDocument doc(handler, filename, schemaName, resourceGroup);
 }
예제 #17
0
//Get max and min chage but also check what type of a,b,c,x,y,z score/ions are present
void TandemReader::getMaxMinCharge(const std::string &fn, bool isDecoy){
  
  int nTot = 0, charge = 0;
  
  namespace xml = xsd::cxx::xml;
 
  ifstream ifs;
  ifs.exceptions(ifstream::badbit|ifstream::failbit);
    
  ifs.open(fn.c_str());
  if (!ifs)
  {
    ostringstream temp;
    temp << "Error : can not open file " << fn << std::endl;
    throw MyException(temp.str());
  }
  parser p;
  
  try
  {
    xml_schema::dom::auto_ptr< xercesc::DOMDocument> 
    doc (p.start (ifs, fn.c_str(),true, schemaDefinition,schema_major, schema_minor, scheme_namespace,true));
    assert(doc.get());
    
    for (doc = p.next(); doc.get() != 0; doc = p.next ())
    {  
      //Check that the tag name is group and that its not the inputput parameters
      if(XMLString::equals(groupStr,doc->getDocumentElement()->getTagName()) 
	&& XMLString::equals(groupModelStr,doc->getDocumentElement()->getAttribute(groupTypeStr)))  
      {
	      tandem_ns::group groupObj(*doc->getDocumentElement()); //Parse to the codesynthesis object model
	        
	      if(groupObj.z().present()) //We are sure we are not in parameters group so z(the charge) has to be present.
	      {
	        stringstream chargeStream (stringstream::in | stringstream::out);
	        chargeStream << groupObj.z();
	        chargeStream >> charge;
	        if (minCharge > charge) minCharge = charge;
	        if (maxCharge < charge) maxCharge = charge;
	        nTot++;
	      }
	      else
	      {
	        ostringstream temp;
	        temp << "Missing charge(attribute z in group element) for one or more groups in: " << fn << endl;
	        throw MyException(temp.str());
	      }
	      if(firstPSM)
	      {
	        //Check what type of scores/ions are present
	        BOOST_FOREACH (const tandem_ns::protein &protObj, groupObj.protein()) { //Protein
	          tandem_ns::protein::peptide_type peptideObj=protObj.peptide(); //Peptide
	          BOOST_FOREACH(const tandem_ns::domain &domainObj, peptideObj.domain()) { //Domain
	            //x,y,z
	            if (domainObj.x_score().present() && domainObj.x_ions().present()) {
            		x_score=true;
	            }
	            if (domainObj.y_score().present() && domainObj.y_ions().present()) {
            		y_score=true;
	            }
	            if (domainObj.z_score().present() && domainObj.z_ions().present()) {
		            z_score=true;
	            }
	            //a,b,c
	            if (domainObj.a_score().present() && domainObj.a_ions().present()) {
            		a_score=true;
	            }
	            if (domainObj.b_score().present() && domainObj.b_ions().present()) {
            		b_score=true;
	            }
	            if (domainObj.c_score().present() && domainObj.c_ions().present()) {
            		c_score=true;
	            }
	          } //End of for domain
	        } //End of for prot
	        firstPSM=false;
	      }
      }
예제 #18
0
void PacificaServices::downloadFinished(QNetworkReply *reply)
{
	const char *prefix = "";
	QDomElement root;
	QDomNode services;
	QDomNode n;
	QDomElement e;
	int i;
	int res;
	QUrl url;
	QVariant possible_redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
	url = possible_redirect.toUrl();
	if(!url.isEmpty() && current_url != url && redirect_count < 5)
	{
		redirect_count++;
		current_url = url;
std::cout << "Redirecting to " << url.toString().toStdString() << "\n";
		QNetworkRequest request(current_url);
		QNetworkReply *reply = manager.get(request);
		return;

	}
//FIXME handle error.
	_services = new QHash<QString, QString>();
//FIXME rename root element once server is updated.
	QDomDocument doc("myemsl");
	std::cout << doc.setContent(reply) << "\n";
	root = doc.documentElement();
	QDomNodeList list = root.elementsByTagName("prefix");
	for(i = 0; i < list.count(); i++)
	{
		e = list.at(i).toElement();
		prefix = strdup(e.text().toStdString().c_str());
	}
	QSettings settings;
	if(settings.contains("url/prefix"))
	{
		prefix = strdup(settings.value("url/prefix").toString().toStdString().c_str());
	}
	list = root.elementsByTagName("services");
	for(i = 0; i < list.count(); i++)
	{
		services = list.at(i);
	}
	list = services.childNodes();
	for(i = 0; i < list.count(); i++)
	{
		e = list.at(i).toElement();
		if(e.nodeName() == "service")
		{
			if(e.attribute("location", "").toStdString().c_str()[0] == '/')
			{
				_services->insert(e.attribute("name", NULL), prefix + e.attribute("location", ""));
			}
			else
			{
				_services->insert(e.attribute("name", NULL), e.attribute("location", ""));
			}
		}
	}
	ready(_services);
}
예제 #19
0
void QgsGrassNewMapset::loadRegions()
{

  QString path = QgsApplication::pkgDataPath() + "/grass/locations.gml";
  QgsDebugMsg( QString( "load:%1" ).arg( path.toLocal8Bit().constData() ) );

  QFile file( path );

  if ( !file.exists() )
  {
    QgsGrass::warning( tr( "Regions file (%1) not found." ).arg( path ) );
    return;
  }
  if ( ! file.open( QIODevice::ReadOnly ) )
  {
    QgsGrass::warning( tr( "Cannot open locations file (%1)" ).arg( path ) );
    return;
  }

  QDomDocument doc( QStringLiteral( "gml:FeatureCollection" ) );
  QString err;
  int line, column;

  if ( !doc.setContent( &file,  &err, &line, &column ) )
  {
    QString errmsg = tr( "Cannot read locations file (%1):" ).arg( path )
                     + tr( "\n%1\nat line %2 column %3" ).arg( err ).arg( line ).arg( column );
    QgsDebugMsg( errmsg );
    QgsGrass::warning( errmsg );
    file.close();
    return;
  }

  QDomElement docElem = doc.documentElement();
  QDomNodeList nodes = docElem.elementsByTagName( QStringLiteral( "gml:featureMember" ) );

  for ( int i = 0; i < nodes.count(); i++ )
  {
    QDomNode node = nodes.item( i );

    if ( node.isNull() )
    {
      continue;
    }

    QDomElement elem = node.toElement();
    QDomNodeList nameNodes = elem.elementsByTagName( QStringLiteral( "gml:name" ) );
    if ( nameNodes.count() == 0 )
      continue;
    if ( nameNodes.item( 0 ).isNull() )
      continue;

    QDomElement nameElem = nameNodes.item( 0 ).toElement();
    if ( nameElem.text().isNull() )
      continue;

    QDomNodeList envNodes = elem.elementsByTagName( QStringLiteral( "gml:Envelope" ) );
    if ( envNodes.count() == 0 )
      continue;
    if ( envNodes.item( 0 ).isNull() )
      continue;
    QDomElement envElem = envNodes.item( 0 ).toElement();

    QDomNodeList coorNodes = envElem.elementsByTagName( QStringLiteral( "gml:coordinates" ) );
    if ( coorNodes.count() == 0 )
      continue;
    if ( coorNodes.item( 0 ).isNull() )
      continue;
    QDomElement coorElem = coorNodes.item( 0 ).toElement();
    if ( coorElem.text().isNull() )
      continue;

    QStringList coor = coorElem.text().split( QStringLiteral( " " ), QString::SkipEmptyParts );
    if ( coor.size() != 2 )
    {
      QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) );
      continue;
    }

    QStringList ll = coor[0].split( QStringLiteral( "," ), QString::SkipEmptyParts );
    QStringList ur = coor[1].split( QStringLiteral( "," ), QString::SkipEmptyParts );
    if ( ll.size() != 2 || ur.size() != 2 )
    {
      QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) );
      continue;
    }

    // Add region
    mRegionsComboBox->addItem( nameElem.text() );

    QgsPointXY llp( ll[0].toDouble(), ll[1].toDouble() );
    mRegionsPoints.push_back( llp );
    QgsPointXY urp( ur[0].toDouble(), ur[1].toDouble() );
    mRegionsPoints.push_back( urp );
  }
  mRegionsComboBox->setCurrentIndex( -1 );

  file.close();
}
예제 #20
0
void SpecialsWindow::loadSpecials(const std::string &file)
{
    // TODO: mTabs->clear();
    while (mTabs->getSelectedTabIndex() != -1)
    {
        mTabs->removeTabWithIndex(mTabs->getSelectedTabIndex());
    }

    for (SpecialMap::iterator it = mSpecials.begin(); it != mSpecials.end();  it++)
    {
        delete (*it).second->display;
    }
    delete_all(mSpecials);
    mSpecials.clear();

    if (file.length() == 0)
        return;

    XML::Document doc(file);
    xmlNodePtr root = doc.rootNode();

    if (!root || !xmlStrEqual(root->name, BAD_CAST "specials"))
    {
        logger->log("Error loading specials file: %s", file.c_str());
        return;
    }

    int setCount = 0;
    std::string setName;
    ScrollArea *scroll;
    FlowContainer *container;

    for_each_xml_child_node(set, root)
    {
        if (xmlStrEqual(set->name, BAD_CAST "set"))
        {
            setCount++;
            setName = XML::getProperty(set, "name", strprintf(_("Specials Set %d"), setCount));

            container = new FlowContainer(SPECIALS_WIDTH, SPECIALS_HEIGHT);
            container->setOpaque(false);
            scroll = new ScrollArea(container);
            scroll->setOpaque(false);
            scroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
            scroll->setVerticalScrollPolicy(ScrollArea::SHOW_ALWAYS);

            mTabs->addTab(setName, scroll);
            for_each_xml_child_node(node, set)
            {
                if (xmlStrEqual(node->name, BAD_CAST "special"))
                {
                    int id = atoi(XML::getProperty(node, "id", "-1").c_str());
                    if (id == -1)
                        continue;
                    std::string name = XML::getProperty(node, "name", strprintf(_("Special %d"), id));
                    std::string icon = XML::getProperty(node, "icon", "");

                    SpecialInfo *special = new SpecialInfo;
                    special->id = id;
                    special->name = name;
                    special->icon = icon;
                    special->display = new SpecialEntry(special);

                    container->add(special->display);

                    mSpecials[id] = special;
                }
            }
        }
    }
예제 #21
0
  void EndoDebugFromXmlFile::Update()
  {
    endodebug( __FUNCTION__ )

    std::string _FileName = *d->m_FileName;
    if( !itksys::SystemTools::FileExists( _FileName.c_str() ) )
    {
      endodebug(_FileName << " does not exist");
      return;
    }

    long int _FileModifiedTime
      = itksys::SystemTools::ModifiedTime( _FileName.c_str() );
    // file has changed: we know an older version...
    if( d->m_FileModifiedTime >= _FileModifiedTime )
    {
        endodebug("File not changed. No Update necessary.");
        return;
    }

    // reread
    endodebugvar( _FileName )
    TiXmlDocument doc( _FileName );
    doc.LoadFile();
    TiXmlHandle docHandle( &doc );
    TiXmlElement* elem = docHandle.FirstChildElement().FirstChildElement( "EndoDebug" ).ToElement();

    if(elem == 0)
    {
      endodebug("EndoDebug element not found");
      return;
    }

    int _DebugEnabled = d->m_EndoDebug->GetDebugEnabled();
    if( elem->QueryIntAttribute("DebugEnabled",&_DebugEnabled) != TIXML_SUCCESS )
      endodebug("DebugEnabled attribute not found");

    int _ShowImagesInDebug = d->m_EndoDebug->GetShowImagesInDebug();
    if( elem->QueryIntAttribute("ShowImagesInDebug",&_ShowImagesInDebug) != TIXML_SUCCESS )
      endodebug("ShowImagesInDebug attribute not found");

    int _ShowImagesTimeOut = d->m_EndoDebug->GetShowImagesTimeOut();
    if( elem->QueryIntAttribute("ShowImagesTimeOut",&_ShowImagesTimeOut) != TIXML_SUCCESS )
      endodebug("ShowImagesTimeOut attribute not found");

    std::string _DebugImagesOutputDirectory = d->m_EndoDebug->GetDebugImagesOutputDirectory();
    if( elem->QueryStringAttribute("DebugImagesOutputDirectory",&_DebugImagesOutputDirectory) != TIXML_SUCCESS )
      endodebug("DebugImagesOutputDirectory attribute not found");

    std::set<std::string> _FilesToDebug;
    std::string _FilesToDebugString;
    if( elem->QueryStringAttribute("FilesToDebug",&_FilesToDebugString) != TIXML_SUCCESS )
    {
      endodebug("FilesToDebug attribute not found");
    }
    else
    {
        StringExplode( _FilesToDebugString, ";", &_FilesToDebug );
    }

    std::set<std::string> _SymbolsToDebug;
    std::string _SymbolsToDebugString;
    if( elem->QueryStringAttribute("SymbolsToDebug",&_SymbolsToDebugString) != TIXML_SUCCESS )
    {
      endodebug("SymbolsToDebug attribute not found");
    }
    else
    {
        StringExplode( _SymbolsToDebugString, ";", &_SymbolsToDebug );
    }

    // save
    mitk::EndoDebug::GetInstance().SetDebugEnabled( _DebugEnabled == 1? true: false );
    mitk::EndoDebug::GetInstance().SetShowImagesInDebug( _ShowImagesInDebug == 1? true: false  );
    mitk::EndoDebug::GetInstance().SetShowImagesTimeOut( _ShowImagesTimeOut );
    mitk::EndoDebug::GetInstance().SetDebugImagesOutputDirectory( _DebugImagesOutputDirectory );
    mitk::EndoDebug::GetInstance().SetFilesToDebug(_FilesToDebug);
    mitk::EndoDebug::GetInstance().SetSymbolsToDebug(_SymbolsToDebug);

    // save that modified time
    d->m_FileModifiedTime = _FileModifiedTime;
  }
예제 #22
0
bool XmlCndInterface::write(std::ostream& stream)
{
	stream << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"; // xml definition
	stream << "<?xml-stylesheet type=\"text/xsl\" href=\"OpenGeoSysCND.xsl\"?>\n\n"; // stylefile definition

	QDomDocument doc("OGS-CND-DOM");
	QDomElement root = doc.createElement("OpenGeoSysCond");
	root.setAttribute( "xmlns:ogs", "http://www.opengeosys.org" );
	root.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" );
	root.setAttribute( "xsi:noNamespaceSchemaLocation", "http://www.opengeosys.org/images/xsd/OpenGeoSysCND.xsd" );

	std::vector<FEMCondition*> const& conditions (_project->getConditions(
	                                                     FiniteElement::INVALID_PROCESS,
	                                                     _exportName,
	                                                     _type) );

	if (conditions.empty())
		return 1;

	doc.appendChild(root);

	size_t nConditions (conditions.size());
	for (size_t i = 0; i < nConditions; i++)
	{
		FEMCondition::CondType current_type = conditions[i]->getCondType();
		if (current_type == _type || _type == FEMCondition::UNSPECIFIED)
		{
			QDomElement listTag;
			QString condText;

			if (current_type == FEMCondition::BOUNDARY_CONDITION)
			{
				listTag = this->getCondListElement(doc, root, "BoundaryConditions");
				condText = "BC";
			}
			else if (current_type == FEMCondition::INITIAL_CONDITION)
			{
				listTag = this->getCondListElement(doc, root, "InitialConditions");
				condText = "IC";
			}
			else if (current_type == FEMCondition::SOURCE_TERM)
			{
				listTag = this->getCondListElement(doc, root, "SourceTerms");
				condText = "ST";
			}
			else
			{
				ERR("XmlCndInterface::writeFile(): Unspecified FEMConditions found ... Abort writing.");
				return 0;
			}
			this->writeCondition(doc,
			                     listTag,
			                     conditions[i],
			                     condText,
			                     QString::fromStdString(_exportName));
		}
	}
	std::string xml = doc.toString().toStdString();
	stream << xml;

	return true;
}
예제 #23
0
GoSource::Ptr GoSource::create(const QString &fileName)
{
    GoSource::Ptr doc(new GoSource(fileName));
    return doc;
}
예제 #24
0
bool EPSPlug::import(QString fName, const TransactionSettings &trSettings, int flags, bool showProgress)
{
#ifdef Q_OS_OSX
	#if QT_VERSION >= 0x050300
		showProgress = false;
	#endif
#endif

	bool success = false;
	interactive = (flags & LoadSavePlugin::lfInteractive);
	cancel = false;
	double x, y, b, h;
	bool ret = false;
	bool found = false;
	CustColors.clear();
	QFileInfo fi = QFileInfo(fName);
	QString ext = fi.suffix().toLower();
	if ( !ScCore->usingGUI() ) {
		interactive = false;
		showProgress = false;
	}
	if ( showProgress ) 
	{
		ScribusMainWindow* mw=(m_Doc==0) ? ScCore->primaryMainWindow() : m_Doc->scMW();
		progressDialog = new MultiProgressDialog( tr("Importing: %1").arg(fi.fileName()), CommonStrings::tr_Cancel, mw);
		QStringList barNames, barTexts;
		barNames << "GI";
		barTexts << tr("Analyzing PostScript:");
		QList<bool> barsNumeric;
		barsNumeric << false;
		progressDialog->addExtraProgressBars(barNames, barTexts, barsNumeric);
		progressDialog->setOverallTotalSteps(3);
		progressDialog->setOverallProgress(0);
		progressDialog->setProgress("GI", 0);
		progressDialog->show();
		connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelRequested()));
		qApp->processEvents();
	}
	else {
		progressDialog = NULL;
	}
	
/* Set default Page to size defined in Preferences */
	x = 0.0;
	y = 0.0;
	b = PrefsManager::instance()->appPrefs.docSetupPrefs.pageWidth;
	h = PrefsManager::instance()->appPrefs.docSetupPrefs.pageHeight;
	if (extensionIndicatesEPSorPS(ext))
	{
		QString tmp, BBox, tmp2, FarNam;
		ScColor cc;
		QFile f(fName);
		if (f.open(QIODevice::ReadOnly))
		{
/* Try to find Bounding Box */
			QDataStream ts(&f);
			while (!ts.atEnd())
			{
				tmp = readLinefromDataStream(ts);
				if (tmp.startsWith("%%BoundingBox:"))
				{
					found = true;
					BBox = tmp.remove("%%BoundingBox:");
				}
				if (!found)
				{
					if (tmp.startsWith("%%BoundingBox"))
					{
						found = true;
						BBox = tmp.remove("%%BoundingBox");
					}
				}
				if (tmp.startsWith("%%EndComments"))
					break; 
			}
			f.close();
			if (found)
			{
				QStringList bb = BBox.split(" ", QString::SkipEmptyParts);
				if (bb.count() == 4)
				{
					x = ScCLocale::toDoubleC(bb[0]);
					y = ScCLocale::toDoubleC(bb[1]);
					b = ScCLocale::toDoubleC(bb[2]);
					h = ScCLocale::toDoubleC(bb[3]);
				}
			}
		}
		importColorsFromFile(fName, CustColors);
	}
#ifdef HAVE_PODOFO
	else if (extensionIndicatesPDF(ext))
	{
		try
		{
			PoDoFo::PdfError::EnableDebug( false );
#if (PODOFO_VERSION == 0 && PODOFO_MINOR > 6)
		PoDoFo::PdfError::EnableLogging( false );
#endif
#if (PODOFO_VERSION == 0 && PODOFO_MINOR == 5 && PODOFO_REVISION == 99) || PODOFO_MINOR > 5
			PoDoFo::PdfMemDocument doc( fName.toLocal8Bit().data() );
#else
			PoDoFo::PdfDocument doc( fName.toLocal8Bit().data() );
#endif
			PoDoFo::PdfPage *curPage = doc.GetPage(0);
			if (curPage != NULL)
			{
				PoDoFo::PdfRect rect = curPage->GetMediaBox();
				b = rect.GetWidth() - rect.GetLeft();
				h = rect.GetHeight() - rect.GetBottom();
			}
		}
		catch(PoDoFo::PdfError& e)
		{
			qDebug("%s", "PoDoFo error while reading page size!");
			e.PrintErrorMsg();
		}
	}
#endif
	baseX = 0;
	baseY = 0;
	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
	{
		m_Doc->setPage(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false);
		m_Doc->addPage(0);
		m_Doc->view()->addPage(0, true);
		baseX = 0;
		baseY = 0;
	}
	else
	{
		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
		{
			m_Doc=ScCore->primaryMainWindow()->doFileNew(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
			ScCore->primaryMainWindow()->HaveNewDoc();
			ret = true;
			baseX = 0;
			baseY = 0;
		}
	}
	if ((!ret) && (interactive))
	{
		baseX = m_Doc->currentPage()->xOffset();
		baseY = m_Doc->currentPage()->yOffset();
	}
	if ((ret) || (!interactive))
	{
		if (b-x > h-y)
			m_Doc->setPageOrientation(1);
		else
			m_Doc->setPageOrientation(0);
		m_Doc->setPageSize("Custom");
	}
	ColorList::Iterator it;
	for (it = CustColors.begin(); it != CustColors.end(); ++it)
	{
		if (!m_Doc->PageColors.contains(it.key()))
			m_Doc->PageColors.insert(it.key(), it.value());
	}
	boundingBoxRect.addRect(0, 0, b-x, h-y);
	Elements.clear();
	m_Doc->setLoading(true);
	m_Doc->DoDrawing = false;
	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
		m_Doc->view()->updatesOn(false);
	m_Doc->scMW()->setScriptRunning(true);
	qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
	QString CurDirP = QDir::currentPath();
	QDir::setCurrent(fi.path());
	if (convert(fName, x, y, b, h))
	{
// 		m_Doc->m_Selection->clear();
		tmpSel->clear();
		QDir::setCurrent(CurDirP);
//		if ((Elements.count() > 1) && (interactive))
		if (Elements.count() > 1)
			m_Doc->groupObjectsList(Elements);
		m_Doc->DoDrawing = true;
		m_Doc->scMW()->setScriptRunning(false);
		m_Doc->setLoading(false);
		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
		if ((Elements.count() > 0) && (!ret) && (interactive))
		{
			if (flags & LoadSavePlugin::lfScripted)
			{
				bool loadF = m_Doc->isLoading();
				m_Doc->setLoading(false);
				m_Doc->changed();
				m_Doc->setLoading(loadF);
				if (!(flags & LoadSavePlugin::lfLoadAsPattern))
				{
					m_Doc->m_Selection->delaySignalsOn();
					for (int dre=0; dre<Elements.count(); ++dre)
					{
						m_Doc->m_Selection->addItem(Elements.at(dre), true);
					}
					m_Doc->m_Selection->delaySignalsOff();
					m_Doc->m_Selection->setGroupRect();
					m_Doc->view()->updatesOn(true);
				}
			}
			else
			{
				m_Doc->DragP = true;
				m_Doc->DraggedElem = 0;
				m_Doc->DragElements.clear();
				m_Doc->m_Selection->delaySignalsOn();
				for (int dre=0; dre<Elements.count(); ++dre)
				{
					tmpSel->addItem(Elements.at(dre), true);
				}
				tmpSel->setGroupRect();
				ScriXmlDoc *ss = new ScriXmlDoc();
				ScElemMimeData* md = new ScElemMimeData();
				md->setScribusElem(ss->WriteElem(m_Doc, tmpSel));
				delete ss;
/*#ifndef Q_WS_MAC*/
// see #2196
				m_Doc->itemSelection_DeleteItem(tmpSel);
/*#else
				qDebug() << "psimport: leaving items on page";
#endif*/
				m_Doc->view()->updatesOn(true);
				m_Doc->m_Selection->delaySignalsOff();
				// We must copy the TransationSettings object as it is owned
				// by handleObjectImport method afterwards
				TransactionSettings* transacSettings = new TransactionSettings(trSettings);
				m_Doc->view()->handleObjectImport(md, transacSettings);
				m_Doc->DragP = false;
				m_Doc->DraggedElem = 0;
				m_Doc->DragElements.clear();
			}
		}
		else
		{
			m_Doc->changed();
			m_Doc->reformPages();
			if (!(flags & LoadSavePlugin::lfLoadAsPattern))
				m_Doc->view()->updatesOn(true);
		}
		success = true;
	}
	else
	{
		QDir::setCurrent(CurDirP);
		m_Doc->DoDrawing = true;
		m_Doc->scMW()->setScriptRunning(false);
		m_Doc->view()->updatesOn(true);
		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
	}
	if (interactive)
		m_Doc->setLoading(false);
	//CB If we have a gui we must refresh it if we have used the progressbar
	if (!(flags & LoadSavePlugin::lfLoadAsPattern))
	{
		if ((showProgress) && (!interactive))
			m_Doc->view()->DrawNew();
	}
	return success;
}
예제 #25
0
 Data next() {
     Document doc(_iterator.next().Obj());
     return make_pair(_sorter->extractKey(doc), doc);
 }
예제 #26
0
bool MainWindow2::saveObject( QString strSavedFilename )
{
    QString filePath = strSavedFilename;

    bool savingTheOLDWAY = filePath.endsWith( PFF_OLD_EXTENSION );

    QFileInfo fileInfo( filePath );
    if ( fileInfo.isDir() ) return false;

    QString tmpFilePath;
    if ( !savingTheOLDWAY )
    {// create temporary directory for compressing files
        tmpFilePath = QDir::tempPath() + "/" + fileInfo.completeBaseName() + PFF_TMP_COMPRESS_EXT;
        QFileInfo tmpDataInfo( tmpFilePath );
        if ( !tmpDataInfo.exists() )
        {
            QDir dir( QDir::tempPath() ); // --the directory where filePath is or will be saved
            dir.mkpath( tmpFilePath ); // --creates a directory with the same name +".data"
        }
    }
    else
    {
        tmpFilePath = fileInfo.absolutePath();
    }


    QString dataLayersDir;
    if ( savingTheOLDWAY )
    {
        dataLayersDir = filePath + "." + PFF_LAYERS_DIR;
    }
    else
    {
        dataLayersDir = tmpFilePath + "/" + PFF_LAYERS_DIR;
    }
    QFileInfo dataInfo( dataLayersDir );
    if ( !dataInfo.exists() )
    {
        QDir dir( tmpFilePath ); // the directory where filePath is or will be saved
        dir.mkpath( dataLayersDir ); // creates a directory with the same name +".data"
    }

    //savedName = filePath;
    this->setWindowTitle( filePath );

    QProgressDialog progress( tr("Saving document..."), tr("Abort"), 0, 100, this );
    progress.setWindowModality( Qt::WindowModal );
    progress.show();
    int progressValue = 0;

    // save data
    int nLayers = m_object->getLayerCount();
    qDebug( "Layer Count=%d", nLayers );

    for ( int i = 0; i < nLayers; i++ )
    {
        Layer* layer = m_object->getLayer( i );
        qDebug() << "Saving Layer " << i << "(" << layer->name << ")";

        progressValue = (i * 100) / nLayers;
        progress.setValue( progressValue );
        if ( layer->type() == Layer::BITMAP ) ((LayerBitmap*)layer)->saveImages( dataLayersDir, i );
        if ( layer->type() == Layer::VECTOR ) ((LayerVector*)layer)->saveImages( dataLayersDir, i );
        if ( layer->type() == Layer::SOUND ) ((LayerSound*)layer)->saveImages( dataLayersDir, i );
    }

    // save palette
    m_object->savePalette( dataLayersDir );

    // -------- save main XML file -----------
    QString mainXMLfile;
    if ( !savingTheOLDWAY )
    {
        mainXMLfile = tmpFilePath + "/" + PFF_XML_FILE_NAME;
    }
    else
    {
        mainXMLfile = filePath;
    }
    QFile* file = new QFile( mainXMLfile );
    if ( !file->open( QFile::WriteOnly | QFile::Text ) )
    {
        //QMessageBox::warning(this, "Warning", "Cannot write file");
        return false;
    }
    QTextStream out( file );
    QDomDocument doc( "PencilDocument" );
    QDomElement root = doc.createElement( "document" );
    doc.appendChild( root );

    // save editor information
    QDomElement editorElement = createDomElement( doc );
    root.appendChild( editorElement );
    qDebug( "Save Editor Node." );

    // save object
    QDomElement objectElement = m_object->createDomElement( doc );
    root.appendChild( objectElement );
    qDebug( "Save Object Node." );

    int IndentSize = 2;
    doc.save( out, IndentSize );
    // -----------------------------------

    if ( !savingTheOLDWAY )
    {
        qDebug() << "Now compressing data to PFF - PCLX ...";

        JlCompress::compressDir( filePath, tmpFilePath );
        removePFFTmpDirectory( tmpFilePath ); // --removing temporary files

        qDebug() << "Compressed. File saved.";
    }

    progress.setValue( 100 );

    m_object->modified = false;
    m_pTimeLine->updateContent();

    m_object->setFilePath( strSavedFilename );

    m_recentFileMenu->addRecentFile( strSavedFilename );
    m_recentFileMenu->saveToDisk();

    return true;
}
예제 #27
0
// A font is specified by two files: a TGA file with the rendered 
// chars for the font, and a XML file which contains global info 
// about the font and the texture coordinates and width of each char
// The parameter fontName is the filename without extension. 
// It is assumed that the files are "fontName.xml" and "fontName.tga"
bool
VSFontLib::load(std::string fontName) 
{
	// Test if image file exists
	FILE *fp;
	std::string s;
	errno_t err = -1;

	s = fontName + ".tga";
	err = fopen_s(&fp, s.c_str(), "r");
	if (fp == NULL || err == -1)
	{
		printf("Unable to find font texture: %s", s.c_str());
		return false;
	}
	
	mFontTex = loadRGBATexture(s, true, false, GL_LINEAR, GL_REPEAT);

	s = fontName + ".xml";
	TiXmlDocument doc(s.c_str());
	bool loadOK = doc.LoadFile();

	if (!loadOK) {
		printf("Problem reading the XML font definition file: %s", s.c_str());
		return false;
	}
	TiXmlHandle hDoc(&doc);
	TiXmlHandle hRoot(0);
	TiXmlElement *pElem;

	pElem = hDoc.FirstChildElement().Element();
	if (0 == pElem)
		return false;

	hRoot = TiXmlHandle(pElem);
	
	pElem->QueryIntAttribute("numchars",&mNumChars);

	if (mNumChars == 0)
		return false;

	hRoot = hRoot.FirstChild("characters");
	pElem = hRoot.FirstChild("chardata").Element();
	if (pElem)
		pElem->QueryIntAttribute("hgt",&mHeight);
	VSFLChar aChar;
	int charCode, numChars = 0;
	for(; 0 != pElem; pElem = pElem->NextSiblingElement(), ++numChars) {

		pElem->QueryIntAttribute("char",&charCode);
		pElem->QueryIntAttribute("wid",&(aChar.width));
		pElem->QueryFloatAttribute("X1", &(aChar.x1));
		pElem->QueryFloatAttribute("X2", &(aChar.x2));
		pElem->QueryFloatAttribute("Y1", &(aChar.y1));
		pElem->QueryFloatAttribute("Y2", &(aChar.y2));
		pElem->QueryIntAttribute("A", &(aChar.A));
		pElem->QueryIntAttribute("C", &(aChar.C));
		mChars[(unsigned char)charCode] = aChar;
	}
	printf("Font has %d chars", numChars);
	return true;
}
예제 #28
0
void NPCDB::loadXmlFile(const std::string &fileName)
{
    XML::Document doc(fileName, true, false);
    const XmlNodePtrConst rootNode = doc.rootNode();

    if (!rootNode || !xmlNameEqual(rootNode, "npcs"))
    {
        logger->log("NPC Database: Error while loading %s!",
            paths.getStringValue("npcsFile").c_str());
        mLoaded = true;
        return;
    }

    // iterate <npc>s
    for_each_xml_child_node(npcNode, rootNode)
    {
        if (xmlNameEqual(npcNode, "include"))
        {
            const std::string name = XML::getProperty(npcNode, "name", "");
            if (!name.empty())
                loadXmlFile(name);
            continue;
        }

        if (!xmlNameEqual(npcNode, "npc"))
            continue;

        const int id = XML::getProperty(npcNode, "id", 0);
        BeingInfo *currentInfo = nullptr;
        if (id == 0)
        {
            logger->log("NPC Database: NPC with missing ID in %s!",
                paths.getStringValue("npcsFile").c_str());
            continue;
        }
        else if (mNPCInfos.find(id) != mNPCInfos.end())
        {
            logger->log("NpcDB: Redefinition of npc ID %d", id);
            currentInfo = mNPCInfos[id];
        }
        if (!currentInfo)
            currentInfo = new BeingInfo;

        currentInfo->setTargetSelection(XML::getBoolProperty(npcNode,
            "targetSelection", true));

        BeingCommon::readBasicAttributes(currentInfo, npcNode, "talk");

        currentInfo->setDeadSortOffsetY(XML::getProperty(npcNode,
            "deadSortOffsetY", 31));

        currentInfo->setAvatarId(static_cast<uint16_t>(XML::getProperty(
            npcNode, "avatar", 0)));

        SpriteDisplay display;
        for_each_xml_child_node(spriteNode, npcNode)
        {
            if (xmlNameEqual(spriteNode, "sprite"))
            {
                if (!spriteNode->xmlChildrenNode)
                    continue;

                SpriteReference *const currentSprite = new SpriteReference;
                currentSprite->sprite = reinterpret_cast<const char*>(
                    spriteNode->xmlChildrenNode->content);
                currentSprite->variant =
                    XML::getProperty(spriteNode, "variant", 0);
                display.sprites.push_back(currentSprite);
            }
            else if (xmlNameEqual(spriteNode, "particlefx"))
            {
                if (!spriteNode->xmlChildrenNode)
                    continue;

                display.particles.push_back(reinterpret_cast<const char*>(
                    spriteNode->xmlChildrenNode->content));
            }
            else if (xmlNameEqual(spriteNode, "menu"))
            {
                std::string name = XML::getProperty(spriteNode, "name", "");
                std::string command = XML::langProperty(spriteNode,
                    "command", "");
                currentInfo->addMenu(name, command);
            }
        }

        currentInfo->setDisplay(display);
        if (currentInfo->getMenu().empty())
        {
            currentInfo->addMenu(_("Talk"), "talk 'NAME'");
            currentInfo->addMenu(_("Buy"), "buy 'NAME'");
            currentInfo->addMenu(_("Sell"), "sell 'NAME'");
        }
        mNPCInfos[id] = currentInfo;
    }
}
예제 #29
0
bool UpgradeChecker::process()
{
	if (!m_file)
		return false;
	QTextStream ts(m_file);
	ts.setCodec(QTextCodec::codecForName("UTF-8"));
	QString errorMsg;
	int eline;
	int ecol;
	QDomDocument doc( "scribusversions" );
	QString data(ts.readAll());
	if ( !doc.setContent( data, &errorMsg, &eline, &ecol )) 
	{
		if (data.toLower().contains("404 not found"))
			outputText("<b>"+ tr("File not found on server")+"</b>");
		else
			outputText("<b>"+ tr("Could not open version file: %1\nError:%2 at line: %3, row: %4").arg(m_file->fileName()).arg(errorMsg).arg(eline).arg(ecol)+"</b>");
		return false;
	}
	
	QDomElement docElem = doc.documentElement();
	QDomNode n = docElem.firstChild();
	while( !n.isNull() ) {
		QDomElement e = n.toElement();
		if( !e.isNull() ) {
			if (e.tagName()=="release")
			{
				if (e.hasAttribute("stability") && e.hasAttribute("platform") && e.hasAttribute("version"))
				{
					if (e.attribute("platform")==m_platform)
					{
						bool newVersion = false;
						QString verA(e.attribute("version"));
						QString verAStripped=verA.toLower();
						bool verIsCVS=verAStripped.contains("cvs");
						if (verIsCVS)
							verAStripped.remove("cvs");
						uint verMajor=verAStripped.section('.',0,0).toInt();
						uint verMinor=verAStripped.section('.',1,1).toInt();
						uint verRevsion1=verAStripped.section('.',2,2).toInt();
						uint verRevsion2=verAStripped.section('.',3,3).toInt();
						//If we found a release whe a user is running an old CVS version
						if (verMajor==major && verMinor==minor && verRevsion1==m_revision1 && verRevsion2==m_revision2 && m_isCVS && !verIsCVS && !m_updates.contains(verA))
							newVersion = true;
						else
						//If we found a version that is not the same as what we are running
						if (!(verMajor==major && verMinor==minor && verRevsion1==m_revision1 && verRevsion2==m_revision2))
						{
							if (
								((verMajor>major) ||
								(verMajor==major && verMinor>minor) ||
								(verMajor==major && verMinor==minor && verRevsion1>m_revision1) ||
								(verMajor==major && verMinor==minor && verRevsion1==m_revision1 && verRevsion2>m_revision2))
								&& !m_updates.contains(verA)
								)
								newVersion = true;
						}
						if (newVersion)
						{
							QString ver = verA;
							QString link = e.attribute("link", "");
							if (!link.isEmpty())
							{
								QString linkStr = QString("<a href=\"%1\">%2</a>").arg(link).arg(link);
								ver = QString("%1 : %2").arg(verA).arg(linkStr);
							}
							m_updates.append(ver);
						}
					}
				}
			}
			else
			if (e.tagName()=="message")
			{
				m_message+=e.text();
			}
		}
		n = n.nextSibling();
	}
	return true;
}
예제 #30
0
	void Track::loadFromFile(const string& filename)
	{
		TiXmlDocument doc( filename.c_str() );
		
		bool loadOkay = doc.LoadFile();
		if(!loadOkay)
		{
			cerr << "Unable to open file." << endl;
			return;
		}

		TiXmlElement* root = doc.FirstChildElement();
		TiXmlElement* elem;
		TiXmlElement* innerElem;
		if(!root) return;

		//block: Nodes
		{
			nodes.clear();

			for(elem = root->FirstChildElement("Nodes")->FirstChildElement("Node"); elem; elem = elem->NextSiblingElement("Node"))
			{
				string label(elem->Attribute("label"));
				NodeFlags flags = parseNodeFlags(elem->Attribute("flags"));
				//if(label == "" || flags == NODE_NONE)
				//	continue;
				nodes.push_back(new Node(label, flags));
			}
		}

		//block: Edges
		{			
			for(elem = root->FirstChildElement("Nodes")->FirstChildElement("Node"); elem; elem = elem->NextSiblingElement("Node"))
			{
				string nodeLabel(elem->Attribute("label"));
				Node* node = getNodes(nodeLabel)[0];
				for(innerElem = elem->FirstChildElement("Edge"); innerElem; innerElem = innerElem->NextSiblingElement("Edge"))
				{
					string label(innerElem->Attribute("label"));
					EdgeFlags flags = parseEdgeFlags(innerElem->Attribute("flags"));
					Direction dir = parseDirection(innerElem->Attribute("direction"));
					string endpointLabel(innerElem->Attribute("endpoint"));
					Node* otherNode = getNodes(endpointLabel)[0];
					node->makeEdge(*otherNode, flags, dir, label);
				}
			}
		}

		//block: Constraints
		{
			for(elem = root->FirstChildElement("Nodes")->FirstChildElement("Node"); elem; elem = elem->NextSiblingElement("Node"))
			{
				string nodeLabel(elem->Attribute("label"));
				Node* node = getFirstNode(nodeLabel);
				for(innerElem = elem->FirstChildElement("Constraint"); innerElem; innerElem = innerElem->NextSiblingElement("Constraint"))
				{
					Constraint* c = parseConstraint(innerElem, this, node);
					vector<Node*> nodes = c->getAffectedNodes();
					for(size_t x = 0; x < nodes.size(); ++x)
					{
						nodes[x]->addConstraint(c);
					}
				}
			}
		}
	}