Exemplo n.º 1
0
  void TOPPASResources::load(const QString& file_name)
  {
    Param load_param;
    ParamXMLFile paramFile;
    paramFile.load(String(file_name), load_param);

    for (Param::ParamIterator it = load_param.begin(); it != load_param.end(); ++it)
    {
      StringList substrings;
      it.getName().split(':', substrings);
      if (substrings.size() != 2 ||
          substrings.back() != "url_list" ||
          (it->value).valueType() != DataValue::STRING_LIST)
      {
        std::cerr << "Invalid file format." << std::endl;
        return;
      }

      QString key = (substrings[0]).toQString();
      StringList url_list = (it->value);
      QList<TOPPASResource> resource_list;
      for (StringList::const_iterator it = url_list.begin(); it != url_list.end(); ++it)
      {
        resource_list << TOPPASResource(QUrl(it->toQString()));
      }

      add(key, resource_list);
    }
  }
Exemplo n.º 2
0
void CMakeProvider::writeSubEngines(const BuildSetup &setup, std::ofstream &workspace) const {
	for (EngineDescList::const_iterator i = setup.engines.begin(), end = setup.engines.end(); i != end; ++i) {
		// We ignore all sub engines here because they are handled in the inner loop
		if (!i->enable || isSubEngine(i->name, setup.engines) || i->subEngines.empty()) {
			continue;
		}

		std::string engineName;
		std::transform(i->name.begin(), i->name.end(), std::back_inserter(engineName), toupper);

		workspace << "set(SUB_ENGINES_" << engineName;
		for (StringList::const_iterator j = i->subEngines.begin(), subEnd = i->subEngines.end(); j != subEnd; ++j) {
			const EngineDesc &subEngine = findEngineDesc(*j, setup.engines);
			if (!subEngine.enable) continue;

			std::string subEngineName;
			std::transform(j->begin(), j->end(), std::back_inserter(subEngineName), toupper);

			workspace << " " << subEngineName;
		}
		workspace << ")\n";
	}

	workspace << "\n";
}
Exemplo n.º 3
0
String FileFilter::MakeAPIFilter() const
{
   String filter;

   if ( !extensions.IsEmpty() )
   {
      if ( !description.IsEmpty() )
      {
         filter += description;
         filter += " (";
      }

      for ( StringList::const_iterator i = extensions.Begin();
            i != extensions.End();
            ++i )
      {
         if ( i != extensions.Begin() )
            filter += ' '; // also legal are ';' and ','
         if ( i->StartsWith( '.' ) )
            filter += '*';
         filter += *i;
      }

      if ( !description.IsEmpty() )
         filter += ')';
   }

   return filter;
}
Exemplo n.º 4
0
void ExternalProcess::Start( const String& program, const StringList& arguments )
{
   Array<const char16_type*> argv;
   for ( StringList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
      argv.Add( i->c_str() );
   if ( (*API->ExternalProcess->StartExternalProcess)( handle, program.c_str(), argv.Begin(), argv.Length() ) == api_false )
      throw APIFunctionError( "StartExternalProcess" );
}
Exemplo n.º 5
0
void ExternalProcess::SetEnvironment( const StringList& environment )
{
   Array<const char16_type*> vars;
   for ( StringList::const_iterator i = environment.Begin(); i != environment.End(); ++i )
      vars.Add( i->c_str() );
   if ( (*API->ExternalProcess->SetExternalProcessEnvironment)( handle, vars.Begin(), vars.Length() ) == api_false )
      throw APIFunctionError( "SetExternalProcessEnvironment" );
}
Exemplo n.º 6
0
void SWOptionFilter::setOptionValue(const char *ival) {
	for (StringList::const_iterator loop = optValues->begin(); loop != optValues->end(); loop++) {
		if (!stricmp(loop->c_str(), ival)) {
			optionValue = *loop;
			option = (!strnicmp(ival, "On", 2));	// convenience for boolean filters
			break;
		}
	}
}
Exemplo n.º 7
0
int ExternalProcess::ExecuteProgram( const String& program, const StringList& arguments )
{
   Array<const char16_type*> argv;
   for ( StringList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
      argv.Add( i->c_str() );
   int retVal = (*API->ExternalProcess->ExecuteProgram)( program.c_str(), argv.Begin(), argv.Length() );
   if ( retVal < -1 )
      ExternalProcessPrivate::Throw( ExternalProcessContext::FailedToStart );
   return retVal;
}
Exemplo n.º 8
0
bool FileDataCacheItem::FromString( const String& s )
{
   path.Clear();
   lastUsed = 0;
   time.year = 0;

   StringList tokens;
   s.Break( tokens, char16_type( '\n' ) );

   for ( StringList::const_iterator i = tokens.Begin(); i != tokens.End(); )
   {
      if ( *i == "path" )
      {
         if ( ++i == tokens.End() )
            return false;
         path = i->Trimmed();
         ++i;
      }
      else if ( *i == "lastUsed" )
      {
         if ( ++i == tokens.End() )
            return false;
         lastUsed = i->ToUInt();
         ++i;
      }
      else if ( *i == "time" )
      {
         if ( tokens.End() - i < 3 )
            return false;
         int y, m, d; double f;
         JDToComplexTime( y, m, d, f, i[1].ToUInt()+0.5 );
         unsigned t = i[2].ToUInt();
         time.year = y;
         time.month = m;
         time.day = d;
         time.milliseconds = t - 86399000;
         time.hour = TruncI( (t = TruncI( t/1000.0 ))/3600.0 );
         time.minute = TruncI( (t -= time.hour*3600)/60.0 );
         time.second = t - time.minute*60;
         i += 3;
      }
      else if ( *i == "data" )
      {
         if ( !GetDataFromTokens( tokens ) )
            return false;
         ++i;
      }
      else
      {
         ++i;
      }
   }

   return !path.IsEmpty() && lastUsed > 0 && time.year > 0 && ValidateData();
}
Exemplo n.º 9
0
ExternalProcess::pid_type ExternalProcess::StartProgram( const String& program, const StringList& arguments, const String& workingDirectory )
{
   Array<const char16_type*> argv;
   for ( StringList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
      argv.Add( i->c_str() );
   uint64 pid = 0;
   api_bool ok = (*API->ExternalProcess->StartProgram)( program.c_str(), argv.Begin(), argv.Length(), workingDirectory.c_str(), &pid );
   if ( ok == api_false || pid == 0 )
      ExternalProcessPrivate::Throw( ExternalProcessContext::FailedToStart );
   return pid_type( pid );
}
Exemplo n.º 10
0
bool LDAPAttribute::isNotPrintable() const {
    StringList::const_iterator i;
    for(i=m_values.begin(); i!=m_values.end(); i++) {
        size_t len = i->size();
        for(size_t j=0; j<len; j++) {
            if (! isprint( (i->data())[j] ) ) {
                return true;
            }
        }
    }
    return false;
}
Exemplo n.º 11
0
bool FileDataCacheItem::GetVector( DVector& v, StringList::const_iterator& i, const StringList& s )
{
   if ( i == s.End() )
      return false;
   int n = i->ToInt();
   if ( n < 0 || s.End() - i <= n )
      return false;
   ++i;
   v = DVector( n );
   for ( int j = 0; j < n; ++j, ++i )
      v[j] = i->ToDouble();
   return true;
}
Exemplo n.º 12
0
   void LoadFiltersFromGlobalString( const IsoString& globalKey )
   {
      filters.Clear();

      String s = PixInsightSettings::GlobalString( globalKey  );
      if ( !s.IsEmpty() )
      {
         for ( size_type p = 0; ; )
         {
            size_type p1 = s.Find( '(', p );
            if ( p1 == String::notFound )
               break;

            size_type p2 = s.Find( ')', p1 );
            if ( p2 == String::notFound )
               break;

            String extStr = s.Substring( p1, p2-p1 );
            if ( !extStr.IsEmpty() )
            {
               StringList extLst;
               extStr.Break( extLst, ' ', true );
               if ( !extLst.IsEmpty() )
               {
                  FileFilter filter;

                  for ( StringList::const_iterator i = extLst.Begin(); i != extLst.End(); ++i )
                  {
                     size_type d = i->Find( '.' );
                     if ( d != String::notFound )
                        filter.AddExtension( i->Substring( d ) );
                  }

                  if ( !filter.Extensions().IsEmpty() )
                  {
                     String desc = s.Substring( p, p1-p );
                     desc.Trim();
                     filter.SetDescription( desc );

                     filters.Add( filter );
                  }
               }
            }

            p = p2 + 1;
         }
      }
   }
Exemplo n.º 13
0
StringList
Slice::ObjCGenerator::MetaDataVisitor::getMetaData(const ContainedPtr& cont)
{
    StringList ret;
    StringList localMetaData = cont->getMetaData();
    StringList::const_iterator p;

    for(p = localMetaData.begin(); p != localMetaData.end(); ++p)
    {
        if(p->find(_objcPrefix) != string::npos)
        {
            ret.push_back(*p);
        }
    }

    return ret;
}
Exemplo n.º 14
0
        /* {{{ MySQL_ArtResultSet::MySQL_ArtResultSet() -I- */
        MySQL_ArtResultSet::MySQL_ArtResultSet(const StringList& fn, rset_t* const rs, boost::shared_ptr< MySQL_DebugLogger > & l)
            : num_fields(static_cast<int>(fn.size())), rset(rs), current_record(rset->begin()),
              started(false), field_index_to_name_map(new sql::SQLString[num_fields]),
              num_rows(rset->size()), row_position(0), is_closed(false), logger(l)
        {
            CPP_ENTER("MySQL_ArtResultSet::MySQL_ArtResultSet");
            CPP_INFO_FMT("metadata.size=%d resultset.size=%d", fn.size(), rset->size());

            //	field_index_to_name_map = new sql::SQLString[num_fields];

            unsigned int idx = 0;
            for (StringList::const_iterator it = fn.begin(), e = fn.end(); it != e; ++it, ++idx) {
                boost::scoped_array< char > upstring(sql::mysql::util::utf8_strup(it->c_str(), 0));
                field_name_to_index_map[sql::SQLString(upstring.get())] = idx;
                field_index_to_name_map[idx] = upstring.get();
            }

            meta.reset(new MySQL_ArtResultSetMetaData(this, logger));
        }
void
mitk::DICOMGDCMTagScanner
::Scan()
{
  // TODO integrate push/pop locale??
  m_GDCMScanner.Scan( m_InputFilenames );

  m_ScanResult.clear();
  for (StringList::const_iterator inputIter = m_InputFilenames.begin();
       inputIter != m_InputFilenames.end();
       ++inputIter)
  {
    m_ScanResult.push_back( DICOMGDCMImageFrameInfo::New( DICOMImageFrameInfo::New(*inputIter, 0), m_GDCMScanner.GetMapping(inputIter->c_str()) ) );
  }
}
Exemplo n.º 16
0
void ClassMenuItemAdder::generateMenu(IMenu& createItem, const StringList& comboStrings)
{
	StringList::const_iterator it;
	int index = 0;
	for (it = comboStrings.begin(); it != comboStrings.end(); ++it) {
		StringList path;
		splitStringList(&path, it->c_str(), '\\');
		int level = 0;
		IMenu* item = &createItem;

		for(int level = 0; level < int(path.size()); ++level){
			const char* leaf = path[level].c_str();
			if(level == path.size() - 1){
				addAction(*item, leaf, index++);
			}
			else{
				if (property_tree::IMenu* menu = item->findMenu(leaf))
					item = menu;
				else
					item = addMenu(*item, leaf);
			}
		}
	}
}
Exemplo n.º 17
0
    Aside():
        config(Config::instance()),
        keyMUKey(config->keyMUKey),
        keyMUSign(config->keyMUSign),
        keyMUPrefixes(config->keyMUPrefixes),
        keyMUItem(config->keyMUItem),
        keyMUUpsert(config->keyMUUpsert),

        keyMDErrCode(config->keyMDErrCode.data(), config->keyMDErrCode.length()),
        keyMDErrDesc(config->keyMDErrDesc.data(), config->keyMDErrDesc.length()),
        keyMDPayload(config->keyMDPayload.data(), config->keyMDPayload.length()),
        keyMDToken(config->keyMDToken.data(), config->keyMDToken.length()),
        keyMDTokenExpire(config->keyMDTokenExpire.data(), config->keyMDTokenExpire.length()),

        keyId(config->keyId.data(), config->keyId.length()),
        keyQEchoData(config->keyQEchoData.data(), config->keyQEchoData.length()),

        keyQUPayload(config->keyQUPayload.data(), config->keyQUPayload.length()),
        keyQUToken(config->keyQUToken.data(), config->keyQUToken.length()),
        keyQUPrefix(config->keyQUPrefix.data(), config->keyQUPrefix.length()),
        keyQUFilters(config->keyQUFilters.data(), config->keyQUFilters.length()),
        keyQUExcludes(config->keyQUExcludes.data(), config->keyQUExcludes.length()),
        keyQUFields(config->keyQUFields.data(), config->keyQUFields.length()),
        keyQUNum(config->keyQUNum.data(), config->keyQUNum.length()),

        keyQDErrCode(config->keyQDErrCode.data(), config->keyQDErrCode.length()),
        keyQDErrDesc(config->keyQDErrDesc.data(), config->keyQDErrDesc.length()),
        keyQDPayload(config->keyQDPayload.data(), config->keyQDPayload.length()),

        queryVisibleAll(config->queryVisibleAll),
        farm(itemDict, funnelDict)
    {
        if (!queryVisibleAll) {
            if (!config->queryVisibleFields.empty() &&
                !(config->queryVisibleFields.size() == 1 && *config->queryVisibleFields.begin() == "*")) {
                for (StringList::const_iterator it = config->queryVisibleFields.begin();
                    it != config->queryVisibleFields.end(); ++it) {
                    queryVisibleFields.insert(new Value(it->data(), it->length()));
                }
            }
            if (!config->queryInvisibleFields.empty()) {
                for (StringList::const_iterator it = config->queryInvisibleFields.begin();
                    it != config->queryInvisibleFields.end(); ++it) {
                    queryInvisibleFields.insert(new Value(it->data(), it->length()));
                }
            }
        }
    }
Exemplo n.º 18
0
void
Slice::ObjCGenerator::MetaDataVisitor::validate(const ContainedPtr& cont)
{
    ModulePtr m = ModulePtr::dynamicCast(cont);
    if(m)
    {
        bool error = false;
        bool foundPrefix = false;

        StringList meta = getMetaData(m);
        StringList::const_iterator p;

        for(p = meta.begin(); p != meta.end(); ++p)
        {
            const string prefix = "prefix:";
            string name;
            if(p->substr(_objcPrefix.size(), prefix.size()) == prefix)
            {
                foundPrefix = true;
                name = trim(p->substr(_objcPrefix.size() + prefix.size()));
                if(name.empty())
                {
                    if(_history.count(*p) == 0)
                    {
                        string file = m->definitionContext()->filename();
                        ostringstream os;
                        os << _msg << " `" << *p << "'" << endl;
                        emitWarning(file, m->line(), os.str());
                        _history.insert(*p);
                    }
                    error = true;
                }
                else
                {
                    if(!addModule(m, name))
                    {
                        modulePrefixError(m, *p);
                    }
                }
            }
            else
            {
                if(_history.count(*p) == 0)
                {
                    string file = m->definitionContext()->filename();
                    ostringstream os;
                    os << _msg << " `" << *p << "'" << endl;
                    emitWarning(file, m->line(), os.str());
                    _history.insert(*p);
                }
                error = true;
            }
        }

        if(!error && !foundPrefix)
        {
            StringList names = splitScopedName(m->scoped());
            string name;
            for(StringList::const_iterator i = names.begin(); i != names.end(); ++i)
            {
                name += *i;
            }
            if(!addModule(m, name))
            {
                modulePrefixError(m, "");
            }
        }
    }
}
Exemplo n.º 19
0
char OSISFootnotes::processText(SWBuf &text, const SWKey *key, const SWModule *module) {
	SWBuf token;
	bool intoken    = false;
	bool hide       = false;
	SWBuf tagText;
	XMLTag startTag;
	SWBuf refs = "";
	int footnoteNum = 1;
	char buf[254];
	SWKey *p = (module) ? module->createKey() : (key) ? key->clone() : new VerseKey();
        VerseKey *parser = SWDYNAMIC_CAST(VerseKey, p);
        if (!parser) {
        	delete p;
                parser = new VerseKey();
        }
        *parser = key->getText();

	SWBuf orig = text;
	const char *from = orig.c_str();

	XMLTag tag;
	bool strongsMarkup = false;


	for (text = ""; *from; ++from) {

		// remove all newlines temporarily to fix kjv2003 module
		if ((*from == 10) || (*from == 13)) {
			if ((text.length()>1) && (text[text.length()-2] != ' ') && (*(from+1) != ' '))
				text.append(' ');
			continue;
		}


		if (*from == '<') {
			intoken = true;
			token = "";
			continue;
		}



		if (*from == '>') {	// process tokens
			intoken = false;
			if (!strncmp(token, "note", 4) || !strncmp(token.c_str(), "/note", 5)) {
				tag = token;

				if (!tag.isEndTag()) {
					if (tag.getAttribute("type") && (!strcmp("x-strongsMarkup", tag.getAttribute("type"))
											|| !strcmp("strongsMarkup", tag.getAttribute("type")))	// deprecated
							) {
						tag.setEmpty(false);  // handle bug in KJV2003 module where some note open tags were <note ... />
						strongsMarkup = true;
					}

					if (!tag.isEmpty()) {
//					if ((!tag.isEmpty()) || (SWBuf("strongsMarkup") == tag.getAttribute("type"))) {
						refs = "";
						startTag = tag;
						hide = true;
						tagText = "";
						continue;
					}
				}
				if (hide && tag.isEndTag()) {
					if (module->isProcessEntryAttributes() && !strongsMarkup) { //don`t parse strongsMarkup to EntryAttributes as Footnote
						sprintf(buf, "%i", footnoteNum++);
						StringList attributes = startTag.getAttributeNames();
						for (StringList::const_iterator it = attributes.begin(); it != attributes.end(); it++) {
							module->getEntryAttributes()["Footnote"][buf][it->c_str()] = startTag.getAttribute(it->c_str());
						}
						module->getEntryAttributes()["Footnote"][buf]["body"] = tagText;
						startTag.setAttribute("swordFootnote", buf);
						if ((startTag.getAttribute("type")) && (!strcmp(startTag.getAttribute("type"), "crossReference"))) {
							if (!refs.length())
								refs = parser->parseVerseList(tagText.c_str(), *parser, true).getRangeText();
							module->getEntryAttributes()["Footnote"][buf]["refList"] = refs.c_str();
						}
					}
					hide = false;
					if (option || (startTag.getAttribute("type") && !strcmp(startTag.getAttribute("type"), "crossReference"))) {	// we want the tag in the text; crossReferences are handled by another filter
						text.append(startTag);
//						text.append(tagText);	// we don't put the body back in because it is retrievable from EntryAttributes["Footnotes"][]["body"].
					}
					else	continue;
				}
				strongsMarkup = false;
			}

			// if not a heading token, keep token in text
			//if ((!strcmp(tag.getName(), "reference")) && (!tag.isEndTag())) {
			//	SWBuf osisRef = tag.getAttribute("osisRef");
			if (!strncmp(token, "reference", 9)) {
				if (refs.length()) {
					refs.append("; ");
				}

				const char* attr = strstr(token.c_str() + 9, "osisRef=\"");
				const char* end  = attr ? strchr(attr+9, '"') : 0;

				if (attr && end) {
					refs.append(attr+9, end-(attr+9));
				}
			}
			if (!hide) {
				text.append('<');
				text.append(token);
				text.append('>');
			}
			else {
				tagText.append('<');
				tagText.append(token);
				tagText.append('>');
			}
			continue;
		}
		if (intoken) { //copy token
			token.append(*from);
		}
		else if (!hide) { //copy text which is not inside a token
			text.append(*from);
		}
		else tagText.append(*from);
	}
        delete parser;
	return 0;
}
	//------------------------------
	bool LibraryControllersLoader::begin__input____InputLocal( const input____InputLocal__AttributeData& attributeData )
	{
		// we ignore inputs that don't have semantics or source
		if ( !attributeData.semantic || !attributeData.source  )
		{
			return true;
		}

		ControllerInputSemantics semantic = getControllerInputSemanticsBySemanticStr( attributeData.semantic );
		if ( semantic == SEMANTIC_UNKNOWN )
		{
			return true;
		}

		switch ( mCurrentControllerType )
		{
		case SKIN_CONTROLLER:
			{
				switch ( semantic )
				{
				case SEMANTIC_JOINT:
					{
						if ( !mCurrentSkinControllerData )
						{
							break;
						}

						String sourceId = getIdFromURIFragmentType(attributeData.source);

						const StringList* nodeSidsOrIds = 0;
						bool isIdArray = false;
						StringListMap::const_iterator itSid = mJointSidsMap.find(sourceId);
						// check if the node sid array could be found
						if ( itSid != mJointSidsMap.end() )
						{
							nodeSidsOrIds = &itSid->second;
							isIdArray = false;
						}
						else
						{
							// check if it is an id_array
							StringListMap::const_iterator itId = mJointIdsMap.find(sourceId);
							if ( itId != mJointIdsMap.end() )
							{
								nodeSidsOrIds = &itId->second;
								isIdArray = true;
							}
							else
							{
								if ( !handleFWLError ( SaxFWLError::ERROR_SOURCE_NOT_FOUND, "Source with id \"" + sourceId + "\" in skin controller with  id \"" + mOriginalId + "\" used in input with semantic SEMANTIC_JOINT could not be found!" ))
									return false;
								break;
							}
						}

						const COLLADAFW::UniqueId& controllerUniqueId = mCurrentSkinControllerData->getUniqueId();
						addSkinDataJointSidsPair( controllerUniqueId, *nodeSidsOrIds, isIdArray);

						// try to write the SkinController here
						if ( ((getObjectFlags() & Loader::CONTROLLER_FLAG) != 0) && (mCurrentControllerSourceUniqueId.isValid()) )
						{
							Loader::InstanceControllerDataList& instanceControllerDataList = getInstanceControllerDataListByControllerUniqueId(controllerUniqueId);
							Loader::InstanceControllerDataList::iterator listIt = instanceControllerDataList.begin();

							while ( listIt != instanceControllerDataList.end() )
							{
								const Loader::InstanceControllerData& instanceControllerData = *listIt;
								bool success = getFileLoader()->createAndWriteSkinController( instanceControllerData, 
																					   		  controllerUniqueId, 
									                                                          mCurrentControllerSourceUniqueId,
									                                                          *nodeSidsOrIds,
																							  isIdArray);
								//on success we need to remove this controller instance
								if ( success )
								{
									listIt = instanceControllerDataList.erase( listIt );
								}
								else
								{
									listIt++;
								}
							}
						}
						mCurrentSkinControllerData->setJointsCount(nodeSidsOrIds->size());
					}
					break;
				case SEMANTIC_INV_BIND_MATRIX:
					{
						if ( !mCurrentSkinControllerData)
						{
							break;
						}

						String sourceId = getIdFromURIFragmentType(attributeData.source);
						SourceBase* sourceBase = getSourceById ( sourceId );

						if ( !sourceBase || (sourceBase->getDataType() != SourceBase::DATA_TYPE_REAL) )
						{
                            handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "SourceBase of skin controller with semantic SEMANTIC_INV_BIND_MATRIX not valid!" );
							break;
						}

						if ( sourceBase->getStride() != 16 )
						{
                            handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "Stride of sourceBase of skin controller with semantic SEMANTIC_INV_BIND_MATRIX not valid!" );
							break;
						}

						const RealSource *inverseBindMatricesSource = (const RealSource *)sourceBase;
						const RealArrayElement& inverseBindMatricesElement = inverseBindMatricesSource->getArrayElement();

						const RealArray& inverseBindMatricesArray = inverseBindMatricesElement.getValues();

						size_t matrixElementsCount = inverseBindMatricesArray.getCount();

						size_t matrixCount = matrixElementsCount / 16;


						COLLADAFW::Matrix4Array& inverseBindMatrices = mCurrentSkinControllerData->getInverseBindMatrices();
						inverseBindMatrices.allocMemory( matrixCount );
						inverseBindMatrices.setCount( matrixCount );

						size_t index = 0;
						for ( size_t i = 0; i < matrixCount; ++i)
						{
							// fill the matrix
							COLLADABU::Math::Matrix4 matrix;
							for ( size_t j = 0; j < 16; ++j,++index)
							{
								matrix.setElement( j, inverseBindMatricesArray[index]);
							}
							inverseBindMatrices[i] = matrix;
						}
					}
					break;
				}
			}
			break;
		case MORPH_CONTROLLER:
			{
				switch ( semantic )
				{
				case SEMANTIC_MORPH_TARGET:
					{
						if ( !mCurrentMorphController )
						{
							break;
						}

						String sourceId = getIdFromURIFragmentType(attributeData.source);
						StringListMap::const_iterator it = mJointIdsMap.find(sourceId);

						// check if the node sid array could be found
						if ( it == mJointIdsMap.end() )
						{
							if ( !handleFWLError ( SaxFWLError::ERROR_SOURCE_NOT_FOUND, "Source with id \"" + sourceId + "\" in morph controller with  id \"" + mOriginalId + "\" used in input with semantic SEMANTIC_MORPH_TARGET could not be found!" ))
								return false;
							break;
						}

						const StringList& meshIds = it->second;
						size_t meshIdCount = meshIds.size();

						COLLADAFW::UniqueIdArray& morphTargets = mCurrentMorphController->getMorphTargets();
						morphTargets.allocMemory(meshIdCount);
						morphTargets.setCount(meshIdCount);
						StringList::const_iterator itTarget = meshIds.begin();
						for ( size_t i = 0 ; itTarget != meshIds.end(); ++itTarget, ++i)
						{
							morphTargets[i] = createUniqueIdFromId( itTarget->c_str(), COLLADAFW::Geometry::ID());
						}

					}
					break;
				case SEMANTIC_MORPH_WEIGHT:
					{
						if ( !mCurrentMorphController)
						{
							break;
						}

						String sourceId = getIdFromURIFragmentType(attributeData.source);
						SourceBase* sourceBase = getSourceById( sourceId );

						if ( !sourceBase || (sourceBase->getDataType() != SourceBase::DATA_TYPE_REAL) )
						{
                            handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "SourceBase of skin controller with semantic SEMANTIC_MORPH_WEIGHT not valid!" );
							break;
						}


						unsigned long long stride = sourceBase->getStride();
						if( stride == 0 )
						{
							handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "Stride of sourceBase of skin controller with semantic SEMANTIC_MORPH_WEIGHT not found! Assuming stride 1!" );
							stride = 1;
						}
						if ( stride != 1 )
						{
                            handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "Stride of sourceBase of skin controller with semantic SEMANTIC_MORPH_WEIGHT not valid!" );
							break;
						}
						const RealSource *weightSource = (const RealSource *)sourceBase;
						COLLADAFW::FloatOrDoubleArray& morphWeights = mCurrentMorphController->getMorphWeights();
						addToSidTree( sourceId.c_str(), 0, &morphWeights );
						moveUpInSidTree();

						setRealValues( morphWeights, weightSource );
					}
					break;
				}
			}
			break;
		}

		return true;
	}
Exemplo n.º 21
0
ArgumentList ExtractArguments( const StringList& argv, argument_item_mode mode, ArgumentOptions options )
{
   bool noItems             = mode == ArgumentItemMode::NoItems;
   bool itemsAsFiles        = mode == ArgumentItemMode::AsFiles;
   bool itemsAsViews        = mode == ArgumentItemMode::AsViews;
   bool allowWildcards      = !noItems && options.IsFlagSet( ArgumentOption::AllowWildcards );
   bool noPreviews          = itemsAsViews && options.IsFlagSet( ArgumentOption::NoPreviews );
   bool recursiveDirSearch  = itemsAsFiles && allowWildcards && options.IsFlagSet( ArgumentOption::RecursiveDirSearch );
   bool recursiveSearchArgs = recursiveDirSearch && options.IsFlagSet( ArgumentOption::RecursiveSearchArgs );

   // This is the recursive search mode flag, controlled by --r[+|-]
   bool recursiveSearch = false;

   // The list of existing view identifiers, in case itemsAsViews = true.
   SortedStringList imageIds;

   // The list of extracted arguments
   ArgumentList arguments;

   for ( StringList::const_iterator i = argv.Begin(); i != argv.End(); ++i )
   {
      if ( i->StartsWith( '-' ) )
      {
         Argument arg( i->At( 1 ) );

         if ( recursiveSearchArgs && arg.Id() == s_recursiveSearchArg )
         {
            if ( arg.IsSwitch() )
               recursiveSearch = arg.SwitchState();
            else if ( arg.IsLiteral() )
               recursiveSearch = true;
            else
               arguments.Add( arg );
         }
         else
            arguments.Add( arg );
      }
      else
      {
         if ( noItems )
            throw ParseError( "Non-parametric arguments are not allowed", *i  );

         StringList items;

         if ( itemsAsFiles )
         {
            String fileName = *i;
            if ( fileName.StartsWith( '\"' ) )
               fileName.Delete( 0 );
            if ( fileName.EndsWith( '\"' ) )
               fileName.Delete( fileName.UpperBound() );

            fileName.Trim();
            if ( fileName.IsEmpty() )
               throw ParseError( "Empty path specification", *i );

            fileName = File::FullPath( fileName );

            if ( fileName.HasWildcards() )
            {
               if ( !allowWildcards )
                  throw ParseError( "Wildcards not allowed", fileName );

               items = SearchDirectory( fileName, recursiveSearch );
            }
            else
               items.Add( fileName );
         }
         else if ( itemsAsViews )
         {
            String viewId = *i;

            if ( !allowWildcards )
               if ( viewId.HasWildcards() )
                  throw ParseError( "Wildcards not allowed", viewId );

            size_type p = viewId.Find( "->" );

            if ( p != String::notFound )
            {
               if ( noPreviews )
                  throw ParseError( "Preview identifiers not allowed", viewId );

               String imageId = viewId.Left( p );
               if ( imageId.IsEmpty() )
                  throw ParseError( "Missing image identifier", viewId );

               String previewId = viewId.Substring( p+2 );
               if ( previewId.IsEmpty() )
                  throw ParseError( "Missing preview identifier", viewId );

               FindPreviews( items, imageId, previewId );
            }
            else
            {
               if ( viewId.HasWildcards() )
               {
                  Array<ImageWindow> W = ImageWindow::AllWindows();
                  for ( size_type i = 0; i < W.Length(); ++i )
                  {
                     View v = W[i].MainView();
                     if ( String( v.Id() ).WildMatch( viewId ) )
                        AddView( items, v );
                  }
               }
               else
               {
                  ImageWindow w = ImageWindow::WindowById( IsoString( viewId ) );
                  if ( w.IsNull() )
                     throw ParseError( "Image not found", viewId );
                  AddView( items, w.MainView() );
               }
            }
         }
         else
            items.Add( *i );

         Argument arg( *i, items );
         arguments.Add( arg );
      }
   }

   return arguments;
}
Exemplo n.º 22
0
bool OSISHeadings::handleToken(SWBuf &buf, const char *token, BasicFilterUserData *userData) {

	MyUserData *u = (MyUserData *)userData;
	XMLTag tag(token);
	SWBuf name = tag.getName();

	// we only care about titles and divs or if we're already in a heading
	//
	// are we currently in a heading?
	if (u->currentHeadingName.size()) {
		u->heading.append(u->lastTextNode);
		if (name == u->currentHeadingName) {
			if (tag.isEndTag(u->sID)) {
				if (!u->depth-- || u->sID) {
					// see comment below about preverse div changed and needing to preserve the <title> container tag for old school pre-verse titles
					// we've just finished a heading.  It's all stored up in u->heading
					bool canonical = (SWBuf("true") == u->currentHeadingTag.getAttribute("canonical"));
					bool preverse = (SWBuf("x-preverse") == u->currentHeadingTag.getAttribute("subType") || SWBuf("x-preverse") == u->currentHeadingTag.getAttribute("subtype"));

					// do we want to put anything in EntryAttributes?
					if (u->module->isProcessEntryAttributes() && (option || canonical || !preverse)) {
						SWBuf buf; buf.appendFormatted("%i", u->headerNum++);
						// leave the actual <title...> wrapper in if we're part of an old school preverse title
						// because now frontend have to deal with preverse as a div which may or may not include <title> elements
						// and they can't simply wrap all preverse material in <h1>, like they probably did previously
						SWBuf heading;
						if (u->currentHeadingName == "title") {
							XMLTag wrapper = u->currentHeadingTag;
							if (SWBuf("x-preverse") == wrapper.getAttribute("subType")) wrapper.setAttribute("subType", 0);
							else if (SWBuf("x-preverse") == wrapper.getAttribute("subtype")) wrapper.setAttribute("subtype", 0);
							heading = wrapper;
							heading += u->heading;
							heading += tag;
						}
						else heading = u->heading;
						u->module->getEntryAttributes()["Heading"][(preverse)?"Preverse":"Interverse"][buf] = heading;

						StringList attributes = u->currentHeadingTag.getAttributeNames();
						for (StringList::const_iterator it = attributes.begin(); it != attributes.end(); it++) {
							u->module->getEntryAttributes()["Heading"][buf][it->c_str()] = u->currentHeadingTag.getAttribute(it->c_str());
						}
					}

					// do we want the heading in the body?
					if (!preverse && (option || canonical)) {
						buf.append(u->currentHeadingTag);
						buf.append(u->heading);
						buf.append(tag);
					}
					u->suspendTextPassThru = false;
					u->clear();
				}
			}
			else u->depth++;
		}
		u->heading.append(tag);
		return true;
	}

	// are we a title or a preverse div?
	else if (   name == "title"
		|| (name == "div"
			&& ( SWBuf("x-preverse") == tag.getAttribute("subType")
			  || SWBuf("x-preverse") == tag.getAttribute("subtype")))) {

		u->currentHeadingName = name;
		u->currentHeadingTag = tag;
		u->heading = "";
		u->sID = u->currentHeadingTag.getAttribute("sID");
		u->depth = 0;
		u->suspendTextPassThru = true;

		return true;
	}

	return false;
}
Exemplo n.º 23
0
bool ListWidget::handleKeyDown(Common::KeyState state) {
	bool handled = true;
	bool dirty = false;
	int oldSelectedItem = _selectedItem;

	if (!_editMode && isprint((char)state.ascii)) {
		// Quick selection mode: Go to first list item starting with this key
		// (or a substring accumulated from the last couple key presses).
		// Only works in a useful fashion if the list entries are sorted.
		uint32 time = getMillis();
		if (_quickSelectTime < time) {
			_quickSelectStr = (char)state.ascii;
		} else {
			_quickSelectStr += (char)state.ascii;
		}
		_quickSelectTime = time + 300;	// TODO: Turn this into a proper constant (kQuickSelectDelay ?)

		if (_quickSelect) {
			// FIXME: This is bad slow code (it scans the list linearly each time a
			// key is pressed); it could be much faster. Only of importance if we have
			// quite big lists to deal with -- so for now we can live with this lazy
			// implementation :-)
			int newSelectedItem = 0;
			int bestMatch = 0;
			bool stop;
			for (StringList::const_iterator i = _list.begin(); i != _list.end(); ++i) {
				const int match = matchingCharsIgnoringCase(i->c_str(), _quickSelectStr.c_str(), stop);
				if (match > bestMatch || stop) {
					_selectedItem = newSelectedItem;
					bestMatch = match;
					if (stop)
						break;
				}
				newSelectedItem++;
			}

			scrollToCurrent();
		} else {
			sendCommand(_cmd, 0);
		}
	} else if (_editMode) {
		// Class EditableWidget handles all text editing related key presses for us
		handled = EditableWidget::handleKeyDown(state);
	} else {
		// not editmode

		switch (state.keycode) {
		case Common::KEYCODE_RETURN:
		case Common::KEYCODE_KP_ENTER:
			if (_selectedItem >= 0) {
				// override continuous enter keydown
				if (_editable && (_currentKeyDown != Common::KEYCODE_RETURN && _currentKeyDown != Common::KEYCODE_KP_ENTER)) {
					dirty = true;
					startEditMode();
				} else
					sendCommand(kListItemActivatedCmd, _selectedItem);
			}
			break;
		case Common::KEYCODE_BACKSPACE:
		case Common::KEYCODE_KP_PERIOD:
		case Common::KEYCODE_DELETE:
			if (_selectedItem >= 0) {
				if (_editable) {
					// Ignore delete and backspace when the list item is editable
				} else {
					sendCommand(kListItemRemovalRequestCmd, _selectedItem);
				}
			}
			break;
		case Common::KEYCODE_UP:
			if (_selectedItem > 0)
				_selectedItem--;
			break;
		case Common::KEYCODE_DOWN:
			if (_selectedItem < (int)_list.size() - 1)
				_selectedItem++;
			break;
		case Common::KEYCODE_PAGEUP:
			_selectedItem -= _entriesPerPage - 1;
			if (_selectedItem < 0)
				_selectedItem = 0;
			break;
		case Common::KEYCODE_PAGEDOWN:
			_selectedItem += _entriesPerPage - 1;
			if (_selectedItem >= (int)_list.size() )
				_selectedItem = _list.size() - 1;
			break;
		case Common::KEYCODE_HOME:
			_selectedItem = 0;
			break;
		case Common::KEYCODE_END:
			_selectedItem = _list.size() - 1;
			break;
		default:
			handled = false;
		}

		scrollToCurrent();
	}

	if (dirty || _selectedItem != oldSelectedItem)
		draw();

	if (_selectedItem != oldSelectedItem) {
		sendCommand(kListSelectionChangedCmd, _selectedItem);
		// also draw scrollbar
		_scrollBar->draw();
	}

#if !defined(PALMOS_MODE)
	// not done on PalmOS because keyboard is emulated and keyup is not generated
	_currentKeyDown = state.keycode;
#endif

	return handled;
}
Exemplo n.º 24
0
Plugin::List Plugin::scan( TPContext * context , const String & prefix , const StringList & symbols )
{
	Plugin::List result;

    if ( ! g_module_supported() )
    {
        tpwarn( "PLUGINS ARE NOT SUPPORTED ON THIS PLATFORM" );

        return result;
    }

    const gchar * plugins_path = context->get( TP_PLUGINS_PATH );

    if ( ! plugins_path )
    {
        tpwarn( "PLUGINS PATH IS NOT SET" );

        return result;
    }

    if ( ! g_file_test( plugins_path , G_FILE_TEST_IS_DIR ) )
    {
    	return result;
    }

    GError * error = 0;

    GDir * dir = g_dir_open( plugins_path , 0 , & error );

    if ( ! dir )
    {
        tpwarn( "FAILED TO OPEN PLUGINS PATH '%s' : %s" , plugins_path , error->message );

        g_clear_error( & error );

        return result;
    }

    for ( const gchar * name = g_dir_read_name( dir ); name ; name = g_dir_read_name( dir ) )
    {
        if ( g_str_has_prefix( name , prefix.c_str() ) )
        {
            if ( ! g_str_has_suffix( name , ".config" ) )
            {
                gchar * file_name = g_build_filename( plugins_path , name , NULL );

                tplog( "FOUND PLUGIN %s" , file_name );

                GModule * module = g_module_open( file_name , G_MODULE_BIND_LOCAL );

                if ( 0 == module )
                {
                	tpwarn( "  FAILED TO OPEN : %s" , g_module_error() );
                }
                else
                {
                	tplog2( "  LOADED" );

                	StringList all_symbols( symbols );

                	all_symbols.push_front( TP_PLUGIN_SHUTDOWN );
                	all_symbols.push_front( TP_PLUGIN_INITIALIZE );

                	GPointerMap symbols_found;

                	for ( StringList::const_iterator it = all_symbols.begin(); it != all_symbols.end(); ++it )
                	{
                		const char * symbol_name = it->c_str();

                		if ( gpointer symbol = get_symbol( module , symbol_name ) )
                		{
                    		tplog2( "  FOUND SYMBOL '%s'" , symbol_name );
                    		symbols_found[ symbol_name ] = symbol;
                		}
                		else
                		{
                			break;
                		}
                	}

                	if ( symbols_found.size() != all_symbols.size() )
                	{
                		g_module_close( module );
                	}
                	else
                	{
                		result.push_back( new Plugin( module , symbols_found ) );
                	}
                }

                g_free( file_name );
            }
        }
    }

    g_dir_close( dir );

    return result;
}
Exemplo n.º 25
0
    virtual void Execute(const std::string& sExecute, const StringList& rlsParams)
    {
      STAFF_ASSERT(m_pProvider != NULL && m_pProvider->m_pImpl->m_pConn != NULL, "Not Initialized");

      Reset();

      std::string sExecuteParams = sExecute;
      int nIndex = 1;
      std::string sIndex;
      unsigned nCount = 0;
      std::string::size_type nPos = 0;
      while ((nPos = sExecuteParams.find("?", nPos)) != std::string::npos)
      {
        ToString(nIndex, sIndex);
        sExecuteParams.replace(nPos, 1, "$" + sIndex);
        nPos += sIndex.size() + 1;
        ++nCount;
        ++nIndex;
      }

      STAFF_ASSERT(nCount == rlsParams.size(), "Params count mismatch");

      int* panParamLengths = new int[nCount];
      int* panParamFormats = new int[nCount];
      char** paszParamValues = new char*[nCount];

      try
      {
        unsigned nPos = 0;
        for (StringList::const_iterator itParam = rlsParams.begin();
             itParam != rlsParams.end(); ++itParam, ++nPos)
        {
          panParamFormats[nPos] = 0;
          if (*itParam == STAFF_DAS_NULL_VALUE)
          {
            panParamLengths[nPos] = 0;
            paszParamValues[nPos] = NULL;
          }
          else
          {
            panParamLengths[nPos] = itParam->size();
            paszParamValues[nPos] = const_cast<char*>(itParam->c_str());
          }
        }

        m_pResult = PQexecParams(m_pProvider->m_pImpl->m_pConn,
          sExecuteParams.c_str(), nCount, NULL, paszParamValues, panParamLengths, panParamFormats, 0);

        delete[] paszParamValues;
        delete[] panParamFormats;
        delete[] panParamLengths;
      }
      catch(...)
      {
        delete[] paszParamValues;
        delete[] panParamFormats;
        delete[] panParamLengths;
        throw;
      }

      ExecStatusType tQueryStatus = PQresultStatus(m_pResult);
      if (tQueryStatus != PGRES_COMMAND_OK)
      {
        STAFF_ASSERT(tQueryStatus == PGRES_TUPLES_OK, "error executing query #"
                     + ToString(tQueryStatus) + ": \n"
                     + std::string(PQerrorMessage(m_pProvider->m_pImpl->m_pConn))
                     + "\nQuery was:\n----------\n" + sExecute + "\n----------\n");

        m_nRowsCount = static_cast<unsigned>(PQntuples(m_pResult));
        m_nFieldsCount = static_cast<unsigned>(PQnfields(m_pResult));
      }
    }
STDMETHODIMP CShooterContextMenuExt::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo )
{
	// If lpVerb really points to a string, ignore this function call and bail out.
	if ( 0 != HIWORD( pCmdInfo->lpVerb ) )
		return E_INVALIDARG;

	// Get the command index - the only valid one is 0.
	switch ( LOWORD( pCmdInfo->lpVerb) )
	{
	case 0:
	case 1:
		{
			TCHAR szShooterDir[MAX_PATH];
			TCHAR szShooterDldrPath[MAX_PATH];

			//Build the ShooterDownloader's file path from this module's path.
			//Limitation: ShooterDownloader must locate in the same dir as this module.
			HINSTANCE hModule = _AtlBaseModule.GetModuleInstance();
			GetModuleFileName((HMODULE) hModule, szShooterDir, sizeof(szShooterDir));
			TCHAR* pLastSlash = _tcsrchr(szShooterDir, _T('\\'));
			*(pLastSlash + 1) = _T('\0');
			_tcscpy_s(szShooterDldrPath, szShooterDir);
			_tcscat_s(szShooterDldrPath, SHOOTER_DLDR_FILE_NAME);

			TCHAR szTempDir[MAX_PATH], szTempFilePath[MAX_PATH];
			// Get the temp path.
			DWORD dwRetVal = GetTempPath(MAX_PATH,     // length of the buffer
				szTempDir); // buffer for path 
			if (dwRetVal > MAX_PATH || (dwRetVal == 0))
			{
				return E_FAIL;
			}

			// Create a temporary file. 
			UINT uRetVal = GetTempFileName(szTempDir, // directory for tmp files
				TEXT("SDL"),  // temp file name prefix 
				0,            // create unique name 
				szTempFilePath);  // buffer for name 
			if (uRetVal == 0)
			{
				return E_FAIL;
			}

			//Write file list to a temp file.
			FILE* fp; 
			errno_t ret = _tfopen_s(&fp, szTempFilePath, _T("w, ccs=UTF-8"));
			if(ret != 0)
			{
				return E_FAIL;
			}
			
			StringList::const_iterator itor;
			for(itor = m_fileList.begin(); itor != m_fileList.end(); itor++)
			{
				_ftprintf_s(fp, _T("%s\n"), itor->c_str());
			}
			fclose(fp);

			//Call ShooterDownloader and pass it the file list.
			const static int PARAM_SIZE = 512;
			TCHAR param[PARAM_SIZE];
			if(LOWORD( pCmdInfo->lpVerb) == 0)
			{
				//download subtitle
				_stprintf_s(param, PARAM_SIZE, _T("-lst=\"%s\" /r"), szTempFilePath);
			}
			else
			{
				//convert subtitle
				_stprintf_s(param, PARAM_SIZE, _T("-lst=\"%s\" /r /c"), szTempFilePath);
			}

			ShellExecute(NULL, _T("Open"), szShooterDldrPath, param, NULL, SW_SHOWNORMAL);

			return S_OK;
		}
		break;

	default:
		return E_INVALIDARG;
		break;
	}
}
Exemplo n.º 27
0
const string LdapTools::nextSpicePort(const Node* node) {
	int port = 0;
	int portMin = Config::getInstance()->getSpicePortMin();
	int portMax = Config::getInstance()->getSpicePortMax();
	int size = portMax - portMin + 1;
	//bool* portsUsed = new bool[size];
	bool* portsUsed = (bool *) malloc(size * sizeof(bool));
	for (int i = 0; i < size; i++) {
		portsUsed[i] = false;
	}
	string base("ou=virtual machines,ou=virtualization,ou=services,");
	base.append(Config::getInstance()->getLdapBaseDn());
//	string filter = "(&(objectClass=sstSpice))";
	string filter = "(&(objectClass=sstSpice)(sstNode=";
	filter.append(node->getName()).append("))");
	StringList attrs = StringList();
	attrs.add("sstVirtualMachine");
	attrs.add("sstSpicePort");
	LDAPSearchResults* entries = lc->search(base, LDAPConnection::SEARCH_SUB, filter, attrs);
	LDAPEntry* entry = entries->getNext();
	while (entry != 0) {
		string vmName = "";
		const LDAPAttribute* attribute = entry->getAttributeByName("sstVirtualMachine");
		const StringList values = attribute->getValues();
		StringList::const_iterator it = values.begin();
		if (it != values.end()) {
			vmName = it->c_str();
		}
		const LDAPAttribute* attribute2 = entry->getAttributeByName("sstSpicePort");
		const StringList values2 = attribute2->getValues();
		StringList::const_iterator it2 = values2.begin();
		if (it2 != values2.end()) {
			port = atoi(it2->c_str());
			SYSLOGLOGGER(logDEBUG) << "  " << port << " in use " << port - portMin << " (" << vmName << ")";
			portsUsed[port - portMin] = true;
		}
		delete entry;
		entry = entries->getNext();
	}

	filter = "(&(objectClass=sstSpice)(sstMigrationNode=";
	filter.append(node->getName()).append("))");
	attrs = StringList();
	attrs.add("sstMigrationSpicePort");
	entries = lc->search(base, LDAPConnection::SEARCH_SUB, filter, attrs);
	entry = entries->getNext();
	while (entry != 0) {
		const LDAPAttribute* attribute = entry->getAttributeByName("sstMigrationSpicePort");
		const StringList values = attribute->getValues();
		StringList::const_iterator it = values.begin();
		if (it != values.end()) {
			port = atoi(it->c_str());
			SYSLOGLOGGER(logDEBUG) << "M " << port << " in use " << port - portMin;
			portsUsed[port - portMin] = true;
		}
		delete entry;
		entry = entries->getNext();
	}

	port = 0;
	for (int i = 0; i < size; i++) {
		if (!portsUsed[i]) {
			port = portMin + i;
			break;
		}
	}

	//delete[] portsUsed;
	free(portsUsed);

	SYSLOGLOGGER(logDEBUG) << "nextSpicePort: " << base << "; " << filter << "; port: " << port;
	char buffer[10];
	sprintf(buffer, "%d", port);
	return string(buffer);
}
Exemplo n.º 28
0
char ThMLHeadings::processText(SWBuf &text, const SWKey *key, const SWModule *module) {
	SWBuf token;
	bool intoken    = false;
	bool isheader   = false;
	bool hide       = false;
	bool preverse   = false;
	bool withinDiv  = false;
	SWBuf header;
	int headerNum   = 0;
	int pvHeaderNum = 0;
	char buf[254];
	XMLTag startTag;

	SWBuf orig = text;
	const char *from = orig.c_str();
	
	XMLTag tag;

	for (text = ""; *from; ++from) {
		if (*from == '<') {
			intoken = true;
			token = "";
			
			continue;
		}
		if (*from == '>') {	// process tokens
			intoken = false;

			if (!strnicmp(token.c_str(), "div", 3) || !strnicmp(token.c_str(), "/div", 4)) {
				withinDiv =  (!strnicmp(token.c_str(), "div", 3));
				tag = token;
				if (hide && tag.isEndTag()) {
					if (module->isProcessEntryAttributes() && (option || (!preverse))) {
						if (preverse) {
							sprintf(buf, "%i", pvHeaderNum++);
							module->getEntryAttributes()["Heading"]["Preverse"][buf] = header;
						}
						else {
							sprintf(buf, "%i", headerNum++);
							module->getEntryAttributes()["Heading"]["Interverse"][buf] = header;
							if (option) {	// we want the tag in the text
								text.append(header);
							}
						}
						
						StringList attributes = startTag.getAttributeNames();
						for (StringList::const_iterator it = attributes.begin(); it != attributes.end(); it++) {
							module->getEntryAttributes()["Heading"][buf][it->c_str()] = startTag.getAttribute(it->c_str());
						}
					}
					
					hide = false;
					if (!option || preverse) {	// we don't want the tag in the text anymore
						preverse = false;
						continue;
					}
					preverse = false;
				}
				if (tag.getAttribute("class") && ((!stricmp(tag.getAttribute("class"), "sechead"))
										 ||  (!stricmp(tag.getAttribute("class"), "title")))) {

					isheader = true;
					
					if (!tag.isEndTag()) { //start tag
						if (!tag.isEmpty()) {
							startTag = tag;
					
/* how do we tell a ThML preverse title from one that should be in the text?  probably if any text is before the title...  just assuming all are preverse for now
					}
					if (tag.getAttribute("subtype") && !stricmp(tag.getAttribute("subtype"), "x-preverse")) {
*/
						hide = true;
						preverse = true;
						header = "";
						continue;
						}	// move back up under startTag = tag
					}
/* this is where non-preverse will go eventually
					if (!tag.isEndTag()) { //start tag
						hide = true;
						header = "";
						if (option) {	// we want the tag in the text
							text.append('<');
							text.append(token);
							text.append('>');
						}
						continue;
					}
*/
				}
				else
					isheader = false;
			}

			if (withinDiv && isheader) {
				header.append('<');
				header.append(token);
				header.append('>');
			} else {
				// if not a heading token, keep token in text
				if (!hide) {
					text.append('<');
					text.append(token);
					text.append('>');
				}
			}
			continue;
		}
		if (intoken) { //copy token
			token.append(*from);
		}
		else if (!hide) { //copy text which is not inside a token
			text.append(*from);
		}
		else header.append(*from);
	}
	return 0;
}