int LPID::SetPartName( const STRING& aPartName )
{
    STRING  category;
    STRING  base;
    int     offset;
    int     separation = int( aPartName.find_first_of( "/" ) );

    if( separation != -1 )
    {
        category = aPartName.substr( 0, separation );
        base     = aPartName.substr( separation+1 );
    }
    else
    {
        // leave category empty
        base = aPartName;
    }

    if( (offset = SetCategory( category )) != -1 )
        return offset;

    if( (offset = SetBaseName( base )) != -1 )
    {
        return offset + separation + 1;
    }

    return -1;
}
Exemple #2
0
bool JustRenderIt::ResourceManager::GetResourcePath(STRING& filename,
                                                    STRING folderName)
{
  Trim(filename);
  Trim(folderName);
  if(folderName[folderName.length()-1] == '/' ||
     folderName[folderName.length()-1] == '\\' )
    folderName = folderName.substr(0, folderName.length()-1);
  if(folderName[0] == '/')
    folderName = folderName.substr(1, folderName.length()-1);

  if(!FileExists(filename))
  {
    STRING newfilename = "../resources/";
    newfilename += folderName + "/" + filename;
    if(!FileExists(newfilename))
    {
      char str[256];
      sprintf(str, "Couldn't open \"%s\"", filename.c_str());
      LOG_ERROR1(str);
      return false;
    }
    filename = newfilename;
  }
  return true;
}
Exemple #3
0
// Break up a string composed of multiple sections in parentheses into a collection
// of sub-strings. Sample input string: (Hello)(World1,World2)
MgStringCollection* WfsGetFeatureParams::GetParenthesisedList(CREFSTRING sourceString)
{
    MgStringCollection* stringList = new MgStringCollection();
    if(sourceString.length() > 0)
    {
        // Create a collection of strings
        STRING remaining = MgUtil::Trim(sourceString);
        while(remaining.length() > 0)
        {
            STRING::size_type openParenthesis = remaining.find_first_of(L"(");
            if(openParenthesis != string::npos)
            {
                STRING::size_type closeParenthesis = remaining.find_first_of(L")");
                if(closeParenthesis != string::npos)
                {
                    STRING thisString = remaining.substr(openParenthesis + 1, closeParenthesis - openParenthesis - 1);
                    stringList->Add(thisString);
                    remaining = remaining.substr(closeParenthesis + 1);
                }
            }
            else
            {
                stringList->Add(remaining);
                break;
            }
        }
    }
    return stringList;
}
Exemple #4
0
CKT::CVersion::CVersion(STRING version)
{
	int iPoint = version.find('.');
	STRING sTemp = version.substr(0, iPoint);
	m_byMajor = (BYTE)toInt(sTemp.c_str());

	sTemp = version.substr(iPoint + 1, version.length() - iPoint);
	m_byMinor = (BYTE)toInt(sTemp.c_str());
}
void OSInterface::DeleteFilesFromDirectory(const STRING& aRootDir,const STRING& aExtension)                    
	{
	STRING			patternOfString;
	WIN32_FIND_DATA fileInfo;
    patternOfString = aRootDir + _T("\\*.*") ;
	
	HANDLE hToFile = ::FindFirstFile(patternOfString.c_str(), &fileInfo);	
	
	if(hToFile != INVALID_HANDLE_VALUE)
		{
		do
			{
			if(fileInfo.cFileName[0] != '.')
				{
				
				STRING file = fileInfo.cFileName;
				
				STRING extOfString = file.substr(file.rfind(_T(".")) + 1);

				if(extOfString == aExtension)
					{
					::DeleteFile(file.c_str());
					}
				}		
			}while(::FindNextFile(hToFile , &fileInfo));

		::FindClose(hToFile);
	  	}
	}
Exemple #6
0
void MgWmsLayerDefinitions::GenerateDefinitions(MgUtilDictionary& Dictionary)
{
    MgXmlSynchronizeOnElement ResourceDocument(*m_xmlParser,_("ResourceDocument"));
    if(!ResourceDocument.AtBegin())
        return; // Something is wrong.  We leave.

    while(!ResourceDocument.AtEnd()) {
        STRING sValue; // basic_string
        if(GetElementContents(_("ResourceId"),sValue)) {
            // Okay, the ResourceId is too decorated for our purposes;
            // the outside world doesn't need to know (and clutter up
            // URL command lines with) this syntactic "punctuation" so
            // we just get rid of it.
            // Remove the Library prefix, if present.
            if(sValue.find(_("Library://")) == 0)
                sValue = sValue.substr(10);
            // Remove the LayerDefinition suffix, if present.
            STRING::size_type iEnd = sValue.find(_(".LayerDefinition"));
            if(iEnd != STRING::npos)
                sValue.resize(iEnd);
            // There, that's our Layer Name.
            Dictionary.AddDefinition(_("Layer.Name"),sValue);

            // Until we have "Friendly Name" support, the
            // friendly name will simply be the layer name sans
            // path.
            iEnd = sValue.find_last_of('/');
            if(iEnd != STRING::npos)
                sValue = sValue.substr(iEnd+1); // one past the slash.

            // That's our Layer Title,
            // Note that subsequently-found metadata may override this
            // definition with a real title... one that the user actually
            // wants.  This just provides a default in case no such
            // friendly name exists.... that keeps the list of layer names
            // from being a list of empty strings.
            Dictionary.AddDefinition(_("Layer.Title"),sValue);
        }
        else if(!GetMetadataDefinitions(Dictionary)) {
          SkipElement(NULL);
        }
    }

}
Exemple #7
0
/*
 * Remove the path from a file name, perserving folders.
 * preserveFrom should carry a trailing \.
 */
STRING removePath(const STRING str, const STRING preserveFrom)
{
	const int pos = str.find(preserveFrom);
	if (pos != str.npos)
	{
		return str.substr(pos + preserveFrom.length());
	}
	// Return the path unaltered, since it didn't contain the
	// default folder and any other folders should be subfolders
	// (although a different default folder may be present).
	return str;
}
Exemple #8
0
static void trim(STRING& str)
{
    static const WCHAR Spaces[] = L" \t\r\n";
    size_t i = str.find_first_not_of(Spaces);
    size_t j = str.find_last_not_of(Spaces);
    if (i == STRING::npos || j == STRING::npos)
    {
        str.clear();
    }
    else
    {
        str = str.substr(i, j - i + 1);
    }
}
const std::vector <STRING>  OSInterface::ExtractFilesFromDirectory(const STRING& aRootDir,const STRING& aExtension)                    
	{
	STRING			pathOfFile;
	STRING			patternOfString;
	WIN32_FIND_DATA fileInfo;

    patternOfString = aRootDir + _T("\\*.*") ;

	HANDLE hToFile = ::FindFirstFile(patternOfString.c_str(), &fileInfo);	
	
	std::vector<STRING> aDirFiles;

	if(hToFile != INVALID_HANDLE_VALUE)
		{
		do
			{
			if(fileInfo.cFileName[0] != '.')
				{
				pathOfFile.erase();
				
				pathOfFile = aRootDir + _T("\\")+ fileInfo.cFileName;
				STRING file = fileInfo.cFileName;
								
				STRING extOfString = file.substr(file.rfind(_T(".")) + 1);
				
				if(aExtension.length())
					{
					if(extOfString == aExtension)
						{
						aDirFiles.push_back(pathOfFile);
						}
					}
				else
					{
					bool valid = IsInteger(file);
					if(valid)
						{
						aDirFiles.push_back(pathOfFile);
						}
					}
				}
			}while(::FindNextFile(hToFile , &fileInfo));

		::FindClose(hToFile);
	  	}
	return aDirFiles;
	}
Exemple #10
0
// Get file name from path
STRING Port::FileName(STRING file)
{
#ifdef WIN32
#ifdef UNICODE
	int pos = file.find_last_of(L"\\") + 1;
#else
	int pos = file.find_last_of("\\") + 1;
#endif
#elif defined(UNIX)
#ifdef UNICODE
	int pos = file.find_last_of(L"/") + 1;
#else
	int pos = file.find_last_of("/") + 1;
#endif
#endif
	return file.substr(pos);
}
Exemple #11
0
/*! 
// \param char * str : 
// \param int offset : 
// \param SDL_Surface* screen : 
*/
void cCredits::draw_textFontM(char* pstrLine, int offset, SDL_Surface* screen)
{
	ASSERT(m_pMainFont);

    int tx, ty;
	TTF_SizeText(m_pMainFont,pstrLine, &tx, &ty);
	int iY = screen->h - (offset * ty);
	SDL_Rect trect;
	STRING strLayout = pstrLine;
	STRING strRes = strLayout;
	size_t iLen = strRes.length(); 
	if (pstrLine[0] == '-')
	{
		// highlight
		// eat '-'
		strRes = strLayout.substr(1,iLen - 1); 
		trect.y= iY - 2;
		//trect.x =  (screen->w/2 - ((int)strRes.size()*tx + 3)/2) - 4;
        trect.x =  (screen->w  - tx)/ 2;
		//trect.w = (int)strRes.size()*tx + 8;
        trect.w = tx;
		trect.h = ty + 4;
        SDL_Rect rctBox = trect;
        rctBox.x -= 4;
        rctBox.w += 4;
		Uint32 tcolor = SDL_MapRGBA(screen->format, 128, 0, 0,255);
		SDL_FillRect(screen,&rctBox,tcolor);
	}
	else
	{
		trect.y= iY - 2;
		trect.x =  (screen->w  - tx)/ 2;
		
	}
    GFX_UTIL::DrawString(screen, strRes.c_str(), trect.x, 
                                trect.y, m_colCurrent, m_pMainFont,false);

}
Exemple #12
0
/*
 * Trim whitespace from the sides of a string.
 *
 * str (in) - string to trim
 * return (out) - trimmed string
 */
STRING parser::trim(const STRING &str)
{
	const int len = str.length();
	if (len == 0) return _T("");
	int start = -1, end = -1;
	for (int i = 0; i < len; i++)
	{
		if (str[i] != _T(' ') && str[i] != _T('\t'))
		{
			start = i;
			break;
		}
	}
	if (start == -1) return _T("");
	for (int j = len - 1; j >= 0; j--)
	{
		if (str[j] != _T(' ') && str[j] != _T('\t'))
		{
			end = j + 1 - start;
			break;
		}
	}
	return str.substr(start, end);
}
Exemple #13
0
bool MgWmsLayerDefinitions::GetMetadataDefinitions(MgUtilDictionary& Dictionary)
{
//    STRING sDebug = m_xmlParser->Current().Contents();
    // We're looking for a <ResourceDocumentHeader ...>
    MgXmlSynchronizeOnElement ElementResourceDocumentHeader(*m_xmlParser,_("ResourceDocumentHeader"));
    if(!ElementResourceDocumentHeader.AtBegin())
        return false;

    // And inside that, there's a <Metadata ...>
    MgXmlSynchronizeOnElement ElementMetadata(*m_xmlParser,_("Metadata"));
    if(!ElementMetadata.AtBegin())
        return false;

    // And inside *that*, we hope there's a <Simple...>
    MgXmlSynchronizeOnElement ElementSimple(*m_xmlParser,_("Simple"));
    if(!ElementSimple.AtBegin())
        return false;

    // And once we're here, we hope to find a grunch of <Property...> elements
    while(!ElementSimple.AtEnd()) {
        MgXmlSynchronizeOnElement ElementProperty(*m_xmlParser,_("Property"));
        if(ElementProperty.AtBegin()) {
            // Each of which consist of <Name> and <Value> pairs...
            STRING sName;
            STRING sValue;
            if(GetElementContents(_("Name"),sName) && GetElementContents(_("Value"),sValue)) {
                STRING sDefinitionName =  _("Layer.");
                // Present the names slightly differently than internal representation.
                // System-defined metadata is published with an underscore prefix.  We
                // publish this without the underscore: "_Bounds" -> "Layer.Bounds".
                // User-defined metadata will not have the underscore, and we present
                // this for consumption as "Layer.user.Whatever" -- just to make sure
                // that the user and system namespaces remain distinct.
                if(sName[0] == '_')
                    sDefinitionName += sName.substr(1);
                else
                    sDefinitionName += _("user.") + sName;

                //----------------------------------------------------------------------
                // If it starts and ends with escaped angled brackets, let's assume it's
                // "corrupted" XML that simply needs unescaping.
                //
                // TODO: This is not meant to be a long-term solution; it just overcomes
                // a current schema restriction on metadata consisting of mixed content.
                STRING::size_type iLt =sValue.find(_("&lt;"));
                STRING::size_type iGt = sValue.rfind(_("&gt;"));
                STRING::size_type iLen = sValue.length();
                if(sValue.find(_("&lt;")) == 0 && sValue.rfind(_("&gt;")) == sValue.length() - 4) {
                  STRING::size_type iPos;
                  while((iPos = sValue.find(_("&lt;")))  != STRING::npos)
                    sValue = sValue.substr(0,iPos) + _("<") + sValue.substr(iPos+4);
                  while((iPos = sValue.find(_("&gt;")))  != STRING::npos)
                    sValue = sValue.substr(0,iPos) + _(">") + sValue.substr(iPos+4);
                  while((iPos = sValue.find(_("\x201d")))  != STRING::npos)
                    sValue = sValue.substr(0,iPos) + _("\"") + sValue.substr(iPos+1);
                }
                //----------------------------------------------------------------------

                Dictionary.AddDefinition(sDefinitionName,sValue);
            }
        }
    }

    return true;
}
/// <summary>
/// Executes the specific request.
/// </summary>
/// <returns>
/// MgHttpResponse
/// This contains the response (including MgHttpResult and StatusCode) from the server.
/// </returns>
void MgHttpWfsDescribeFeatureType::Execute(MgHttpResponse& hResponse)
{
    Ptr<MgHttpResult> hResult = hResponse.GetResult();

    MG_HTTP_HANDLER_TRY()

    // We have to wrap the request parameters, since the outside
    // world is case-sensitive (with respect to names,) but
    // we need our parameters NOT to be so.
    Ptr<MgHttpRequestParam> origReqParams = m_hRequest->GetRequestParam();
    MgHttpRequestParameters Parms(origReqParams);
    MgHttpResponseStream Out;

    MgOgcServer::SetLoader(GetDocument);

    MgUserInformation::SetCurrentUserInfo(m_userInfo);

    // Instance a server-lette
    MgOgcWfsServer Wfs(Parms,Out);

    // Determine required feature types
    CPSZ pszFeatureTypes = Wfs.RequestParameter(MgHttpResourceStrings::reqWfsTypeName.c_str());
    STRING sFeatureTypes = pszFeatureTypes? pszFeatureTypes : _("");
    Ptr<MgStringCollection> featureTypeList;
    if(sFeatureTypes.empty())
    {
        featureTypeList = NULL;
    }
    else
    {
        featureTypeList = MgStringCollection::ParseCollection(sFeatureTypes, L",");
    }

    Ptr<MgResourceService> pResourceService = (MgResourceService*)(CreateService(MgServiceType::ResourceService));
    Ptr<MgFeatureService> pFeatureService = (MgFeatureService*)(CreateService(MgServiceType::FeatureService));

    // Retrieve feature definitions
    auto_ptr<MgWfsFeatureDefinitions> pFeatureTypes;
    if(NULL == featureTypeList)
    {
        pFeatureTypes.reset(new MgWfsFeatureDefinitions(pResourceService,pFeatureService));
    }
    else
    {
        pFeatureTypes.reset(new MgWfsFeatureDefinitions(pResourceService,pFeatureService,featureTypeList));
    }
    Wfs.SetFeatureDefinitions(pFeatureTypes.get());

    // In order to validate request we have to invoke the ProcessRequest
    if(!Wfs.ProcessRequest(this))
    {
        // Obtain the response byte reader
        Ptr<MgByteReader> errorResponse = Out.Stream().GetReader();

        // Set the result
        hResult->SetResultObject(errorResponse, errorResponse->GetMimeType());
        return;
    }

    // Determine required output format
    // This part must behind the Wfs.ProcessRequest, where parameters have been validated.
    CPSZ pszOutputFormat = Wfs.RequestParameter(MgHttpResourceStrings::reqWfsOutputFormat.c_str());
    STRING sOutputFormat = pszOutputFormat? pszOutputFormat : _("");
    if(sOutputFormat.empty())
    {
        sOutputFormat = Wfs.GetDefaultDescribeFeatureTypeOutputFormat(STRING(Wfs.RequestParameter(MgHttpResourceStrings::reqWfsVersion.c_str())));
    }

    if(pFeatureTypes->InSameNamespace()) 
    {
        STRING sPrefix = L"";
        STRING sUrl = L"";
        STRING sResource = L""; // TODO: look for this in arg, since POST may put it there to save us trouble.
        STRING sSchemaHash = L"";
        Ptr<MgResourceIdentifier> idResource;
        Ptr<MgStringCollection> pFeatureClasses = new MgStringCollection();

        while(pFeatureTypes->ReadNext())
        {
            STRING sClassFullName = pFeatureTypes->GetClassFullName();
            
            if(!sFeatureTypes.empty() && STRING::npos == sFeatureTypes.find(sClassFullName))
            {
                continue;
            }

            STRING::size_type iPos = sClassFullName.find(_(":")); //NOXLATE
            if(iPos != STRING::npos)
            {
                if(sPrefix.empty())
                {
                    sPrefix = sClassFullName.substr(0,iPos);
                }

                STRING sClass = sClassFullName.substr(iPos+1);

                sUrl = pFeatureTypes->GetNamespaceUrl();

                if(NULL == idResource)
                {
                    if(pFeatureTypes->PrefixToFeatureSource(sPrefix, sResource, sSchemaHash)) {
                        idResource = new MgResourceIdentifier(sResource);
                    }
                    else
                    {
                        // Badly formed feature type?  Throw an exception.
                        GenerateTypeNameException(hResult,sFeatureTypes);
                        return;
                    }
                }

                pFeatureClasses->Add(((sSchemaHash.size()==0) ? sClass : sSchemaHash + _(":") + sClass)); //NOXLATE
            }
            else {
                // Badly formed feature type?  Throw an exception.
                GenerateTypeNameException(hResult,sFeatureTypes);
                return;
            }
        }

        if(pFeatureClasses->GetCount() == 0)
        {
            // Badly formed feature type?  Throw an exception.
            GenerateTypeNameException(hResult,sFeatureTypes);
            return;
        }

        Ptr<MgByteReader> response  = pFeatureService->DescribeWfsFeatureType(idResource, pFeatureClasses, sPrefix, sUrl);

        // Set the result
        hResult->SetResultObject(response, sOutputFormat);
    }
    else {
        // There's more than one feature, so we need to enumerate
        // them and have each get imported.
        //
        if(!pFeatureTypes->SubsetFeatureList(sFeatureTypes.c_str()))
            GenerateTypeNameException(hResult,sFeatureTypes);
        else {

#ifdef _WFS_LOGGING
            MyLog.Write(_("WFS::DescribeFeatureType\r\n"));
#endif
            // Execute the request
            //Wfs.ProcessRequest(this);

            // Slurp the results.
            Ptr<MgByteReader> capabilities = Out.Stream().GetReader();

            // Set the result
            hResult->SetResultObject(capabilities, capabilities->GetMimeType());
        }
    }

    MG_HTTP_HANDLER_CATCH_AND_THROW_EX(L"MgHttpWfsDescribeFeatureType.Execute")
}
STRING LPID::Format( const STRING& aLogicalLib, const STRING& aPartName, const STRING& aRevision )
    throw( PARSE_ERROR )
{
    STRING  ret;
    int     offset;

    if( aLogicalLib.size() )
    {
        offset = okLogical( aLogicalLib );
        if( offset != -1 )
        {
            THROW_PARSE_ERROR(
                    _( "Illegal character found in logical lib name" ),
                    wxString::FromUTF8( aLogicalLib.c_str() ),
                    aLogicalLib.c_str(),
                    0,
                    offset
                    );
        }
        ret += aLogicalLib;
        ret += ':';
    }

    {
        STRING  category;
        STRING  base;

        int separation = int( aPartName.find_first_of( "/" ) );

        if( separation != -1 )
        {
            category = aPartName.substr( 0, separation );
            base     = aPartName.substr( separation+1 );
        }
        else
        {
            // leave category empty
            base = aPartName;
        }

        if( (offset = okCategory( category )) != -1 )
        {
            THROW_PARSE_ERROR(
                    _( "Illegal character found in category" ),
                    wxString::FromUTF8( aRevision.c_str() ),
                    aRevision.c_str(),
                    0,
                    offset
                    );
        }

        if( (offset = okBase( base )) != -1 )
        {
            THROW_PARSE_ERROR(
                    _( "Illegal character found in base name" ),
                    wxString::FromUTF8( aRevision.c_str() ),
                    aRevision.c_str(),
                    0,
                    offset + separation + 1
                    );
        }

        if( category.size() )
        {
            ret += category;
            ret += '/';
        }

        ret += base;
    }

    if( aRevision.size() )
    {
        offset = okRevision( aRevision );
        if( offset != -1 )
        {
            THROW_PARSE_ERROR(
                    _( "Illegal character found in revision" ),
                    wxString::FromUTF8( aRevision.c_str() ),
                    aRevision.c_str(),
                    0,
                    offset
                    );
        }

        ret += '/';
        ret += aRevision;
    }

    return ret;
}
Exemple #16
0
/*
 * Render a particular frame to a canvas.
 */
bool CAnimation::renderAnmFrame(CCanvas *cnv, unsigned int frame)
{
	extern STRING g_projectPath;

    cnv->ClearScreen(TRANSP_COLOR);

	// Wrap around.
    frame %= m_data.frameCount;

	const STRING frameFile = m_data.frameFiles[frame];

    if (frameFile.empty()) return false;

	const STRING ext = parser::uppercase(getExtension(frameFile));
    if (ext == _T("TBM") || ext.substr(0, 3) == _T("TST") || ext == _T("GPH"))
	{
		TILE_BITMAP tbm;

		if (ext == _T("TBM"))
		{
			if (!tbm.open(g_projectPath + BMP_PATH + frameFile)) return false;
		}
		else
		{
			// Set up a 1x1 tile bitmap.
			tbm.resize(1, 1);
			tbm.tiles[0][0] = frameFile;
		}

        // Draw the tilebitmap and mask to new canvases.
		const int w = tbm.width * 32, h = tbm.height * 32;
		CCanvas cnvTbm, cnvMaskTbm;
		cnvTbm.CreateBlank(NULL, w, h, TRUE);
		cnvMaskTbm.CreateBlank(NULL, w, h, TRUE);

		if (tbm.draw(&cnvTbm, &cnvMaskTbm, 0, 0))
		{
			// Stretch the canvas and mask to an intermediate canvas.
			CCanvas cnvInt;
			cnvInt.CreateBlank(NULL, w, h, TRUE);
			cnvInt.ClearScreen(m_data.transpColors[frame]);

			cnvTbm.BltStretchMask(
				&cnvMaskTbm,
				&cnvInt,
				0, 0, 
				0, 0,
				w, h, 
				m_data.pxWidth, m_data.pxHeight
			);
			// Blt to the target canvas.
			cnvInt.BltTransparent(cnv, 0, 0, m_data.transpColors[frame]);
		}
	}
	else
	{
		// Image file.
		const STRING strFile = resolve(g_projectPath + BMP_PATH + frameFile);
		FIBITMAP *bmp = FreeImage_Load(
			FreeImage_GetFileType(getAsciiString(strFile).c_str(), 16), 
			getAsciiString(strFile).c_str()
		);

        CCanvas cnvImg;
		cnvImg.CreateBlank(NULL, m_data.pxWidth, m_data.pxHeight, TRUE);
		
		CONST HDC hdc = cnvImg.OpenDC();
		StretchDIBits(
			hdc, 
			0, 0, 
			m_data.pxWidth, m_data.pxHeight, 
			0, 0, 
			FreeImage_GetWidth(bmp), 
			FreeImage_GetHeight(bmp), 
			FreeImage_GetBits(bmp), 
			FreeImage_GetInfo(bmp), 
			DIB_RGB_COLORS, 
			SRCCOPY
		);
		FreeImage_Unload(bmp);
		cnvImg.CloseDC(hdc);

		// Apply ambient level.
		extern AMBIENT_LEVEL g_ambientLevel;
		if (g_ambientLevel.color)
		{
			CCanvas cnvAl;
			cnvAl.CreateBlank(NULL, m_data.pxWidth, m_data.pxHeight, TRUE);
			cnvAl.ClearScreen(g_ambientLevel.color);
			cnvAl.BltAdditivePart(cnvImg.GetDXSurface(), 0, 0, 0, 0, m_data.pxWidth, m_data.pxHeight, g_ambientLevel.sgn, -1, m_data.transpColors[frame]);
		}

		cnvImg.BltTransparent(cnv, 0, 0, m_data.transpColors[frame]);

    } // if (ext == TBM)
	return true;
}
int LPID::Parse( const STRING& aLPID )
{
    clear();

    const char* rev = EndsWithRev( aLPID );
    size_t      revNdx;
    size_t      partNdx;
    size_t      baseNdx;
    int         offset;

    //=====<revision>=========================================
    if( rev )
    {
        revNdx = rev - aLPID.c_str();

        // no need to check revision, EndsWithRev did that.
        revision = aLPID.substr( revNdx );
        --revNdx;  // back up to omit the '/' which preceeds the rev
    }
    else
        revNdx = aLPID.size();

    //=====<logical>==========================================
    if( ( partNdx = aLPID.find( ':' ) ) != aLPID.npos )
    {
        offset = SetLogicalLib( aLPID.substr( 0, partNdx ) );
        if( offset > -1 )
        {
            return offset;
        }
        ++partNdx;  // skip ':'
    }
    else
        partNdx = 0;

    //=====<rawName && category>==============================
    // "length limited" search:
    const char* base = (const char*) memchr( aLPID.c_str() + partNdx, '/', revNdx - partNdx );

    if( base )
    {
        baseNdx  = base - aLPID.c_str();
        offset  = SetCategory( aLPID.substr( partNdx, baseNdx - partNdx ) );
        if( offset > -1 )
        {
            return offset + partNdx;
        }
        ++baseNdx;   // skip '/'
    }
    else
    {
        baseNdx = partNdx;
    }

    //=====<baseName>==========================================
    offset = SetBaseName( aLPID.substr( baseNdx, revNdx - baseNdx ) );
    if( offset > -1 )
    {
        return offset + baseNdx;
    }

    return -1;
}
Exemple #18
0
// Remove the path from a file name.
STRING removePath(const STRING str)
{
	return str.substr(str.find_last_of(_T('\\')) + 1);
}
Exemple #19
0
// 字符串相关
INT	KLU_ConvertStringToVector(LPCTSTR strStrintgSource, std::vector< STRING >& vRet, LPCTSTR szKey, BOOL bOneOfKey, BOOL bIgnoreEmpty)
{
	vRet.clear();

	//------------------------------------------------------------
	//合法性
	if(!strStrintgSource || strStrintgSource[0] == '\0') return 0;
	
	STRING strSrc = strStrintgSource;

	//------------------------------------------------------------
	//查找第一个分割点
	STRING::size_type nLeft = 0;
	STRING::size_type nRight;
	if(bOneOfKey)
	{
		nRight = strSrc.find_first_of(szKey);
	}
	else
	{
		nRight = strSrc.find(szKey);
	}

	if(nRight == std::string::npos)
	{
		nRight = strSrc.length();
	}
	while(TRUE)
	{
		STRING strItem = strSrc.substr(nLeft, nRight-nLeft);
		if(strItem.length() > 0 || !bIgnoreEmpty)
		{
			vRet.push_back(strItem);
		}

		if(nRight == strSrc.length())
		{
			break;
		}

		nLeft = nRight + (bOneOfKey ? 1 : _tcslen(szKey));
		
		if(bOneOfKey)
		{
			STRING strTemp = strSrc.substr(nLeft);
			nRight = strTemp.find_first_of(szKey);
			if(nRight != STRING::npos) nRight += nLeft;
		}
		else
		{
			nRight = strSrc.find(szKey, nLeft);
		}

		if(nRight == std::string::npos)
		{
			nRight = strSrc.length();
		}
	}

	return (INT)vRet.size();
}
VOID CStringFilter::ReplaceToSign(const STRING& strIn, STRING& strOut)
{
	const CHAR		KeyStart		= '#';
	const CHAR		ContentsEnd		= '}';

	std::vector<PICE>	vSrcPice;	//来源字串分割成多段
	
	STRING strSrc = strIn;

	PICE			  pc;
	STRING::size_type sB = 0;
	STRING::size_type sC = 0;
	STRING::size_type sE = strSrc.find_first_of(KeyStart);
	STRING::size_type sLen = strSrc.size();

#if	0
	::OutputDebugString("ReplaceToSign Begin=======================\n");
	char dbgmsg[256];
	_snprintf(dbgmsg, 255, "strSrc:%s", strSrc.c_str());
	::OutputDebugString(dbgmsg);
	::OutputDebugString("\n------------------------------------------");
#endif

	do
	{	
		if(sE == STRING::npos)
		{
			//push last replace str
			pc.bReplace = TRUE;
			pc.pice = strSrc.substr(sC);
			vSrcPice.push_back(pc);
			break;
		}

		//get op
		STRING strOp = strSrc.substr(sE+1, 1);

		if(strOp == "{")	//ok, check magic #{} string.
		{
			//item element is valid. ex: #{_INFOID123}
			STRING strItemElement = strSrc.substr(sE+2, 7);
			//info message is valid. ex: #{_INFOMSGxxxxxx}
			STRING strInfoMsg = strSrc.substr(sE+2, 8);

			if(strItemElement == "_INFOID")
			{
				//get itemId
				//todo_yangjun	需要仔细检查剩下的字符是否还是一个完整的INFOID信息
				STRING::size_type sIDEnd = strSrc.find(ContentsEnd, sE+2+7);
				if(sE+2+7 >= sLen)	// fix dead loop if str is "xxx#{_INFOID" [9/25/2006]
				{
					//skip invalid #{
					sE += 2;
					goto LengthOver2;
				}
				STRING strId = strSrc.substr(sE+2+7, sIDEnd-sE-2-7);
				INT itemId = atoi(strId.c_str());

				if(g_pTransferItemSystem->IsElementExist(itemId))
				{//ok, valid item element found.

					//0. push normal replace str
					pc.bReplace = TRUE;
					pc.pice = strSrc.substr(sC, sE-sC);
					vSrcPice.push_back(pc);
					//1. push no replace str
					pc.bReplace = FALSE;
					pc.pice = strSrc.substr(sE, sIDEnd-sE+1);
					vSrcPice.push_back(pc);
				}

				//step to new point.
				sE = sIDEnd + 1;
				sC = sE;
			}
			else if(strInfoMsg == "_INFOMSG")
			{
				//get info message
				INT nContentsLen = atoi(strSrc.substr(sE+2+8,3).c_str());
				STRING::size_type sIDEnd = sE+2+8+3+nContentsLen;
				if(sE+2+8 >= sLen)
				{
					//skip invalid #{
					sE += 2;
					goto LengthOver2;
				}
				
				//ok, valid info message found.
				//0. push normal replace str
				pc.bReplace = TRUE;
				pc.pice = strSrc.substr(sC, sE-sC);
				vSrcPice.push_back(pc);
				//1. push no replace str
				pc.bReplace = FALSE;
				pc.pice = strSrc.substr(sE, sIDEnd-sE+1);
				vSrcPice.push_back(pc);

				//step to new point.
				sE = sIDEnd + 1;
				sC = sE;
			}
			else
			{
				//all other things
				sE += 2;
			}
		}
		else
		{
			//single #
			sE += 1;
		}
LengthOver2:
		if(sE >= sLen) 
		{
			if(sC != sE)
			{
				//push last replace str
				pc.bReplace = TRUE;
				pc.pice = strSrc.substr(sC);
				vSrcPice.push_back(pc);
			}
			break;
		}

		//save new begin point
		sB = sE;

		//find next KeyStart
		sE = strSrc.find(KeyStart, sB);

	}while(TRUE);

	//替换字串中的非法字符
	for(INT i = 0; i < (INT)vSrcPice.size(); ++i)
	{

#if	0
		_snprintf(dbgmsg, 255, "vSrcPice[%d]:%s\n", i, vSrcPice[i].pice.c_str());
		::OutputDebugString(dbgmsg);
#endif

		if(TRUE == vSrcPice[i].bReplace)
		{
			STRING strOld = vSrcPice[i].pice;
			ReplaceToSign_Normal(strOld, vSrcPice[i].pice);
		}
	}

	//生成结果字串
	strOut.clear();
	for(INT i = 0; i < (INT)vSrcPice.size(); ++i)
	{
		strOut += vSrcPice[i].pice;
	}

#if	0
	::OutputDebugString("ReplaceToSign End=========================\n");
#endif

}