bool getNthToken (const String & str, const size_t n, size_t & pos, size_t & endpos, String & token, const unicode_char_t * sepChars)
	{
		size_t desired_first_nonspace = 0;
		size_t space = 0;

		//check for trivial case
		if(n == 0)
			desired_first_nonspace = pos;
		else
		{
			for (size_t i = 0; i < n; ++i)
			{
				//find the first whitespace character
				space = str.find_first_of ( sepChars, pos );
				if (space == std::string::npos)
					return false;
				//now find the next non-whitespace character after it
				desired_first_nonspace = str.find_first_not_of( sepChars, space );
				if (desired_first_nonspace == std::string::npos)
					return false;
				pos = desired_first_nonspace;
			}
		}
		//find the end of the token
		const size_t first_space    = str.find_first_of   (sepChars, desired_first_nonspace );
		//now get that token
		if (first_space != std::string::npos)
			token = str.substr (desired_first_nonspace, first_space - desired_first_nonspace);
		else
			token = str.substr (desired_first_nonspace);

		endpos = desired_first_nonspace;

		return true;
	}
Example #2
0
void Wikidiff2::printText(const String & input)
{
	size_t start = 0;
	size_t end = input.find_first_of("<>&");
	while (end != String::npos) {
		if (end > start) {
			result.append(input, start, end - start);
		}
		switch (input[end]) {
			case '<':
				result.append("&lt;");
				break;
			case '>':
				result.append("&gt;");
				break;
			default /*case '&'*/:
				result.append("&amp;");
		}
		start = end + 1;
		end = input.find_first_of("<>&", start);
	}
	// Append the rest of the string after the last special character
	if (start < input.size()) {
		result.append(input, start, input.size() - start);
	}
}
Example #3
0
 /*
   ('a', 0) => 'a'
   ('a', 1) => 'a'
   ('a/b', 0) => 'a'
   ('a/b', 1) => 'b'
 */
 String ExtractMergedValue(const String& val) const
 {
   const String::size_type pos = val.find_first_of('/');
   if (pos != String::npos)
   {
     Require(String::npos == val.find_first_of('/', pos + 1));
     return Index == 0 ? val.substr(0, pos) : val.substr(pos + 1);
   }
   else
   {
     return val;
   }
 }
Example #4
0
void SCsTranslator::processSentenceLevel1(pANTLR3_BASE_TREE node)
{
    unsigned int nodesCount = node->getChildCount(node);
    assert(nodesCount == 3);

    pANTLR3_BASE_TREE node_obj = (pANTLR3_BASE_TREE)node->getChild(node, 0);
    pANTLR3_BASE_TREE node_pred = (pANTLR3_BASE_TREE)node->getChild(node, 1);
    pANTLR3_BASE_TREE node_subj = (pANTLR3_BASE_TREE)node->getChild(node, 2);

    pANTLR3_COMMON_TOKEN tok_pred = node_pred->getToken(node_pred);

    if (tok_pred->type != ID_SYSTEM)
    {
        THROW_EXCEPT(Exception::ERR_PARSE,
                     String("Invalid predicate '") + ((const char*) node_pred->getText(node_pred)->chars) + "' in simple sentence",
                     mParams.fileName,
                     tok_pred->getLine(tok_pred));
    }

    sElement *el_obj = parseElementTree(node_obj);
    sElement *el_subj = parseElementTree(node_subj);

    // determine arc type
    sc_type type = sc_type_edge_common;
    String pred = GET_NODE_TEXT(node_pred);
    size_t n = pred.find_first_of("#");
    if (n != pred.npos)
        type = _getArcPreffixType(pred.substr(0, n));

    _addEdge(el_obj, el_subj, type, false, pred);
}
Example #5
0
    //-----------------------------------------------------------------------
    StringVector StringUtil::split( const String& str, const String& delims, unsigned int maxSplits, bool preserveDelims)
    {
        StringVector ret;
        // Pre-allocate some space for performance
        ret.reserve(maxSplits ? maxSplits+1 : 10);    // 10 is guessed capacity for most case

        unsigned int numSplits = 0;

        // Use STL methods
        size_t start, pos;
        start = 0;
        do
        {
            pos = str.find_first_of(delims, start);
            if (pos == start)
            {
                // Do nothing
                start = pos + 1;
            }
            else if (pos == String::npos || (maxSplits && numSplits == maxSplits))
            {
                // Copy the rest of the string
                ret.push_back( str.substr(start) );
                break;
            }
            else
            {
                // Copy up to delimiter
                ret.push_back( str.substr(start, pos - start) );

                if(preserveDelims)
                {
                    // Sometimes there could be more than one delimiter in a row.
                    // Loop until we don't find any more delims
                    size_t delimStart = pos, delimPos;
                    delimPos = str.find_first_not_of(delims, delimStart);
                    if (delimPos == String::npos)
                    {
                        // Copy the rest of the string
                        ret.push_back( str.substr(delimStart) );
                    }
                    else
                    {
                        ret.push_back( str.substr(delimStart, delimPos - delimStart) );
                    }
                }

                start = pos + 1;
            }
            // parse up to next real data
            start = str.find_first_not_of(delims, start);
            ++numSplits;

        } while (pos != String::npos);



        return ret;
    }
Example #6
0
ui32 Tokenizer::tokenize( const String& str, TArray<String>& tokens, const String& delimiters ) {
    // Skip delimiters at beginning.
    String::size_type lastPos = str.find_first_not_of( delimiters, 0 );
    
    // find first "non-delimiter".
    String::size_type pos = str.find_first_of( delimiters, lastPos );
    while( String::npos != pos || String::npos != lastPos ) {
        // Found a token, add it to the vector.
        String tmp = str.substr( lastPos, pos - lastPos );
        if ( !tmp.empty() && ' ' != tmp[ 0 ] ) {
            tokens.add( tmp );
        }
        
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of( delimiters, pos );
        
        // Find next "non-delimiter"
        pos = str.find_first_of( delimiters, lastPos );
    }

    return static_cast<ui32>( tokens.size() );
}
String
MSWindowsClipboardHTMLConverter::findArg(
                const String& data, const String& name) const
{
    String::size_type i = data.find(name);
    if (i == String::npos) {
        return String();
    }
    i = data.find_first_of(":\r\n", i);
    if (i == String::npos || data[i] != ':') {
        return String();
    }
    i = data.find_first_of("0123456789\r\n", i + 1);
    if (i == String::npos || data[i] == '\r' || data[i] == '\n') {
        return String();
    }
    String::size_type j = data.find_first_not_of("0123456789", i);
    if (j == String::npos) {
        j = data.size();
    }
    return data.substr(i, j - i);
}
Example #8
0
    //--------------------------------
    void Utils::split ( const String& text, const String& separators, std::vector<String>& words )
    {
        size_t n = text.length();
        size_t start, stop;

        start = text.find_first_not_of(separators);
        while (start < n)
        {
            stop = text.find_first_of(separators, start);
            if (stop > n) stop = n;
            words.push_back(text.substr(start, stop - start));
            start = text.find_first_not_of(separators, stop+1);
        }
    }
//----------------------------------------------------------------------------//
size_t RenderedStringTextComponent::getNextTokenLength(const String& text,
                                                       size_t start_idx)
{
    String::size_type word_start =
        text.find_first_not_of(TextUtils::DefaultWrapDelimiters, start_idx);

    if (word_start == String::npos)
        word_start = start_idx;

    String::size_type word_end =
        text.find_first_of(TextUtils::DefaultWrapDelimiters, word_start);

    if (word_end == String::npos)
        word_end = text.length();

    return word_end - start_idx;
}
	bool getFirstToken (const String & str, size_t pos, size_t & endpos, String & token, const unicode_char_t * sepChars)
	{
		const size_t first_nonspace = str.find_first_not_of ( sepChars, pos );

		if (first_nonspace != std::string::npos)
		{
			const size_t first_space    = str.find_first_of   (sepChars, first_nonspace );

			if (first_space != std::string::npos)
				token = str.substr (first_nonspace, first_space - first_nonspace);
			else
				token = str.substr (first_nonspace);

			endpos = first_space;
			return true;
		}

		return false;
	}
Example #11
0
void Dtime::Time_Label (string label, Units_Type time_format)
{
	String time;

	if (time_format == NO_UNITS) time_format = Time_Format ();

	dtime = 0;
	time = label;
	time.Trim (" \t");

	if (time.empty ()) {
		exe->Warning ("Time Label Conversion ");
		return;
	}
	if (time.find_first_of (".:") == time.npos) {
		size_t len = time.length ();
			
		//---- scan for clock time ----

		if (len >= 3 && len <= 4) {
			bool flag = false;

			if (time [0] == '0') {
				flag = true;
			} else if (len == 4) {
				if (time [0] <= '2' && time [2] <= '5') {
					flag = true;
				}
			} else if (time [1] <= '5') {
				flag = true;
			}
			if (flag) {
				if (len == 4) {
					time.insert (2, ":");
				} else {
					time.insert (1, ":");
				}
			}
		}
	}
	Time_String (time, time_format);
	return;
}
Example #12
0
	StringVector StringUtil::split(const String& str, const String& delims, uint32_t maxSplits, BOOL preserveDelims)
	{
		StringVector ret;
		ret.reserve(maxSplits ? maxSplits + 1 : 10);
		uint32_t numSplits = 0;

		size_t start, pos;
		start = 0;
		do 
		{
			pos = str.find_first_of(delims, start);
			if (pos == start)
			{
				start = pos + 1;
			}
			else if (pos == String::npos || (maxSplits && numSplits == maxSplits))
			{
				ret.push_back(str.substr(start));
				break;
			}
			else
			{
				ret.push_back(str.substr(start, pos - start));
				if (preserveDelims)
				{
					size_t delimStart = pos, delimPos;
					delimPos = str.find_first_not_of(delims, delimStart);
					if (delimPos == String::npos)
					{
						ret.push_back(str.substr(delimStart));
					}
					else
					{
						ret.push_back(str.substr(delimStart, delimPos - delimStart));
					}
				}
				start = pos + 1;
			}
			start = str.find_first_not_of(delims, start);
			++numSplits;
		} while (pos != String::npos);
		return ret;
	}
    void GLSLESProgramManagerCommon::optimiseShaderSource(GLSLESGpuProgram* gpuProgram)
    {
        if(!gpuProgram->getGLSLProgram()->getIsOptimised())
        {
            GpuProgramType gpuType = gpuProgram->getType();
            const glslopt_shader_type shaderType = (gpuType == GPT_VERTEX_PROGRAM) ? kGlslOptShaderVertex : kGlslOptShaderFragment;
            String shaderSource = gpuProgram->getGLSLProgram()->getSource();
            glslopt_shader* shader = glslopt_optimize(mGLSLOptimiserContext, shaderType, shaderSource.c_str(), 0);

            std::stringstream os;
            if(glslopt_get_status(shader))
            {
                // Write the current version (this forces the driver to fulfill the glsl es standard)
                // TODO: Need to insert the current or compatibility version.  This is not future-proof
                os << "#version 100" << std::endl;

                // Default precision declaration is required in fragment and vertex shaders.
                os << "precision highp float;" << std::endl;
                os << "precision highp int;" << std::endl;
                String source = const_cast<char *>(glslopt_get_output(shader));

                // We want to make sure that there are precision qualifiers so strip out the first line
                // which is the version string. We don't want duplicates since we are adding our own.
                size_t pos = source.find_first_of("\n");
                os << source.substr(pos+1, source.length()-1);

                gpuProgram->getGLSLProgram()->setOptimisedSource(os.str());
                gpuProgram->getGLSLProgram()->setIsOptimised(true);
            }
            else
            {
                LogManager::getSingleton().logMessage("Error from GLSL Optimiser, disabling optimisation for program: " + gpuProgram->getName());
                gpuProgram->getGLSLProgram()->setParameter("use_optimiser", "false");
//                LogManager::getSingleton().logMessage(String(glslopt_get_log(shader)));
//                LogManager::getSingleton().logMessage("Original Shader");
//                LogManager::getSingleton().logMessage(gpuProgram->getGLSLProgram()->getSource());
//                LogManager::getSingleton().logMessage("Optimized Shader");
//                LogManager::getSingleton().logMessage(os.str());
            }
            glslopt_shader_delete(shader);
        }
    }
Example #14
0
void MultipleChoiceValue::normalForm() {
	String val = value->toString();
	// which choices are active?
	vector<bool> seen(field().choices->lastId());
	for (size_t pos = 0 ; pos < val.size() ; ) {
		if (val.GetChar(pos) == _(' ')) {
			++pos; // ingore whitespace
		} else {
			// does this choice match the one asked about?
			size_t end = val.find_first_of(_(','), pos);
			if (end == String::npos) end = val.size();
			// find this choice
			for (size_t i = 0 ; i < seen.size() ; ++i) {
				if (is_substr(val, pos, field().choices->choiceName((int)i))) {
					seen[i] = true;
					break;
				}
			}
			pos = end + 1;
		}
	}
	// now put them back in the right order
	val.clear();
	for (size_t i = 0 ; i < seen.size() ; ++i) {
		if (seen[i]) {
			if (!val.empty()) val += _(", ");
			val += field().choices->choiceName((int)i);
		}
	}
	// empty choice name
	if (val.empty()) {
		val = field().empty_choice;
	}
	// store
	value = with_defaultness_of(value, to_script(val));
}
Example #15
0
	//-----------------------------------------------------------------------
	StringVector StringUtil::tokenise( const String& str, const String& singleDelims, const String& doubleDelims, unsigned int maxSplits)
	{
        StringVector ret;
        // Pre-allocate some space for performance
        ret.reserve(maxSplits ? maxSplits+1 : 10);    // 10 is guessed capacity for most case

        unsigned int numSplits = 0;
		String delims = singleDelims + doubleDelims;

		// Use STL methods 
        size_t start, pos;
		char curDoubleDelim = 0;
        start = 0;
        do 
        {
			if (curDoubleDelim != 0)
			{
				pos = str.find(curDoubleDelim, start);
			}
			else
			{
				pos = str.find_first_of(delims, start);
			}

            if (pos == start)
            {
				char curDelim = str.at(pos);
				if (doubleDelims.find_first_of(curDelim) != String::npos)
				{
					curDoubleDelim = curDelim;
				}
                // Do nothing
                start = pos + 1;
            }
            else if (pos == String::npos || (maxSplits && numSplits == maxSplits))
            {
				if (curDoubleDelim != 0)
				{
					//Missing closer. Warn or throw exception?
				}
                // Copy the rest of the string
                ret.push_back( str.substr(start) );
                break;
            }
            else
            {
				if (curDoubleDelim != 0)
				{
					curDoubleDelim = 0;
				}

				// Copy up to delimiter
				ret.push_back( str.substr(start, pos - start) );
				start = pos + 1;
            }
			if (curDoubleDelim == 0)
			{
				// parse up to next real data
				start = str.find_first_not_of(singleDelims, start);
			}
            
            ++numSplits;

        } while (pos != String::npos);

        return ret;
    }
Example #16
0
	bool Potential1210::extractSection
		(ForceFieldParameters& parameters, const String& section_name) 
	{

		// clear the fields first

		clear();

		// check whether the parameters are valid
		if (!parameters.isValid())
		{
			return false;
		}
			

		// extract the basis information
		ParameterSection::extractSection(parameters, section_name);
		
		// check whether all variables we need are defined, terminate otherwise
		if (!hasVariable("A") || !hasVariable("B"))
		{
			return false;
		}

		// build a two dimensional array of the atom types
		// loop variable
		Size	i;

		AtomTypes& atom_types = parameters.getAtomTypes();
		number_of_atom_types_ = atom_types.getNumberOfTypes();
		
		// allocate two onedimensional fields for the two parameters
		A_.resize(number_of_atom_types_ * number_of_atom_types_);
		B_.resize(number_of_atom_types_ * number_of_atom_types_);
		is_defined_.resize(number_of_atom_types_ * number_of_atom_types_);

		for (i = 0; i < number_of_atom_types_ * number_of_atom_types_; i++) 
		{
			is_defined_[i] = false;
		}

		StringHashMap<Index>::Iterator it;

		// determine the factor to convert the parameters to the standard units used
		// as a default, energies are assumend to be in kJ/mol and distances in Angstrom
		double factor_A = 1.0;
		double factor_B = 1.0;
		if (options.has("unit_A"))
		{
			if (options["unit_A"] == "kcal/mol*A^12")
			{
				factor_A = Constants::JOULE_PER_CAL;
			} 
			else 
			{
				Log.warn() << "unknown unit for parameter A: " << options["unit_A"] << endl;
			}
		}	
		
		if (options.has("unit_B"))
		{
			if (options["unit_B"] == "kcal/mol*A^10")
			{
				factor_B = Constants::JOULE_PER_CAL;
			} 
			else 
			{
				Log.warn() << "unknown unit for parameter B: " << options["unit_B"] << endl;
			}
		}	
		

		Atom::Type		type_I;
		Atom::Type		type_J;
		String				type_name_I;
		String				type_name_J;
		String				key;
		Index					index = 0;

		for (it = section_entries_.begin(); !(it == section_entries_.end()); ++it)
		{
			key = (*it).first;
			if ((key.size() > 0) && (key.find_first_of(" ", 0) > 0)) 
			{
				type_name_I = key.before(" ", 0);
				type_name_J = key.after(" ", 0);
				if ((atom_types.hasType(type_name_I)) && (atom_types.hasType(type_name_J))) 
				{
					type_I = atom_types.getType(type_name_I);
					type_J = atom_types.getType(type_name_J);
					index = (Index)(type_I * number_of_atom_types_ + type_J);
					is_defined_[index] = true;
					A_ [index] = getValue(key, "A").toFloat() * factor_A;
					B_ [index] = getValue(key, "B").toFloat() * factor_B;
					index = (Index)(type_I + number_of_atom_types_ * type_J);
					is_defined_[index] = true;
					A_ [index] = getValue(key, "A").toFloat() * factor_A;
					B_ [index] = getValue(key, "B").toFloat() * factor_B;
				}
			}
		}

		return true;
	}
void ResourcePackerScreen::ProcessFlags(const String & flagsPathname)
{
	File * file = File::Create(flagsPathname.c_str(), File::READ | File::OPEN);
	if (!file)
	{
		Logger::Error("Failed to open file: %s", flagsPathname.c_str());
	}
	char flagsTmpBuffer[4096];
	int flagsSize = 0;
	while(!file->IsEof())
	{
		char c;
		int32 readSize = file->Read(&c, 1);
		if (readSize == 1)
		{
			flagsTmpBuffer[flagsSize++] = c;
		}	
	}
	flagsTmpBuffer[flagsSize++] = 0;
	
	currentFlags = flagsTmpBuffer;
	String flags = flagsTmpBuffer;
	
	const String & delims=" ";
	
	// Skip delims at beginning, find start of first token
	String::size_type lastPos = flags.find_first_not_of(delims, 0);
	// Find next delimiter @ end of token
	String::size_type pos     = flags.find_first_of(delims, lastPos);
	// output vector
	Vector<String> tokens;
	
	while (String::npos != pos || String::npos != lastPos)
	{
		// Found a token, add it to the vector.
		tokens.push_back(flags.substr(lastPos, pos - lastPos));
		// Skip delims.  Note the "not_of". this is beginning of token
		lastPos = flags.find_first_not_of(delims, pos);
		// Find next delimiter at end of token.
		pos     = flags.find_first_of(delims, lastPos);
	}
	
	if (CommandLineParser::Instance()->GetVerbose())
		for (int k = 0; k < (int) tokens.size(); ++k)
		{
			Logger::Debug("Token: %s", tokens[k].c_str());
		}

	if (Core::Instance()->IsConsoleMode())
	{
		for (int k = 0; k < (int) tokens.size(); ++k)
		{
			String sub = tokens[k].substr(0, 2);
			if (sub != "--")
				printf("\n[WARNING: flag %s incorrect]\n", tokens[k].c_str());
		}
	}
	
	CommandLineParser::Instance()->SetFlags(tokens);
	
	SafeRelease(file);
}
	//---------------------------------------------------------------------
	void GLSLESProgramManagerCommon::extractConstantDefs(const String& src,
		GpuNamedConstants& defs, const String& filename)
	{
		// Parse the output string and collect all uniforms
		// NOTE this relies on the source already having been preprocessed
		// which is done in GLSLESProgram::loadFromSource
		String line;
		String::size_type currPos = src.find("uniform");
		while (currPos != String::npos)
		{
			GpuConstantDefinition def;
			String paramName;

			// Now check for using the word 'uniform' in a larger string & ignore
			bool inLargerString = false;
			if (currPos != 0)
			{
				char prev = src.at(currPos - 1);
				if (prev != ' ' && prev != '\t' && prev != '\r' && prev != '\n'
					&& prev != ';')
					inLargerString = true;
			}
			if (!inLargerString && currPos + 7 < src.size())
			{
				char next = src.at(currPos + 7);
				if (next != ' ' && next != '\t' && next != '\r' && next != '\n')
					inLargerString = true;
			}

			// skip 'uniform'
			currPos += 7;

			if (!inLargerString)
			{
                String::size_type endPos;
                String typeString;
                GpuSharedParametersPtr blockSharedParams;

                // Check for a type. If there is one, then the semicolon is missing
                // otherwise treat as if it is a uniform block
				String::size_type lineEndPos = src.find_first_of("\n\r", currPos);
				line = src.substr(currPos, lineEndPos - currPos);
                StringVector parts = StringUtil::split(line, " \t");

                // Skip over precision keywords
                if(StringUtil::match((parts.front()), "lowp") ||
                   StringUtil::match((parts.front()), "mediump") ||
                   StringUtil::match((parts.front()), "highp"))
                    typeString = parts[1];
                else
                    typeString = parts[0];

                StringToEnumMap::iterator typei = mTypeEnumMap.find(typeString);
                if (typei == mTypeEnumMap.end())
                {
                    // Gobble up the external name
                    String externalName = parts.front();

                    // Now there should be an opening brace
                    String::size_type openBracePos = src.find("{", currPos);
                    if (openBracePos != String::npos)
                    {
                        currPos = openBracePos + 1;
                    }
                    else
                    {
                        LogManager::getSingleton().logMessage("Missing opening brace in GLSL Uniform Block in file "
                                                              + filename);
                        break;
                    }

                    // First we need to find the internal name for the uniform block
                    String::size_type endBracePos = src.find("}", currPos);

                    // Find terminating semicolon
                    currPos = endBracePos + 1;
                    endPos = src.find(";", currPos);
                    if (endPos == String::npos)
                    {
                        // problem, missing semicolon, abort
                        break;
                    }
                }
                else
                {
                    // find terminating semicolon
                    endPos = src.find(";", currPos);
                    if (endPos == String::npos)
                    {
                        // problem, missing semicolon, abort
                        break;
                    }
                    
                    parseIndividualConstant(src, defs, currPos, filename, blockSharedParams);
                }
                line = src.substr(currPos, endPos - currPos);
			} // not commented or a larger symbol

			// Find next one
			currPos = src.find("uniform", currPos);
		}
		
	}
//----------------------------------------------------------------------------//
RenderedString BasicRenderedStringParser::parse(const String& input_string,
                                                Font* initial_font,
                                                const ColourRect* initial_colours)
{
    // first-time initialisation (due to issues with static creation order)
    if (!d_initialised)
        initialiseTagHandlers();

    initialiseDefaultState();

    // maybe override initial font.
    if (initial_font)
        d_fontName = initial_font->getName();

    // maybe override initial colours.
    if (initial_colours)
        d_colours = *initial_colours;

    RenderedString rs;
    String curr_section;

    size_t curr_pos = 0;

    while (curr_pos < input_string.length())
    {
        size_t cstart_pos = input_string.find_first_of('[', curr_pos);

        // if no control sequence start char, add remaining text verbatim.
        if (String::npos == cstart_pos)
        {
            curr_section += input_string.substr(curr_pos);
            curr_pos = input_string.length();
        }
        else if (cstart_pos == curr_pos || input_string[cstart_pos - 1] != '\\')
        {
            // append everything up to the control start to curr_section.
            curr_section += input_string.substr(curr_pos, cstart_pos - curr_pos);

            // scan forward for end of control sequence
            size_t cend_pos = input_string.find_first_of(']', cstart_pos);
            // if not found, treat as plain text
            if (String::npos == cend_pos)
            {
                curr_section += input_string.substr(curr_pos);
                curr_pos = input_string.length();
            }
            // extract control string
            else
            {
                appendRenderedText(rs, curr_section);
                curr_section.clear();

                String ctrl_string(
                    input_string.substr(cstart_pos + 1,
                                        cend_pos - cstart_pos - 1));
                curr_pos = cend_pos + 1;

                processControlString(rs, ctrl_string);
                continue;
            }
        }
        else
        {
            curr_section += input_string.substr(curr_pos,
                                                cstart_pos - curr_pos - 1);
            curr_section += '[';
            curr_pos = cstart_pos + 1;
            continue;
        }

        appendRenderedText(rs, curr_section);
        curr_section.clear();
    }

    return rs;
}
    //---------------------------------------------------------------------
    void GLSLProgramManagerCommon::extractConstantDefs(const String& src,
        GpuNamedConstants& defs, const String& filename)
    {
        // Parse the output string and collect all uniforms
        // NOTE this relies on the source already having been preprocessed
        // which is done in GLSLProgram::loadFromSource
        String line;
        String::size_type currPos = src.find("uniform");
        while (currPos != String::npos)
        {
            // Now check for using the word 'uniform' in a larger string & ignore
            bool inLargerString = false;
            if (currPos != 0)
            {
                char prev = src.at(currPos - 1);
                if (prev != ' ' && prev != '\t' && prev != '\r' && prev != '\n'
                    && prev != ';')
                    inLargerString = true;
            }
            if (!inLargerString && currPos + 7 < src.size())
            {
                char next = src.at(currPos + 7);
                if (next != ' ' && next != '\t' && next != '\r' && next != '\n')
                    inLargerString = true;
            }

            // skip 'uniform'
            currPos += 7;

            if (!inLargerString)
            {
                String::size_type endPos;
                GpuSharedParametersPtr blockSharedParams;

                // Check for a type. If there is one, then the semicolon is missing
                // otherwise treat as if it is a uniform block
                String::size_type lineEndPos = src.find_first_of("\n\r", currPos);
                line = src.substr(currPos, lineEndPos - currPos);
                StringVector parts = StringUtil::split(line, " \t");
                StringToEnumMap::iterator typei = mTypeEnumMap.find(parts.front());
                if (typei == mTypeEnumMap.end())
                {
                    // Gobble up the external name
                    String externalName = parts.front();

                    // Now there should be an opening brace
                    String::size_type openBracePos = src.find("{", currPos);
                    if (openBracePos != String::npos)
                    {
                        currPos = openBracePos + 1;
                    }
                    else
                    {
                        LogManager::getSingleton().logMessage("Missing opening brace in GLSL Uniform Block in file "
                                                              + filename);
                        break;
                    }

                    // First we need to find the internal name for the uniform block
                    String::size_type endBracePos = src.find("}", currPos);

                    // Find terminating semicolon
                    currPos = endBracePos + 1;
                    endPos = src.find(";", currPos);
                    if (endPos == String::npos)
                    {
                        // problem, missing semicolon, abort
                        break;
                    }

                    // TODO: We don't need the internal name. Just skip over to the end of the block
                    // But we do need to know if this is an array of blocks. Is that legal?

// Find the internal name.
// This can be an array.
//                    line = src.substr(currPos, endPos - currPos);
//                    StringVector internalParts = StringUtil::split(line, ", \t\r\n");
//                    String internalName = "";
//                    uint16 arraySize = 0;
//                    for (StringVector::iterator i = internalParts.begin(); i != internalParts.end(); ++i)
//                    {
//                        StringUtil::trim(*i);
//                        String::size_type arrayStart = i->find("[", 0);
//                        if (arrayStart != String::npos)
//                        {
//                            // potential name (if butted up to array)
//                            String name = i->substr(0, arrayStart);
//                            StringUtil::trim(name);
//                            if (!name.empty())
//                                internalName = name;
//
//                            String::size_type arrayEnd = i->find("]", arrayStart);
//                            String arrayDimTerm = i->substr(arrayStart + 1, arrayEnd - arrayStart - 1);
//                            StringUtil::trim(arrayDimTerm);
//                            arraySize = StringConverter::parseUnsignedInt(arrayDimTerm);
//                        }
//                        else
//                        {
//                            internalName = *i;
//                        }
//                    }
//
//                    // Ok, now rewind and parse the individual uniforms in this block
//                    currPos = openBracePos + 1;
//                    blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(externalName);
//                    if(blockSharedParams.isNull())
//                        blockSharedParams = GpuProgramManager::getSingleton().createSharedParameters(externalName);
//                    do
//                    {
//                        lineEndPos = src.find_first_of("\n\r", currPos);
//                        endPos = src.find(";", currPos);
//                        line = src.substr(currPos, endPos - currPos);
//
//                        // TODO: Give some sort of block id
//                        // Parse the normally structured uniform
//                        parseIndividualConstant(src, defs, currPos, filename, blockSharedParams);
//                        currPos = lineEndPos + 1;
//                    } while (endBracePos > currPos);
                }
                else
                {
                    // find terminating semicolon
                    endPos = src.find(";", currPos);
                    if (endPos == String::npos)
                    {
                        // problem, missing semicolon, abort
                        break;
                    }
                    
                    parseIndividualConstant(src, defs, currPos, filename, blockSharedParams);
                }
                line = src.substr(currPos, endPos - currPos);
            } // not commented or a larger symbol
            
            // Find next one
            currPos = src.find("uniform", currPos);
        }
    }
Example #21
0
int main(int argc, char* argv[])
{
  StringSet targets, configurations, schemes;
  String sdkRoot, projectPath, xcconfigPath, workspacePath;
  String logVerbosity("warning");
  int projectSet = 0;
  int workspaceSet = 0;
  int interactiveFlag = 0;
  int relativeSdkFlag = 0;
  int genProjectionsFlag = 0;
  int allTargets = 0;
  int allSchemes = 0;
  int mode = GenerateMode;

  static struct option long_options[] = {
    {"version", no_argument, 0, 0},
    {"usage", no_argument, 0, 0},
    {"help", no_argument, 0, 0},
    {"interactive", no_argument, &interactiveFlag, 1},
    {"loglevel", required_argument, 0, 0},
    {"sdk", required_argument, 0, 0},
    {"list", no_argument, &mode, ListMode},
    {"project", required_argument, &projectSet, 1},
    {"target", required_argument, 0, 0},
    {"alltargets", no_argument, &allTargets, 1},
    {"configuration", required_argument, 0, 0},
    {"xcconfig", required_argument, 0, 0},
    {"workspace", required_argument, &workspaceSet, 1},
    {"scheme", required_argument, 0, 0},
    {"allschemes", required_argument, &allSchemes, 1},
    {"relativepath", no_argument, &relativeSdkFlag, 1},
    { "genprojections", no_argument, &genProjectionsFlag, 1 },
    {0, 0, 0, 0}
  };

  int numOptions = sizeof(long_options) / sizeof(struct option) - 1;
  while (1) {
    int option_index = 0;
    int c = getopt_long_only(argc, argv, "", long_options, &option_index);

    if (c == -1) {
      break;
    } else if (c || option_index < 0 || option_index >= numOptions) {
      printUsage(argv[0], false);
      exit(EXIT_FAILURE);
    }

    // Process options
    switch (option_index) {
    case 0:
      printVersion(argv[0]);
      exit(EXIT_SUCCESS);
      break;
    case 1:
      printUsage(argv[0], false);
      exit(EXIT_SUCCESS);
      break;
    case 2:
      printUsage(argv[0], true);
      exit(EXIT_SUCCESS);
      break;
    case 4:
      logVerbosity = strToLower(optarg);
      break;
    case 5:
      sdkRoot = optarg;
      break;
    case 7:
      projectPath = optarg;
      break;
    case 8:
      targets.insert(optarg);
      break;
    case 10:
      configurations.insert(optarg);
      break;
    case 11:
      xcconfigPath = optarg;
      break;
    case 12:
      workspacePath = optarg;
      break;
    case 13:
      schemes.insert(optarg);
      break;
    default:
      // Do nothing
      break;
    }
  }

  // Set AI Telemetry_Init 
  TELEMETRY_INIT(L"AIF-23c336e0-1e7e-43ba-a5ce-eb9dc8a06d34");

  if (checkTelemetryOptIn())
  {
      TELEMETRY_ENABLE();
  }
  else
  {
      TELEMETRY_DISABLE();
  }

  TELEMETRY_SET_INTERNAL(isMSFTInternalMachine());
  String machineID = getMachineID();
  if (!machineID.empty())
  {
      TELEMETRY_SET_MACHINEID(machineID.c_str());
  }

  TELEMETRY_EVENT_DATA(L"VSImporterStart", getProductVersion().c_str());

  // Process non-option ARGV-elements
  VariableCollectionManager& settingsManager = VariableCollectionManager::get();
  while (optind < argc) {
    String arg = argv[optind];
    if (arg == "/?") {
      // Due to issue 6715724, flush before exiting
      TELEMETRY_EVENT_DATA(L"VSImporterIncomplete", "printUsage");
      TELEMETRY_FLUSH();
      printUsage(argv[0], true);
      exit(EXIT_SUCCESS);
    } else if (arg.find_first_of('=') != String::npos) {
      settingsManager.processGlobalAssignment(arg);
    } else {
      sbValidateWithTelemetry(0, "Unsupported argument: " + arg);
    }
    optind++;
  }

  // Set output format
  settingsManager.setGlobalVar("VSIMPORTER_OUTPUT_FORMAT", "WinStore10");

  // Set logging level
  SBLogLevel logLevel;
  if (logVerbosity == "debug")
    logLevel = SB_DEBUG;
  else if (logVerbosity == "info")
    logLevel = SB_INFO;
  else if (logVerbosity == "warning")
    logLevel = SB_WARN;
  else if (logVerbosity == "error")
    logLevel = SB_ERROR;
  else if (!logVerbosity.empty()) {
	  sbValidateWithTelemetry(0, "Unrecognized logging verbosity: " + logVerbosity);
  }
  SBLog::setVerbosity(logLevel);

  // Look for a project file in current directory, if one hasn't been explicitly specified 
  if (!projectSet && !workspaceSet) {
    StringList projects;
    findFiles(".", "*.xcodeproj", DT_DIR, false, projects);
    StringList workspaces;
    findFiles(".", "*.xcworkspace", DT_DIR, false, workspaces);

    if (!workspaces.empty()) {
      sbValidateWithTelemetry(workspaces.size() == 1, "Multiple workspaces found. Select the workspace to use with the -workspace option.");
      workspacePath = workspaces.front();
      workspaceSet = 1;
	}
	else if (!projects.empty()) {
		sbValidateWithTelemetry(projects.size() == 1, "Multiple projects found. Select the project to use with the -project option.");
		projectPath = projects.front();
		projectSet = 1;
	} else {
		sbValidateWithTelemetry(0, "The current directory does not contain a project or workspace.");
    }
  }

  // Set the architecture
  String arch = "msvc";
  settingsManager.setGlobalVar("ARCHS", arch);
  settingsManager.setGlobalVar("CURRENT_ARCH", arch);

  // Make sure workspace arguments are valid
  if (workspaceSet) {
    sbValidateWithTelemetry(!projectSet, "Cannot specify both a project and a workspace.");
  }

  // Disallow specifying schemes and targets together
  sbValidateWithTelemetry((schemes.empty() && !allSchemes) || (targets.empty() && !allTargets), "Cannot specify schemes and targets together.");

  // Process allTargets and allSchemes flags
  if (allSchemes)
    schemes.clear();
  if (allTargets)
    targets.clear();

  // Initialize global settings
  String binaryDir = sb_dirname(getBinaryLocation());
  sbValidateWithTelemetry(!binaryDir.empty(), "Failed to resolve binary directory.");
  settingsManager.setGlobalVar("VSIMPORTER_BINARY_DIR", binaryDir);
  settingsManager.setGlobalVar("VSIMPORTER_INTERACTIVE", interactiveFlag ? "YES" : "NO");
  settingsManager.setGlobalVar("VSIMPORTER_RELATIVE_SDK_PATH", relativeSdkFlag ? "YES" : "NO");
  if (!sdkRoot.empty()) {
    sdkRoot = joinPaths(getcwd(), sdkRoot);
  } else {
    sdkRoot = joinPaths(binaryDir, "..");
  }
  settingsManager.setGlobalVar("WINOBJC_SDK_ROOT", sdkRoot);

  // Add useful environment variables to global settings
  String username;
  sbValidateWithTelemetry(sb_getenv("USERNAME", username), "Failed to get current username.");
  settingsManager.setGlobalVar("USER", username);

  // Read xcconfig file specified from the command line
  if (!xcconfigPath.empty())
    settingsManager.processGlobalConfigFile(xcconfigPath);

  // Read xcconfig file specified by the XCODE_XCCONFIG_FILE environment variable
  String xcconfigFile;
  if (sb_getenv("XCODE_XCCONFIG_FILE", xcconfigFile))
    settingsManager.processGlobalConfigFile(xcconfigFile);

  // Validate WinObjC SDK directory
  checkWinObjCSDK();

  // Create a workspace
  SBWorkspace *mainWorkspace;
  if (workspaceSet) {
    mainWorkspace = SBWorkspace::createFromWorkspace(workspacePath);
  } else if (projectSet) {
    mainWorkspace = SBWorkspace::createFromProject(projectPath);
  } else {
	  sbAssertWithTelemetry(0); // non-reachable
  }

  if (mode == ListMode) {
    mainWorkspace->printSummary();
  } else if (mode == GenerateMode) {
    if (!schemes.empty() || allSchemes) {
      mainWorkspace->queueSchemes(schemes, configurations);
    } else {
      mainWorkspace->queueTargets(targets, configurations);
    }
    mainWorkspace->generateFiles(genProjectionsFlag);
  } else {
	  sbAssertWithTelemetry(0); // non-reachable
  }

  TELEMETRY_EVENT_DATA(L"VSImporterComplete", getProductVersion().c_str());
  TELEMETRY_FLUSH();

  return EXIT_SUCCESS;
}