Пример #1
0
void Script::GetAssociatedFilenames(Array<String> &lstFilenames)
{
	// We want to have a list of script filenames which were included within this script
	// -> It appears that there's no "easy" way in Lua to get this kind of information :/

	// Contains "Application", "Interaction" and so on (no final filenames)
	Array<String> lstRequire;

	// Get a list of loaded "require"-files
	{ // -> The files loaded within a Lua script by using "require" can be accessed by using the
		//    global control table variable "_LOADED". See http://www.lua.org/pil/8.1.html for details.
		lua_getfield(m_pLuaState, LUA_REGISTRYINDEX, "_LOADED");
		if (lua_istable(m_pLuaState, -1)) {
			lua_pushnil(m_pLuaState);
			while (lua_next(m_pLuaState, -2)) {
				if (lua_isstring(m_pLuaState, -2))
					lstRequire.Add(lua_tostring(m_pLuaState, -2));
				lua_pop(m_pLuaState, 1);
			}
		}

		// Pop the table from the Lua stack
		lua_pop(m_pLuaState, 1);
	}

	// Get the content of "package.path" used by "require" to search for a Lua loader
	// -> The content looks like "?.lua;C:\SomePath\?.lua;"
	const String sPackagePath = GetGlobalVariable("path", "package");

	// Iterate over the "require"-list
	const String sToReplace = "?.";
	for (uint32 i=0; i<lstRequire.GetNumOfElements(); i++) {
		// Get the current "require"
		const String sRequire = lstRequire[i] + '.';

		// Get the index of the first ";" within the package path
		int nPreviousIndex = 0;
		int nIndex = sPackagePath.IndexOf(';');
		while (nIndex>-1) {
			// Get current package search path, we now have e.g. "C:\SomePath\?.lua"
			String sFilename = sPackagePath.GetSubstring(nPreviousIndex, nIndex-nPreviousIndex);

			// Replace "?." with the "require"-name
			sFilename.Replace(sToReplace, sRequire);

			// Does this file exist?
			if (File(sFilename).Exists()) {
				// We found a match!
				lstFilenames.Add(sFilename);

				// Get us out of the while-loop
				nIndex = -1;
			} else {
				// Get the index of the next ";" within the package path
				nPreviousIndex = nIndex + 1;
				nIndex = sPackagePath.IndexOf(';', nPreviousIndex);
			}
		}
	}
}
Пример #2
0
/**
 * @return True iff the url is correctly URL encoded
 */
Boolean URLUtil::VerifyURLEncoding(
    /* [in] */ const String& url)
{
    AutoPtr<ArrayOf<Char32> > chars = url.GetChars();
    Int32 count = chars->GetLength();
    if (count == 0) {
        return FALSE;
    }

    Int32 index = url.IndexOf('%');
    while (index >= 0 && index < count) {
        if (index < count - 2) {
            //try {
            Int32 byteOut;
            if (FAILED(ParseHex((Byte) (*chars)[++index], &byteOut))) {
                return FALSE;
            }
            if (FAILED(ParseHex((Byte) (*chars)[++index], &byteOut))) {
                return FALSE;
            }
            //} catch (IllegalArgumentException e) {
            //    return false;
            //}
        }
        else {
            return FALSE;
        }

        index = url.IndexOf('%', index + 1);
    }
    return TRUE;
}
Пример #3
0
ECode CSizeF::ParseSizeF(
    /* [in] */ const String& string,
    /* [out] */ ISizeF** size)
{
    VALIDATE_NOT_NULL(size)
    *size = NULL;

    if (string.IsNull()) {
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
    }
    //checkNotNull(string, "string must not be null");

    Int32 sep_ix = string.IndexOf('*');
    if (sep_ix < 0) {
        sep_ix = string.IndexOf('x');
    }
    if (sep_ix < 0) {
        // throw invalidSize(string);
        return E_NUMBER_FORMAT_EXCEPTION;
    }

    // try {
    Float w, h;
    FAIL_RETURN(StringUtils::Parse(string.Substring(0, sep_ix), &w))
    FAIL_RETURN(StringUtils::Parse(string.Substring(sep_ix + 1), &h))

    AutoPtr<CSizeF> s;
    CSizeF::NewByFriend(w, h, (CSizeF**)&s);
    *size = (ISizeF*)s.Get();
    REFCOUNT_ADD(*size)
    // } catch (NumberFormatException e) {
    //     throw invalidSize(string);
    // }
    return NOERROR;
}
Пример #4
0
/**
*  @brief
*    Gets a AngelScript function declaration
*/
String Script::GetAngelScriptFunctionDeclaration(const String &sFunctionName, const String &sFunctionSignature, bool bCppToAngelScript) const
{
	// Start with the PixelLight function signature (e.g. "void(int,float)")
	String sFunctionDeclaration = sFunctionSignature;

	// Find the index of the "("
	int nIndex = sFunctionDeclaration.IndexOf("(");
	if (nIndex > -1) {

		// [HACK] AngelScript really don't like something like "string MyFunction(string)", it want's "string @MyFunction(const string &)"!
		// I assume that "@" means "AngelScript, take over the control of the given memory". I wasn't able to find the documentation about
		// the AngelScript function declaration syntax, just "scriptstring.cpp" as example.
		if (bCppToAngelScript && sFunctionDeclaration.IndexOf("string") > -1) {
			String sParameters = sFunctionDeclaration.GetSubstring(nIndex);	// Find the parameters part in the string
			sParameters.Replace("string", "const string &");				// Change parameters
			sFunctionDeclaration.Delete(nIndex);							// Remove parameters from original function declaration
			sFunctionDeclaration.Replace("string", "string @");				// Change return
			sFunctionDeclaration += sParameters;							// Construct new function declaration
			nIndex = sFunctionDeclaration.IndexOf("(");						// Update the "(" index
		}

		// Create the AngelScript function declaration (e.g. "void MyFunction(int,float)")
		sFunctionDeclaration.Insert(' ' + sFunctionName, nIndex);
	}

	// Return the AngelScript function declaration (e.g. "void MyFunction(int,float)")
	return sFunctionDeclaration;
}
Пример #5
0
ECode UriCodec::Decode(
    /* [in] */ const String& s,
    /* [in] */ Boolean convertPlus,
    /* [in] */ ICharset* charset,
    /* [in] */ Boolean throwOnFailure,
    /* [out] */ String* decodedString)
{
    VALIDATE_NOT_NULL(decodedString);
    if (s.IndexOf('%') == -1 && (!convertPlus || s.IndexOf('+') == -1)) {
        *decodedString = s;
        return NOERROR;
    }

    StringBuilder result(s.GetByteLength());
    AutoPtr<IByteArrayOutputStream> out;
    CByteArrayOutputStream::New((IByteArrayOutputStream**)&out);
    IOutputStream* os = IOutputStream::Probe(out);
    AutoPtr<ArrayOf<Char32> > char32Array = s.GetChars();
    for (Int32 i = 0; i < s.GetLength();) {
        Char32 c = (*char32Array)[i];
        if (c == '%') {
            do {
                Int32 d1, d2;
                if (i + 2 < s.GetLength()
                        && (d1 = HexToInt((*char32Array)[i + 1])) != -1
                        && (d2 = HexToInt((*char32Array)[i + 2])) != -1) {
                    os->Write((Byte) ((d1 << 4) + d2));
                }
                else if (throwOnFailure) {
                    return E_ILLEGAL_ARGUMENT_EXCEPTION;
                }
                else {
                    // TODO: unicode escape
                    const char* chars = "\ufffd";
                    AutoPtr<ArrayOf<Byte> > replacement = GetBytes(chars, charset);
                    os->Write(replacement, 0, replacement->GetLength());
                }
                i += 3;
            } while (i < s.GetLength() && (*char32Array)[i] == '%');

            AutoPtr<ArrayOf<Byte> > bytes;
            out->ToByteArray((ArrayOf<Byte>**)&bytes);
            //result.append(new String(out.toByteArray(), charset);
            result.Append(String((char*)bytes->GetPayload()));
            out->Reset();
        }
        else {
            if (convertPlus && c == '+') {
                c = ' ';
            }
            result.AppendChar(c);
            i++;
        }
    }
    *decodedString = result.ToString();
    return NOERROR;
}
Пример #6
0
Boolean CUsbManager::PropertyContainsFunction(
    /* [in] */ const String& property,
    /* [in] */ const String& function)
{
    AutoPtr<ISystemProperties> sp;
    CSystemProperties::AcquireSingleton((ISystemProperties**)&sp);
    String functions;
    sp->Get(property, String(""), &functions);
    Int32 index = functions.IndexOf(function);

    if (index < 0) {
        return FALSE;
    }

    Char32 c1 = functions.GetChar(index - 1);
    if (index > 0 && c1 != ',') {
        return FALSE;
    }

    Int32 charAfter = index + function.GetLength();
    Char32 c2 = functions.GetChar(charAfter);
    if (charAfter < (Int32)functions.GetLength() && c2 != ',') {
        return FALSE;
    }

    return TRUE;
}
Пример #7
0
String URLUtil::ComposeSearchUrl(
    /* [in] */ const String& inQuery,
    /* [in] */ const String& templateStr,
    /* [in] */ const String& queryPlaceHolder)
{
    Int32 placeHolderIndex = templateStr.IndexOf(queryPlaceHolder);
    if (placeHolderIndex < 0) {
        return String(NULL);
    }

    String query;
    StringBuilder buffer;
    buffer.AppendString(templateStr.Substring(0, placeHolderIndex));

    //try {
    //    query = java.net.URLEncoder.encode(inQuery, "utf-8");
    AutoPtr<IURLEncoder> URLEncoder;
    assert(0);
//    	CURLEncoder::New((IURLEncoder**)&URLEncoder);
    if (FAILED(URLEncoder->Encode(inQuery, String("utf-8"), &query))){
        return String(NULL);
    }
    buffer.AppendString(query);
    //} catch (UnsupportedEncodingException ex) {
    //    return null;
    //}

    buffer.AppendString(templateStr.Substring(
            placeHolderIndex + queryPlaceHolder.GetLength()));

    return buffer.ToString();
}
ECode HttpURLConnection::GetResponseCode(
    /* [out] */ Int32* responseCode)
{
    VALIDATE_NOT_NULL(responseCode)

    // Call getInputStream() first since getHeaderField() doesn't return
    // exceptions
    AutoPtr<IInputStream> is;
    FAIL_RETURN(GetInputStream((IInputStream**)&is));
    String response;
    GetHeaderField(0, &response);
    if (response.IsNull()) {
        *responseCode = -1;
        return NOERROR;
    }
    response = response.Trim();
    Int32 mark = response.IndexOf(" ") + 1;
    if (mark == 0) {
        *responseCode = -1;
        return NOERROR;
    }
    Int32 last = mark + 3;
    if (last > response.GetLength()) {
        last = response.GetLength();
    }
    mResponseCode = StringUtils::ParseInt32(response.Substring(mark, last));
    if ((last + 1) <= response.GetLength()) {
        mResponseMessage = response.Substring(last + 1);
    }
    *responseCode = mResponseCode;
    return NOERROR;
}
ECode CHttpAuthHeader::ParseParameter(
    /* [in] */ const String& parameter)
{
    if (parameter != NULL) {
        // here, we are looking for the 1st occurence of '=' only!!!
        Int32 i = parameter.IndexOf('=');
        if (i >= 0) {
            String token = parameter.Substring(0, i).Trim();
            String value =
                TrimDoubleQuotesIfAny(parameter.Substring(i + 1).Trim());

            if (HttpLog::LOGV) {
                HttpLog::V(String("HttpAuthHeader.parseParameter(): token: ") + token
                    + String(" value: ") + value);
            }

            if (token.EqualsIgnoreCase(REALM_TOKEN)) {
                mRealm = value;
            } else {
                if (mScheme == DIGEST) {
                    ParseParameter(token, value);
                }
            }
        }
    }
    return NOERROR;
}
Пример #10
0
void  LocationMapForm::HandleJavaScriptRequestN (Tizen::Web::Json::IJsonValue *pArg)
{
	 AppLog("PathFinder:: HandleJavaScriptRequestN");
	 result r = E_SUCCESS;
	 JsonObject* pJsonObject = static_cast< JsonObject* >(pArg);
	 IJsonValue* pValue = null;
	 JsonString* pJsonStringValue = null;
	 String key(L"data");

	 r = pJsonObject->GetValue(&key, pValue);
	 pJsonStringValue = static_cast< JsonString* >(pValue);
	 const wchar_t* mapPointString = pJsonStringValue->GetPointer();

	 AppLog("data: %ls\n", mapPointString);

	 String *tmpString = new String(mapPointString);

	 Float x , y;

	 int idx = 0;


	 tmpString->IndexOf(' ' , 0 , idx);

	 String *tmpString2 = new String ( mapPointString + idx + 1 );

	 const wchar_t* tmpChar =  tmpString->GetPointer();
	 wchar_t* tmpChar3 = const_cast<wchar_t*>(tmpChar);
	 tmpChar3[idx] = '\0';
	 const wchar_t* tmpChar2 = tmpString2->GetPointer();

	 x.Parse(tmpChar3 , this->__latitude );
	 y.Parse(tmpChar2 , this->__longitude );
}
Пример #11
0
ECode CVideoPlayer::OnCreate(
    /* [in] */ IBundle* savedInstanceState)
{
    Activity::OnCreate(savedInstanceState);
    SetContentView(2130903046);//R.layout.videoplayer
    mVideoView = IVideoView::Probe(FindViewById(0x7f07000a));//R::Id::VideoView
    AutoPtr<IMediaController> mediaController;
//    FAIL_RETURN(CMediaController::New(this, (IMediaController**)&mediaController));
    mediaController->SetAnchorView(mVideoView);
    AutoPtr<IIntent> intent;
    FAIL_RETURN(GetIntent((IIntent**)&intent));
    AutoPtr<IUri> data;
    intent->GetData((IUri**)&data);
    if (data == NULL)
        return NOERROR;
    String spec;
    String scheme;
    data->GetScheme(&scheme) ;
    if (String("vnd.youtube").Equals(scheme)) {
        String ssp;
        data->GetSchemeSpecificPart(&ssp);
        String id = ssp.Substring(0, ssp.IndexOf('?'));
        FAIL_RETURN(GetSpecFromYouTubeVideoID(id, &spec));
    }
    if (spec == NULL)
        return NOERROR;
    AutoPtr<IUri> video;
//    FAIL_RETURN(Uri::Parse(spec, (IUri**)&video));
    FAIL_RETURN(mVideoView->SetMediaController(mediaController));
    FAIL_RETURN(mVideoView->SetVideoURI(video));
    FAIL_RETURN(IMediaPlayerControl::Probe(mVideoView)->Start());

    return NOERROR;
}
Пример #12
0
ECode CModuleInfo::GetInterfaceInfo(
    /* [in] */ const String& fullName,
    /* [out] */ IInterfaceInfo** interfaceInfo)
{
    if (fullName.IsNull() || NULL == interfaceInfo) {
        return E_INVALID_ARGUMENT;
    }

    ECode ec = AcquireInterfaceList();
    if (FAILED(ec)) return ec;

    Int32 start = fullName.IndexOf('L');
    Int32 end = fullName.IndexOf(';');
    String strName = fullName.Substring(start >= 0 ? start + 1 : 0, end > 0 ? end : fullName.GetLength()).Replace('/', '.');
    return mInterfaceList->AcquireObjByName(strName, (IInterface **)interfaceInfo);
}
Пример #13
0
		Vector<String> String::SplitEmptyEntries(const String& string, const String& delimiter, int count)
		{
			// variables
			int index = 0;
			int lastIndex = -1;
			Vector<String> vector;

			while (index != -1) {
				index = string.IndexOf(delimiter, lastIndex + 1);
				
				if (lastIndex + 1 == index) {
					vector.Add(String());
				} else {
					// TODO: readable calculation
					int startIndex = ((lastIndex == -1) ? (0) : (lastIndex + delimiter._length));
					int length = ((index == -1) ? (string._length - lastIndex - delimiter._length) : (index - lastIndex - delimiter._length));
					vector.Add(String(string._data, startIndex, length));
				}

				lastIndex = index;

				if (vector.Length >= count - 1) {
					// TODO: readable calculation
					int startIndex = ((lastIndex == -1) ? (0) : (lastIndex + delimiter._length));
					int length = ((lastIndex == -1) ? (string._length) : (string._length - lastIndex - delimiter._length));
					vector.Add(String(string._data, startIndex, length));
					return vector;
				}
			}

			return vector;
		}
Пример #14
0
void RemoveANSISequences(String & s)
{
   TCHECKPOINT;

   static const char _escapeBuf[] = {0x1B, '[', '\0'};
   static String _escape; if (_escape.IsEmpty()) _escape = _escapeBuf;

   while(true)
   {
      const int32 idx = s.IndexOf(_escape);  // find the next escape sequence
      if (idx >= 0)
      {
         const char * data = s()+idx+2;  // move past the ESC char and the [ char
         switch(data[0])
         {
            case 's': case 'u': case 'K':   // these are single-letter codes, so
               data++;                      // just skip over them and we are done
            break;

            case '=':
               data++;
            // fall through!
            default:
               // For numeric codes, keep going until we find a non-digit that isn't a semicolon
               while((muscleInRange(*data, '0', '9'))||(*data == ';')) data++;
               if (*data) data++;  // and skip over the trailing letter too.
            break;
         }
         s = s.Substring(0, idx) + s.Substring((uint32)(data-s()));  // remove the escape substring
      }
      else break;
   }
}
ECode CHttpAuthHeader::ParseScheme(
    /* [in] */ const String& header,
    /* [out] */ String* scheme)
{
    if (header != NULL) {
        Int32 i = header.IndexOf(' ');
        if (i >= 0) {
            String localScheme = header.Substring(0, i).Trim();
            if (localScheme.EqualsIgnoreCase(DIGEST_TOKEN)) {
                mScheme = DIGEST;

                // md5 is the default algorithm!!!
                mAlgorithm = String("md5");
            } else {
                if (localScheme.EqualsIgnoreCase(BASIC_TOKEN)) {
                    mScheme = BASIC;
                }
            }

            *scheme = header.Substring(i + 1);
        }
    }

    *scheme = String(NULL);
    return NOERROR;
}
Пример #16
0
ECode CExifInterface::GetAttributeDouble(
    /* [in] */ const String& tag,
    /* [in] */ Double defaultValue,
    /* [out] */ Double* result)
{
    VALIDATE_NOT_NULL(result);
    *result = defaultValue;

    HashMap<String, String>::Iterator it = mAttributes.Find(tag);
    if (it != mAttributes.End()) {
        String value = it->mSecond;
        if (value.IsNull()) {
            return NOERROR;
        }

        Int32 index = value.IndexOf("/");
        if (index == -1) {
            return NOERROR;
        }
        Double denom = StringUtils::ParseDouble(value.Substring(index + 1));
        if (denom == 0) {
            return NOERROR;
        }
        Double num = StringUtils::ParseDouble(value.Substring(0, index));
        *result = num / denom;
    }
    return NOERROR;
}
ECode CJDBCResultSetMetaData::FindColByName(
    /* [in] */ const String& columnName,
    /* [out] */ Int32 * value)
{
    String c = String(NULL);
    if (r != NULL && ((CJDBCResultSet *)r.Get())->tr != NULL) {
        for (Int32 i = 0; i < ((CJDBCResultSet *)r.Get())->tr->mNcolumns; i++) {
            c = (*((CJDBCResultSet *)r.Get())->tr->mColumn)[i];
            if (c != NULL) {
                if (c.EqualsIgnoreCase(columnName) == 0) {
                    *value = i + 1;
                } else {
                    Int32 k = c.IndexOf('.');
                    if (k > 0) {
                        c = c.Substring(k + 1);
                        if (c.EqualsIgnoreCase(columnName) == 0) {
                            *value = i + 1;
                        }
                    }
                }
            }
        }
    } else {
        return E_SQL_EXCEPTION;
    }
    return NOERROR;
}
Пример #18
0
/**
*  @brief
*    Adds a Python function
*/
bool Script::AddPythonFunction(PyObject *pPythonDictionary, const String &sFunction, PyObject *pPythonFunction, const String &sNamespace) const
{
    // Is the given namespace empty?
    if (sNamespace.GetLength()) {
        // Nope, the target namespace is not yet reached...

        // Find the next "." within the given nested Python namespace name
        int nPartEnd = sNamespace.IndexOf(".");
        if (nPartEnd < 0)
            nPartEnd = sNamespace.GetLength();

        // Get the current Python namespace name
        const String sSubsNamespaceName = sNamespace.GetSubstring(0, nPartEnd);

        // Is there already a Python dictionary object with the given name?
        // Request the Python dictionary (results in borrowed reference, don't use Py_DECREF on it)
        PyObject *pNestedPythonDictionary = PyDict_GetItemString(pPythonDictionary, sSubsNamespaceName);
        if (pNestedPythonDictionary) {
            // There's already an Python object with the given name - Must be a Python dictionary object...
            if (PyDict_Check(pNestedPythonDictionary)) {
                // Go down the rabbit hole...
                return AddPythonFunction(pNestedPythonDictionary, sFunction, pPythonFunction, sNamespace.GetSubstring(nPartEnd + 1));
            } else {
                // Error!
                return false;
            }
        } else {
            // Create the Python dictionary object (results in new reference, use Py_DECREF on the result)
            pNestedPythonDictionary = PyDict_New();

            // Add the new Python dictionary object to the current one
            if (PyDict_SetItemString(pPythonDictionary, sSubsNamespaceName, pNestedPythonDictionary) == -1) {
                // Remove our reference from the Python dictionary object
                Py_DECREF(pNestedPythonDictionary);

                // Error!
                return false;
            }

            // Go down the rabbit hole...
            const bool bResult = AddPythonFunction(pNestedPythonDictionary, sFunction, pPythonFunction, sNamespace.GetSubstring(nPartEnd + 1));

            // Remove our reference from the Python dictionary object
            Py_DECREF(pNestedPythonDictionary);

            // Done
            return bResult;
        }
    } else {
        // Jap, now add the given Python function object to the current Python dictionary object
        if (PyDict_SetItemString(pPythonDictionary, sFunction, pPythonFunction) == -1) {
            // Error!
            return false;
        }
    }

    // Done
    return true;
}
Пример #19
0
void CExifInterface::LoadAttributes() // throws IOException
{
    // format of string passed from native C code:
    // "attrCnt attr1=valueLen value1attr2=value2Len value2..."
    // example:
    // "4 attrPtr ImageLength=4 1024Model=6 FooImageWidth=4 1280Make=3 FOO"

    mAttributes.Clear();

    String attrStr;
    synchronized(sLock) {
        attrStr = GetAttributesNative(mFilename);
    }

    // get count
    Int32 ptr = attrStr.IndexOf(' ');
    Int32 count = StringUtils::ParseInt32(attrStr.Substring(0, ptr));
    // skip past the space between item count and the rest of the attributes
    ++ptr;

    Int32 equalPos, lenPos, attrLen;
    String attrName, attrValue;
    for (Int32 i = 0; i < count; i++) {
        // extract the attribute name
        equalPos = attrStr.IndexOf('=', ptr);
        attrName = attrStr.Substring(ptr, equalPos);
        ptr = equalPos + 1;     // skip past =

        // extract the attribute value length
        lenPos = attrStr.IndexOf(' ', ptr);
        attrLen = StringUtils::ParseInt32(attrStr.Substring(ptr, lenPos));
        ptr = lenPos + 1;       // skip pas the space

        // extract the attribute value
        attrValue = attrStr.Substring(ptr, ptr + attrLen);
        ptr += attrLen;

        if (attrName.Equals("hasThumbnail")) {
            mHasThumbnail = attrValue.EqualsIgnoreCase(String("true"));
        }
        else {
            mAttributes[attrName] = attrValue;
        }
    }
}
Пример #20
0
String URLUtil::StripAnchor(
    /* [in] */ const String& url)
{
    Int32 anchorIndex = url.IndexOf('#');
    if (anchorIndex != -1) {
        return url.Substring(0, anchorIndex);
    }
    return url;
}
Пример #21
0
/**
*  @brief
*    Loads a resource which type has to be evaluated internally
*/
bool Application::LoadResource(const String &sFilename, const String &sType)
{
	bool bResult = false;	// Error by default

	// Clear the scene, after calling this method the scene is empty
	ClearScene();

	// Destroy the currently used script
	DestroyScript();

	// Backup the filename of the current resource
	m_sResourceFilename = sFilename;

	// Is there anything to load in?
	if (sFilename.GetLength()) {
		{ // Make the directory of the scene to load in to the current directory

			// Ok, the next thing is tricky, and every solution will end up in being a hack due to lack of information.
			// Within materials, meshes etc. there are usually relative paths provided, no absolute (not just true for PixelLight file formats).
			// Further, those paths are usually relative to a project root resulting e.g. within a default directory layout like
			// - Root
			//   - Data
			//     - Meshes
			//     - Materials
			// For "normal" projects this is no issue because everything is usually relative to the root project directory...
			// ... but this viewer must be able to pick out e.g. a mesh out of nowhere and must still be able to locate the required
			// other resources like materials. So, in here, we can only work with heuristics... this can and will of course go from
			// time to time horribly wrong...

			// First try: Find the first "Data" occurrence with the given filename and hope that it's the project root directory

			// Get filename as clean URL
			Url cUrl = Url(sFilename);
			cUrl.Collapse();

			// Get the first part of the path, and then look for "Data"
			uint32 nPathPos = 0;
			String sPart = cUrl.GetFirstPath(nPathPos);
			while (sPart != "Data" && sPart.GetLength())
				sPart = cUrl.GetNextPath(nPathPos);
			if (sPart == "Data") {
				// Set the base directory of the application
				SetBaseDirectory(cUrl.GetRoot() + cUrl.GetPath().GetSubstring(0, nPathPos - 5));	// -5 = Remove "Data/"
			} else {
				// Second try: Cut of "/Data/Scenes/" and hope that it's the project root directory.
				// If it's not there, take the directory the given resource is in.

				// Validate path
				const String sDirectory = cUrl.CutFilename();

				// Search for "/Data/Scenes/" and get the prefix of that, in case it's not there just use directly the scene directory
				const int nIndex = sDirectory.IndexOf("/Data/Scenes/");

				// Set the base directory of the application
				SetBaseDirectory("file://" + ((nIndex >= 0) ? sDirectory.GetSubstring(0, nIndex) : sDirectory) + '/');
			}
		}
Пример #22
0
//===============================================================
//UEventObserver::UEvent
//===============================================================
UEventObserver::UEvent::UEvent(
    /* [in] */ const String& message)
{
    Int32 offset = 0;
    Int32 length = message.GetLength();
    Int32 equals, at;
    while (offset < length) {
        equals = message.IndexOf(String("="), offset);
        at = message.IndexOf(String("\0"), offset);
        if (at < 0) break;

        if (equals > offset && equals < at) {
            // key is before the equals sign, and value is after
            mMap[message.Substring(offset, equals)] = message.Substring(equals + 1, at);
        }

        offset = at + 1;
    }
}
Пример #23
0
String StringBlock::Subtag(
    /* [in] */ const String& full,
    /* [in] */ const String& attribute)
{
    Int32 start = full.IndexOf(attribute);
    if (start < 0) {
        return String(NULL);
    }

    start += attribute.GetLength();
    Int32 end = full.IndexOf(';', start);

    if (end < 0) {
        return full.Substring(start);
    }
    else {
        return full.Substring(start, end);
    }
}
Пример #24
0
ECode CQName::ValueOf(
    /* [in] */ String qNameAsString,
    /* [out] */  IQName** qName)
{
    // null is not valid
    if (qNameAsString == NULL) {
        // throw new IllegalArgumentException("cannot create QName from \"null\" or \"\" String");
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
    }

    // "" local part is valid to preserve compatible behavior with QName 1.0
    if (qNameAsString.GetLength() == 0) {
        return CQName::New(
            IXMLConstants::NULL_NS_URI,
            qNameAsString,
            IXMLConstants::DEFAULT_NS_PREFIX,
            qName);
    }

    // local part only?
    if (qNameAsString.GetChar(0) != '{') {
        return CQName::New(
            IXMLConstants::NULL_NS_URI,
            qNameAsString,
            IXMLConstants::DEFAULT_NS_PREFIX,
            qName);
    }

    // Namespace URI improperly specified?
    if (qNameAsString.StartWith(String("{") + IXMLConstants::NULL_NS_URI + "}")) {
        // throw new IllegalArgumentException(
        //     "Namespace URI .equals(XMLConstants.NULL_NS_URI), "
        //     + ".equals(\"" + XMLConstants.NULL_NS_URI + "\"), "
        //     + "only the local part, "
        //     + "\"" + qNameAsString.substring(2 + XMLConstants.NULL_NS_URI.length()) + "\", "
        //     + "should be provided.");
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
    }

    // Namespace URI and local part specified
    Int32 endOfNamespaceURI = qNameAsString.IndexOf('}');
    if (endOfNamespaceURI == -1) {
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
        // throw new IllegalArgumentException(
        //     "cannot create QName from \""
        //         + qNameAsString
        //         + "\", missing closing \"}\"");
    }
    return CQName::New(
        qNameAsString.Substring(1, endOfNamespaceURI),
        qNameAsString.Substring(endOfNamespaceURI + 1),
        IXMLConstants::DEFAULT_NS_PREFIX,
        qName);
}
std::vector<String> String::Split(String sep) const
{
    if (sep == Empty)
        sep = " ";

    String tmp = *this;
    std::vector<String> ret;

    int pos = tmp.IndexOf(sep);
    while (pos >= 0)
    {
        ret.push_back(tmp.Substring(0, pos));
        tmp = tmp.Substring(pos + sep.Length());
        pos = tmp.IndexOf(sep);
    }

    ret.push_back(tmp);

    return ret;
}
Пример #26
0
ECode CModuleInfo::GetEnumInfo(
    /* [in] */ const String& fullName,
    /* [out] */ IEnumInfo** enumInfo)
{
    if (fullName.IsNull() || !enumInfo) {
        return E_INVALID_ARGUMENT;
    }

    if (!mClsMod->mEnumCount) {
        return E_DOES_NOT_EXIST;
    }

    ECode ec = AcquireEnumList();
    if (FAILED(ec)) return ec;

    Int32 start = fullName.IndexOf('L');
    Int32 end = fullName.IndexOf(';');
    String strName = fullName.Substring(start >= 0 ? start + 1 : 0, end > 0 ? end : fullName.GetLength()).Replace('/', '.');
    return mEnumList->AcquireObjByName(strName, (IInterface **)enumInfo);
}
Пример #27
0
static status_t ParseConnectArgAux(const String & s, uint32 startIdx, uint16 & retPort, bool portRequired)
{
   const int32 colIdx = s.IndexOf(':', startIdx);
   const char * pStr = (colIdx>=0)?(s()+colIdx+1):NULL;
   if ((pStr)&&(muscleInRange(*pStr, '0', '9')))
   {
      const uint16 p = (uint16) atoi(pStr);
      if (p > 0) retPort = p;
      return B_NO_ERROR;
   }
   else return portRequired ? B_ERROR : B_NO_ERROR;
}
Пример #28
0
ECode CKXmlSerializer::WriteAttribute(
    /* [in] */ const String& _ns,
    /* [in] */ const String& name,
    /* [in] */ const String& value)
{
    String ns = _ns;
    if (!mPending) {
//        throw new IllegalStateException("illegal position for attribute");
        return E_ILLEGAL_STATE_EXCEPTION;
    }

    //        int cnt = nspCounts[depth];

    if (ns.IsNull()) {
        ns = "";
    }

    //        depth--;
    //        pending = false;

    String prefix("");
    if (!ns.IsEmpty()) {
        FAIL_RETURN(GetPrefix(ns, FALSE, TRUE, &prefix));
    }

    //        pending = true;
    //        depth++;

    /*        if (cnt != nspCounts[depth]) {
                mWriter.write(' ');
                mWriter.write("xmlns");
                if (nspStack[cnt * 2] != null) {
                    mWriter.write(':');
                    mWriter.write(nspStack[cnt * 2]);
                }
                mWriter.write("=\"");
                writeEscaped(nspStack[cnt * 2 + 1], '"');
                mWriter.write('"');
            }
            */

    FAIL_RETURN(IWriter::Probe(mWriter)->Write(' '));
    if (!prefix.IsEmpty()) {
        FAIL_RETURN(IWriter::Probe(mWriter)->Write(prefix));
        FAIL_RETURN(IWriter::Probe(mWriter)->Write(':'));
    }
    FAIL_RETURN(IWriter::Probe(mWriter)->Write(name));
    FAIL_RETURN(IWriter::Probe(mWriter)->Write('='));
    Char32 q = value.IndexOf('"') == -1 ? '"' : '\'';
    FAIL_RETURN(IWriter::Probe(mWriter)->Write(q));
    FAIL_RETURN(WriteEscaped(value, q));
    return IWriter::Probe(mWriter)->Write(q);
}
String SQLiteDatabaseConfiguration::StripPathForLogs(
    /* [in] */ const String& path)
{
    if (path.IndexOf('@') == -1) {
        return path;
    }
    AutoPtr<IMatcher> matcher;
    EMAIL_IN_DB_PATTERN->Matcher(path, (IMatcher**)&matcher);
    String result;
    matcher->ReplaceAll(String("XX@YY"), &result);
    return result;
}
Пример #30
0
String SystemLinux::GetLocaleLanguage() const
{
	// Get the locale
	const char *pszSaveLocale = setlocale(LC_ALL, nullptr);
	setlocale(LC_ALL, "");
	const String sLocal = setlocale(LC_ALL, nullptr);
	setlocale(LC_ALL, pszSaveLocale);

	// Find the '_'
	const int nIndex = sLocal.IndexOf("_");
	return (nIndex >= 0) ? sLocal.GetSubstring(0, nIndex) : "";
}