Example #1
0
void wxNumberFormatter::AddThousandsSeparators(wxString& s)
{
    // Thousands separators for numbers in scientific format are not relevant.
    if ( s.find_first_of("eE") != wxString::npos )
        return;

    wxChar thousandsSep;
    if ( !GetThousandsSeparatorIfUsed(&thousandsSep) )
        return;

    size_t pos = s.find(GetDecimalSeparator());
    if ( pos == wxString::npos )
    {
        // Start grouping at the end of an integer number.
        pos = s.length();
    }

    // End grouping at the beginning of the digits -- there could be at a sign
    // before their start.
    const size_t start = s.find_first_of("0123456789");

    // We currently group digits by 3 independently of the locale. This is not
    // the right thing to do and we should use lconv::grouping (under POSIX)
    // and GetLocaleInfo(LOCALE_SGROUPING) (under MSW) to get information about
    // the correct grouping to use. This is something that needs to be done at
    // wxLocale level first and then used here in the future (TODO).
    const size_t GROUP_LEN = 3;

    while ( pos > start + GROUP_LEN )
    {
        pos -= GROUP_LEN;
        s.insert(pos, thousandsSep);
    }
}
Example #2
0
bool IsWordChar(const wxString &s, int strSize)
{
	if(strSize) {
		return s.find_first_of(wxT("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_")) != wxString::npos;

	} else {
		return s.find_first_of(wxT("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_")) != wxString::npos;
	}
}
Example #3
0
bool mbVarParser::Parse( wxString& text )
{
	// substitute variables in string with variable values
	// iterative, doesn't support nested variable definitions

	// find first opening bracket
	size_t lpos = text.find_first_of(wxT("["), 0);
	if( lpos != std::string::npos )
	{
		// find first closing bracket
		size_t rpos = text.find_first_of(wxT("]"), lpos);
		if( rpos != std::string::npos )
		{
			// find opening bracket in between
			size_t cpos = text.find_first_of(wxT("["), lpos+1);
			if( cpos != std::string::npos && cpos < rpos )
			{
				// if exists ignore first bracket

				wxString more = text.Mid(cpos);
				Parse(more);
				text = text.Left(cpos) + more;
				return true;
			}


			// try to parse what's between
			wxString fragment = text.Mid(lpos+1,rpos-lpos-1);
			wxString more = text.Mid(rpos+1);
			wxString value;
			if( GmbVariables().Parse( fragment, value) )
			{
				//wxLogMessage(wxT("Parsed [%s] to [%s]"), fragment.c_str(), value.c_str());
				text = text.Left(lpos) + value;
			}
			else
			{
				text = text.Left(rpos+1);
			}

			// if there is more, parse it again
			if( !more.empty() )
			{
				Parse(more);
			}

			// concatenate results and return
			text += more;
			return true;
		}
	}

	return false;
}
Example #4
0
void ConnectionDialog::setIP(wxString ip)
{
    size_t pos = ip.find_first_of('.');
    TextCtrlIP1->ChangeValue(ip.substr(0, pos));
    size_t pos2 = ip.find_first_of('.', pos + 1);
    TextCtrlIP2->ChangeValue(ip.substr(pos + 1, pos2 - pos - 1));
    pos = pos2;
    pos2 = ip.find_first_of('.', pos + 1);
    TextCtrlIP3->ChangeValue(ip.substr(pos + 1, pos2 - pos - 1));
    pos = pos2;
    pos2 = ip.find_first_of('.', pos + 1);
    TextCtrlIP4->ChangeValue(ip.substr(pos + 1, pos2 - pos - 1));
    TextCtrlIP1->SelectAll();
}
Example #5
0
bool ProjectOptionsDlg::ValidateTargetName(const wxString& name)
{
    if (name.IsEmpty())
        return false;

    if (m_Project->GetBuildTarget(name))
    {
        cbMessageBox(_("A target with this name already exists in this project!"),
                        _("Error"),
                        wxOK | wxCENTRE | wxICON_ERROR, this);
        return false;
    }

    if (m_Project->HasVirtualBuildTarget(name))
    {
        cbMessageBox(_("A virtual target with this name already exists in this project!"),
                        _("Error"),
                        wxOK | wxCENTRE | wxICON_ERROR, this);
        return false;
    }

    const wxString forbidden = _T(";,!@#$%^&*\"':`~=?\\><");
    if (name.find_first_of(forbidden, 0) != wxString::npos)
    {
        cbMessageBox(_("The name contains at least one invalid character:\n\n") + forbidden,
                        _("Error"),
                        wxOK | wxCENTRE | wxICON_ERROR, this);
        return false;
    }

    return true;
}
Example #6
0
bool CServerPath::Segmentize(wxString str, tSegmentList& segments)
{
	bool append = false;
	while (!str.empty())
	{
		wxString segment;
		int pos = str.find_first_of(traits[m_type].separators);
		if (pos == -1)
		{
			segment = str,
			str.clear();
		}
		else if (!pos)
		{
			str = str.Mid(1);
			continue;
		}
		else
		{
			segment = str.Left(pos);
			str = str.Mid(pos + 1);
		}

		if (traits[m_type].has_dots)
		{
			if (segment == _T("."))
				continue;
			else if (segment == _T(".."))
			{
				if (segments.empty())
					return false;
				else
				{
					segments.pop_back();
					continue;
				}
			}
		}

		bool append_next = false;
		if (traits[m_type].separatorEscape && segment.Last() == traits[m_type].separatorEscape)
		{
			append_next = true;
			segment.RemoveLast();
			segment += traits[m_type].separators[0];
		}

		if (append)
			segments.back() += segment;
		else
			segments.push_back(segment);

		append = append_next;
	}
	if (append)
		return false;

	return true;
}
Example #7
0
// returns the base/root directory of the given path.
// Example /this/that/something.txt -> dest == "/"
wxString Path::GetRootDirectory(const wxString &src)
{
    size_t pos = src.find_first_of(wxFileName::GetPathSeparators());
    if (pos == wxString::npos)
        return wxString();
    else
        return wxString(src.begin(), src.begin() + pos);
}
Example #8
0
void FindDialog::SetFindText(const wxString& text)
{
    // don't overwrite search text with empty or multiline text
    if (text.empty() || text.find_first_of('\n') != wxString::npos)
        return;
    text_ctrl_find->ChangeValue(text);
    text_ctrl_find->SelectAll();
}
bool MODULE::IsLibNameValid( const wxString & aName )
{
    const wxChar * invalids = StringLibNameInvalidChars( false );

    if( aName.find_first_of( invalids ) != std::string::npos )
        return false;

    return true;
}
int wxStringFormatter::FindEndOfSymbol(wxString input)
{
	int pos = input.find_first_of(DELIMS);

	if(pos == wxNOT_FOUND)
	{
		return input.Len()-1;
	}
	return pos - 1;
}
wxString wxStringFormatter::DoBlocks(wxString input)
{
	int level = 0;
	int pos = 0;
	while(input.find_first_of(m_blockDelims) != wxNOT_FOUND)
	{
		pos = FindNextBlock(input, 0, level);
	}
	return input;
}
wxString wxStringFormatter::FindNextFunction(wxString input, int& Startpos, int& Endpos)
{
	wxLogDebug("FindNextFunction: " + input);
	int functBegin;
	int blockOpen = input.find_first_of(DELIMS_F_OPEN);
	if(blockOpen == wxNOT_FOUND)
	{
		Startpos = wxNOT_FOUND;
		return "";
	}

	int blockClose = input.find_first_of(m_funcDelims, blockOpen +1);
	while(!DELIMS_F_CLOSE.Contains(input.GetChar(blockClose)) && blockClose != wxNOT_FOUND)
	{
		if(DELIMS_F_OPEN.Contains(input.GetChar(blockClose)))
		{
			blockOpen = blockClose;
			blockClose = input.find_first_of(m_funcDelims, blockOpen +1);
		}
	}

	if(blockClose == wxNOT_FOUND)
	{
		Startpos = wxNOT_FOUND;
		return "";
	}

	Endpos = blockClose + 1;

	//return input.SubString(blockOpen+1, blockClose-1);

	functBegin = input.find_last_of(DELIMS, blockOpen -1);
	functBegin++;

	wxString tmp = DoFunction(input.SubString(functBegin, blockOpen -1),  input.SubString(blockOpen+1, blockClose-1));
	if(m_concatDelims.Contains(input.GetChar(functBegin -1)))
	{
		functBegin--;
	}
	Startpos = functBegin;
	return tmp;
}
Example #13
0
void DebuggerTree::FixupVarNameForChange(wxString& str)
{
    // remove everything from '=' and after
    str = str.BeforeFirst(_T('='));
    str.Trim(false);
    str.Trim(true);

    // if it contains invalid chars, clear it
    if (str.find_first_of(_T(" \t")) != wxString::npos)
        str.Clear();
}
Example #14
0
wxFFileStream::wxFFileStream(const wxString& fileName, const wxString& mode)
             : wxFFileInputStream(),
               wxFFileOutputStream()
{
    wxASSERT_MSG( mode.find_first_of('+') != wxString::npos,
                  "must be opened in read-write mode for this class to work" );

    wxFFileOutputStream::m_file =
    wxFFileInputStream::m_file = new wxFFile(fileName, mode);

    // see comment in wxFileStream ctor
    wxFFileInputStream::m_file_destroy = true;
}
Example #15
0
wxString CCodeParser::ParseBrackets(wxString code, int& functionStart)
{
    int openingBrackets = 0;
    int closingBrackets = 0;
    int index = 0;
    wxString Str;

    int functionLength = 0;
    index = code.find('{', functionStart);
    if (index != wxNOT_FOUND)
    {
        openingBrackets++;
        index++;
        functionStart = index;
        int loop = 0;
        while (openingBrackets > closingBrackets)
        {
            index = code.find_first_of(wxT("{}"), index);
            if (index == wxNOT_FOUND)
            {
                Str = code.Mid(functionStart, index);
                functionStart = index;
                return Str;
            }
            if (code.GetChar(index) == '{')
            {
                index++;
                openingBrackets++;
            }
            else
            {
                index++;
                closingBrackets++;
            }
            if (loop == 100)
            {
                return wxT("");
            }
            loop++;
        }
        index--;
        functionLength = index - functionStart;
    }
    else
    {
        wxMessageBox(wxT("no brackets found"));
    }
    Str = code.Mid(functionStart, functionLength);
    functionStart = functionStart + functionLength + 1;
    return Str;
}
int wxStringFormatter::FindNextBlock(wxString& input, int pos, int& level)
{
	wxString str;
	wxLogDebug(wxString::Format("FindNextBlock: %d ", pos) + input);
	int blockOpen;
	int blockClose;

	blockClose = input.find_first_of(m_blockDelims, pos);

	if(DELIMS_B_CLOSE.Contains(input.GetChar(blockClose)))
	{
		return blockClose;
	}
	else if(DELIMS_B_OPEN.Contains(input.GetChar(blockClose)))
	{
		level++;
		blockOpen = blockClose;
		blockClose = FindNextBlock(input, blockClose+1, level);

		wxString block;
		block = input.SubString(blockOpen + 1, blockClose - 1);
		str.Printf("> %d %d", blockOpen + 1, blockClose - 1);
		wxLogDebug("block > " + block + str);
		block = DoFunctions(block);
		block = ReplaceSymbols(block);
		block = DoConcat(block);
		input.replace(blockOpen, (blockClose + 1) - blockOpen, block);
		level--;
	}
	else
	{
		wxLogDebug("not found");
		return wxNOT_FOUND;
	}

	if(level > 0)
	{
		return FindNextBlock(input, blockOpen, level);
	}
	return -1;
}
Example #17
0
wxString wxMemoryFSHandlerBase::FindFirst(const wxString& url, int flags)
{
    if ( (flags & wxDIR) && !(flags & wxFILE) )
    {
        // we only store files, not directories, so we don't risk finding
        // anything
        return wxString();
    }

    const wxString spec = GetRightLocation(url);
    if ( spec.find_first_of("?*") == wxString::npos )
    {
        // simple case: there are no wildcard characters so we can return
        // either 0 or 1 results and we can find the potential match quickly
        return m_Hash.count(spec) ? url : wxString();
    }
    //else: deal with wildcards in FindNext()

    m_findArgument = spec;
    m_findIter = m_Hash.begin();

    return FindNext();
}
Example #18
0
void wxNumberFormatter::RemoveTrailingZeroes(wxString& s)
{
    // If number is in scientific format, trailing zeroes belong to the exponent and cannot be removed.
    if ( s.find_first_of("eE") != wxString::npos )
        return;

    const size_t posDecSep = s.find(GetDecimalSeparator());
    // No decimal point => removing trailing zeroes irrelevant for integer number.
    if ( posDecSep == wxString::npos )
        return;
    wxCHECK_RET( posDecSep, "Can't start with decimal separator" );

    // Find the last character to keep.
    size_t posLastNonZero = s.find_last_not_of("0");

    // If it's the decimal separator itself, don't keep it neither.
    if ( posLastNonZero == posDecSep )
        posLastNonZero--;

    s.erase(posLastNonZero + 1);
    // Remove sign from orphaned zero.
    if ( s.compare("-0") == 0 )
        s = "0";
}
Example #19
0
/**
* Convert the value of the property to PHP code
*/
wxString PHPTemplateParser::ValueToCode( PropertyType type, wxString value )
{
	wxString result;

	switch ( type )
	{
	case PT_WXPARENT:
		{
			result = wxT("$this->") + value;
			break;
		}
	case PT_WXPARENT_SB:
		{
			result = wxT("$") + value + wxT("->GetStaticBox()");
			break;
		}
	case PT_WXSTRING:
	case PT_FILE:
	case PT_PATH:
		{
			if ( value.empty() )
			{
				result << wxT("wxEmptyString");
			}
			else
			{
				result << wxT("\"") << PHPCodeGenerator::ConvertPHPString( value ) << wxT("\"");
			}
			break;
		}
	case PT_WXSTRING_I18N:
		{
			if ( value.empty() )
			{
				result << wxT("wxEmptyString");
			}
			else
			{
				if ( m_i18n )
				{
					result << wxT("_(\"") << PHPCodeGenerator::ConvertPHPString(value) << wxT("\")");
				}
				else
				{
					result << wxT("\"") << PHPCodeGenerator::ConvertPHPString(value) << wxT("\"");
				}
			}
			break;
		}
	case PT_CLASS:
	case PT_MACRO:
	case PT_OPTION:
	case PT_EDIT_OPTION:
		{
			result = value;
			break;
		}
	case PT_TEXT:
	case PT_FLOAT:
	case PT_INT:
	case PT_UINT:
		{
			result = value;
			break;
		}
	case PT_BITLIST:
		{
			result = ( value.empty() ? wxT("0") : value );

			wxString pred, bit;
			wxStringTokenizer bits( result, wxT("|"), wxTOKEN_STRTOK );

			while( bits.HasMoreTokens() )
			{
				bit = bits.GetNextToken();
				pred = m_predModulePrefix[bit];

				/*if( bit.Contains( wxT("wx") ) )
				{
					if( !pred.empty() )	result.Replace( bit, pred + bit.AfterFirst('x') );
					else
						result.Replace( bit, wxT("wx") + bit.AfterFirst('x') );
				}*/
			}
			break;
		}
	case PT_WXPOINT:
		{
			if ( value.empty() )
			{
				result = wxT("wxDefaultPosition");
			}
			else
			{
				result << wxT("new wxPoint( ") << value << wxT(" )");
			}
			break;
		}
	case PT_WXSIZE:
		{
			if ( value.empty() )
			{
				result = wxT("wxDefaultSize");
			}
			else
			{
				result << wxT("new wxSize( ") << value << wxT(" )");
			}
			break;
		}
	case PT_BOOL:
		{
			result = ( value == wxT("0") ? wxT("false") : wxT("true") );
			break;
		}
	case PT_WXFONT:
		{
			if ( !value.empty() )
			{
				 wxFontContainer fontContainer = TypeConv::StringToFont( value );
				 wxFont font = fontContainer.GetFont();

				 const int pointSize = fontContainer.GetPointSize();

				 result = wxString::Format( "new wxFont( %s, %s, %s, %s, %s, %s )",
							 ((pointSize <= 0) ? "wxC2D(wxNORMAL_FONT)->GetPointSize()" : (wxString() << pointSize)),
							 TypeConv::FontFamilyToString( fontContainer.GetFamily() ),
							 font.GetStyleString(),
							 font.GetWeightString(),
							 ( fontContainer.GetUnderlined() ? "true" : "false" ),
							 ( fontContainer.m_faceName.empty() ? "wxEmptyString" : ("\"" + fontContainer.m_faceName + "\"") )
						 );
			}
			else
			{
				result = "wxC2D(wxNORMAL_FONT)";
			}
			break;
		}
		case PT_WXCOLOUR:
		{
			if ( !value.empty() )
			{
				if ( value.find_first_of( wxT("wx") ) == 0 )
				{
					// System Colour
					result << wxT("wxSystemSettings::GetColour( ") << ValueToCode( PT_OPTION, value ) << wxT(" )");
				}
				else
				{
					wxColour colour = TypeConv::StringToColour( value );
					result = wxString::Format( wxT("new wxColour( %i, %i, %i )"), colour.Red(), colour.Green(), colour.Blue() );
				}
			}
			else
			{
				result = wxT("new wxColour()");
			}
			break;
		}
	case PT_BITMAP:
		{
			wxString path;
			wxString source;
			wxSize icoSize;
			TypeConv::ParseBitmapWithResource( value, &path, &source, &icoSize );

			if ( path.empty() )
			{
				// Empty path, generate Null Bitmap
				result = wxT("wxNullBitmap");
				break;
			}

			if ( path.StartsWith( wxT("file:") ) )
			{
				wxLogWarning( wxT("PHP code generation does not support using URLs for bitmap properties:\n%s"), path.c_str() );
				result = wxT("wxNullBitmap");
				break;
			}

			if ( source == wxT("Load From File") )
			{
				wxString absPath;
				try
				{
					absPath = TypeConv::MakeAbsolutePath( path, AppData()->GetProjectPath() );
				}
				catch( wxFBException& ex )
				{
					wxLogError( ex.what() );
					result = wxT( "wxNullBitmap" );
					break;
				}

				wxString file = ( m_useRelativePath ? TypeConv::MakeRelativePath( absPath, m_basePath ) : absPath );

				result << wxT("new wxBitmap( \"") << PHPCodeGenerator::ConvertPHPString( file ) << wxT("\", wxBITMAP_TYPE_ANY )");
			}
			else if ( source == _("Load From Embedded File") )
			{
				result << wxT( "wxNullBitmap /* embedded files aren't supported */" );
			}
			else if ( source == wxT("Load From Resource") )
			{
				result << wxT("new wxBitmap( \"") << path << wxT("\", wxBITMAP_TYPE_RESOURCE )");
			}
			else if ( source == wxT("Load From Icon Resource") )
			{
				if ( wxDefaultSize == icoSize )
				{
					result << wxT("new wxICON( ") << path << wxT(" )");
				}
				else
				{
					result.Printf( wxT("new wxIcon( \"%s\", wxBITMAP_TYPE_ICO_RESOURCE, %i, %i )"), path.c_str(), icoSize.GetWidth(), icoSize.GetHeight() );
				}
			}
			else if ( source == _("Load From Art Provider") )
			{
				wxString rid = path.BeforeFirst( wxT(':') );
				if( rid.StartsWith( wxT("gtk-") ) ) rid = wxT("wxT(\"") + rid + wxT("\")");

				result = wxT("wxArtProvider::GetBitmap( ") + rid + wxT(", ") +  path.AfterFirst( wxT(':') ) + wxT(" )");
			}
			break;

			break;
		}
	case PT_STRINGLIST:
		{
			// Stringlists are generated like a sequence of wxString separated by ', '.
			wxArrayString array = TypeConv::StringToArrayString( value );
			if ( array.Count() > 0 )
			{
				result = ValueToCode( PT_WXSTRING_I18N, array[0] );
			}

			for ( size_t i = 1; i < array.Count(); i++ )
			{
				result << wxT(", ") << ValueToCode( PT_WXSTRING_I18N, array[i] );
			}
			break;
		}
	default:
		break;
	}

	return result;
}
Example #20
0
/**
* Convert the value of the property to C++ code
*/
wxString CppTemplateParser::ValueToCode( PropertyType type, wxString value )
{
	wxString result;

	switch ( type )
	{
	case PT_WXSTRING:
		{
			result << wxT("wxT(\"") << CppCodeGenerator::ConvertCppString( value ) << wxT("\")");
			break;
		}
	case PT_WXSTRING_I18N:
		{
			if ( m_i18n )
			{
				result << wxT("_(\"") << CppCodeGenerator::ConvertCppString(value) << wxT("\")");
			}
			else
			{
				result << wxT("wxT(\"") << CppCodeGenerator::ConvertCppString(value) << wxT("\")");
			}
			break;
		}
	case PT_MACRO:
	case PT_TEXT:
	case PT_OPTION:
	case PT_FLOAT:
		{
			result = value;
			break;
		}
	case PT_BITLIST:
		{
			result = ( value.empty() ? wxT("0") : value );
			break;
		}
	case PT_WXPOINT:
		{
			if ( value.empty() )
			{
				result = wxT("wxDefaultPosition");
			}
			else
			{
				result << wxT("wxPoint( ") << value << wxT(" )");
			}
			break;
		}
	case PT_WXSIZE:
		{
			if ( value.empty() )
			{
				result = wxT("wxDefaultSize");
			}
			else
			{
				result << wxT("wxSize( ") << value << wxT(" )");
			}
			break;
		}
	case PT_BOOL:
		{
			result = ( value == wxT("0") ? wxT("false") : wxT("true") );
			break;
		}
	case PT_WXFONT:
		{
			if ( !value.empty() )
			{
				wxFont font = TypeConv::StringToFont( value );
				result	= wxString::Format( wxT("wxFont( %i, %i, %i, %i, %s, wxT(\"%s\") )" ),
											font.GetPointSize(),
											font.GetFamily(),
											font.GetStyle(),
											font.GetWeight(),
											( font.GetUnderlined() ? wxT("true") : wxT("false") ),
											font.GetFaceName().c_str()
											);
			}
			else
			{
				result = wxT("wxFont()");
			}
			break;
		}
	case PT_WXCOLOUR:
		{
			if ( !value.empty() )
			{
				if ( value.find_first_of( wxT("wx") ) == 0 )
				{
					// System Colour
					result << wxT("wxSystemSettings::GetColour( ") << value << wxT(" )");
				}
				else
				{
					wxColour colour = TypeConv::StringToColour( value );
					result = wxString::Format( wxT("wxColour( %i, %i, %i )"), colour.Red(), colour.Green(), colour.Blue() );
				}
			}
			else
			{
				result = wxT("wxColour()");
			}
			break;
		}
	case PT_BITMAP:
		{
			// Splitting bitmap resource property value - it is of the form "path; source"
			size_t semicolonIndex = value.find_first_of( wxT(";") );
			wxString path;
			wxString source;
			if ( semicolonIndex != value.npos )
			{
				path = value.substr( 0, semicolonIndex );
				source = value.substr( semicolonIndex + 2 ); // Separated by "; "
			}
			else
			{
				path = value;
				source = wxT("Load From File");
			}

			if ( path.empty() )
			{
				// Empty path, generate Null Bitmap
				result = wxT("wxNullBitmap");
				break;
			}

			if ( source == wxT("Load From File") )
			{
				wxString absPath = TypeConv::MakeAbsolutePath( path, GlobalData()->GetProjectPath() );
				wxString file = ( m_useRelativePath ? TypeConv::MakeRelativePath( absPath, m_basePath ) : absPath );

				wxString cppString = CppCodeGenerator::ConvertCppString( file );

				wxFileName bmpFileName( path );
				if ( bmpFileName.GetExt().Upper() == wxT("XPM") )
				{
					// If the bitmap is an XPM we will embed it in the code, otherwise it will be loaded from the file at run time.
					result << wxT("wxBitmap( ") << CppCodeGenerator::ConvertXpmName( path ) << wxT(" )");
				}
				else
				{
					result << wxT("wxBitmap( wxT(\"") << cppString << wxT("\"), wxBITMAP_TYPE_ANY )");
				}
			}
			else if ( source == wxT("Load From Resource") )
			{
				result << wxT("wxBitmap( wxT(\"") << path << wxT("\"), wxBITMAP_TYPE_RESOURCE )");
			}
			else if ( source == wxT("Load From Icon Resource") )
			{
				result << wxT("wxICON( ") << path << wxT(" )");
			}

			break;
		}
	case PT_STRINGLIST:
		{
			// Stringlists are generated like a sequence of wxString separated by ', '.
			wxArrayString array = TypeConv::StringToArrayString( value );
			if ( array.Count() > 0 )
			{
				result = ValueToCode( PT_WXSTRING_I18N, array[0] );
			}

			for ( size_t i = 1; i < array.Count(); i++ )
			{
				result << wxT(", ") << ValueToCode( PT_WXSTRING_I18N, array[i] );
			}
			break;
		}
	default:
		break;
	}

	return result;
}
bool wxStringFormatter::CheckSyntax(wxString& input)
{
	int opDelim =0;
	int clDelim = 0;
	int index = input.find_first_of(DELIMS_F_OPEN, 0);
	while(index != wxNOT_FOUND)
	{
		if(index != wxNOT_FOUND)
		{
			opDelim++;
			index = input.find_first_of(DELIMS_F_OPEN, index +1);
		}
	}
	index = input.find_first_of(DELIMS_F_CLOSE, 0);
	while(index != wxNOT_FOUND)
	{
		if(index != wxNOT_FOUND)
		{
			clDelim++;
			index = input.find_first_of(DELIMS_F_CLOSE, index+1);
		}
	}
	if(opDelim < clDelim)
	{
		input = "!ERROR: Missing \"" + DELIMS_F_OPEN + "\"!";
		return true;
	}
	else if(opDelim > clDelim)
	{
		input = "!ERROR: Missing \"" + DELIMS_F_CLOSE + "\"!";
		return true;
	}

	opDelim =0;
	clDelim = 0;
	index = input.find_first_of(DELIMS_B_OPEN, 0);
	while(index != wxNOT_FOUND)
	{
		if(index != wxNOT_FOUND)
		{
			opDelim++;
			index = input.find_first_of(DELIMS_B_OPEN, index +1);
		}
	}
	index = input.find_first_of(DELIMS_B_CLOSE, 0);
	while(index != wxNOT_FOUND)
	{
		if(index != wxNOT_FOUND)
		{
			clDelim++;
			index = input.find_first_of(DELIMS_B_CLOSE, index+1);
		}
	}

	if(opDelim < clDelim)
	{
		input = "!ERROR: Missing \"" + DELIMS_B_OPEN + "\"!";
		return true;
	}
	else if(opDelim > clDelim)
	{
		input = "!ERROR: Missing \"" + DELIMS_B_CLOSE + "\"!";
		return true;
	}
	return false;
}
Example #22
0
wxFileDialog::wxFileDialog(wxWindow *parent, const wxString& message,
                           const wxString& defaultDir,
                           const wxString& defaultFileName,
                           const wxString& wildCard,
                           long style, const wxPoint& pos,
                           const wxSize& sz,
                           const wxString& name)
    : wxFileDialogBase()
{
    parent = GetParentForModalDialog(parent, style);

    if (!wxFileDialogBase::Create(parent, message, defaultDir, defaultFileName,
                                  wildCard, style, pos, sz, name))
    {
        return;
    }

    if (!PreCreation(parent, pos, wxDefaultSize) ||
        !CreateBase(parent, wxID_ANY, pos, wxDefaultSize, style,
                wxDefaultValidator, wxT("filedialog")))
    {
        wxFAIL_MSG( wxT("wxFileDialog creation failed") );
        return;
    }

    GtkFileChooserAction gtk_action;
    GtkWindow* gtk_parent = NULL;
    if (parent)
        gtk_parent = GTK_WINDOW( gtk_widget_get_toplevel(parent->m_widget) );

    const gchar* ok_btn_stock;
    if ( style & wxFD_SAVE )
    {
        gtk_action = GTK_FILE_CHOOSER_ACTION_SAVE;
        ok_btn_stock = GTK_STOCK_SAVE;
    }
    else
    {
        gtk_action = GTK_FILE_CHOOSER_ACTION_OPEN;
        ok_btn_stock = GTK_STOCK_OPEN;
    }

    m_widget = gtk_file_chooser_dialog_new(
                   wxGTK_CONV(m_message),
                   gtk_parent,
                   gtk_action,
                   GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                   ok_btn_stock, GTK_RESPONSE_ACCEPT,
                   NULL);
    g_object_ref(m_widget);
    GtkFileChooser* file_chooser = GTK_FILE_CHOOSER(m_widget);

    m_fc.SetWidget(file_chooser);

    gtk_dialog_set_default_response(GTK_DIALOG(m_widget), GTK_RESPONSE_ACCEPT);

    if ( style & wxFD_MULTIPLE )
        gtk_file_chooser_set_select_multiple(file_chooser, true);

    // gtk_widget_hide_on_delete is used here to avoid that Gtk automatically
    // destroys the dialog when the user press ESC on the dialog: in that case
    // a second call to ShowModal() would result in a bunch of Gtk-CRITICAL
    // errors...
    g_signal_connect(m_widget,
                    "delete_event",
                    G_CALLBACK (gtk_widget_hide_on_delete),
                    this);

    // local-only property could be set to false to allow non-local files to be
    // loaded. In that case get/set_uri(s) should be used instead of
    // get/set_filename(s) everywhere and the GtkFileChooserDialog should
    // probably also be created with a backend, e.g. "gnome-vfs", "default", ...
    // (gtk_file_chooser_dialog_new_with_backend). Currently local-only is kept
    // as the default - true:
    // gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(m_widget), true);

    g_signal_connect (m_widget, "response",
        G_CALLBACK (gtk_filedialog_response_callback), this);


    // deal with extensions/filters
    SetWildcard(wildCard);

    wxString defaultFileNameWithExt = defaultFileName;
    if ( !wildCard.empty() && !defaultFileName.empty() &&
            !wxFileName(defaultFileName).HasExt() )
    {
        // append the default extension to the initial file name: GTK won't do
        // it for us by default (unlike e.g. MSW)
        const wxString defaultExt = m_fc.GetCurrentWildCard().AfterFirst('.');
        if ( defaultExt.find_first_of("?*") == wxString::npos )
            defaultFileNameWithExt += "." + defaultExt;
    }


    // if defaultDir is specified it should contain the directory and
    // defaultFileName should contain the default name of the file, however if
    // directory is not given, defaultFileName contains both
    wxFileName fn;
    if ( defaultDir.empty() )
        fn.Assign(defaultFileNameWithExt);
    else if ( !defaultFileNameWithExt.empty() )
        fn.Assign(defaultDir, defaultFileNameWithExt);
    else
        fn.AssignDir(defaultDir);

    // set the initial file name and/or directory
    fn.MakeAbsolute(); // GTK+ needs absolute path
    const wxString dir = fn.GetPath();
    if ( !dir.empty() )
    {
        gtk_file_chooser_set_current_folder(file_chooser, dir.fn_str());
    }

    const wxString fname = fn.GetFullName();
    if ( style & wxFD_SAVE )
    {
        if ( !fname.empty() )
        {
            gtk_file_chooser_set_current_name(file_chooser, fname.fn_str());
        }

#if GTK_CHECK_VERSION(2,7,3)
        if ((style & wxFD_OVERWRITE_PROMPT) && !gtk_check_version(2,7,3))
            gtk_file_chooser_set_do_overwrite_confirmation(file_chooser, true);
#endif
    }
    else // wxFD_OPEN
    {
        if ( !fname.empty() )
        {
            gtk_file_chooser_set_filename(file_chooser,
                                          fn.GetFullPath().fn_str());
        }
    }

    if ( style & wxFD_PREVIEW )
    {
        GtkWidget *previewImage = gtk_image_new();

        gtk_file_chooser_set_preview_widget(file_chooser, previewImage);
        g_signal_connect(m_widget, "update-preview",
                         G_CALLBACK(gtk_filedialog_update_preview_callback),
                         previewImage);
    }
}
Example #23
0
    bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
    {
        const UChar32 s_last = source.Last();
        const UChar32 t_last = translation.Last();
        const bool s_punct = u_ispunct(s_last);
        const bool t_punct = u_ispunct(t_last);

        if (u_getIntPropertyValue(s_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE ||
            u_getIntPropertyValue(t_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE)
        {
            // too many reordering related false positives for brackets
            // e.g. "your {site} account" -> "váš účet na {site}"
            if ((wchar_t)u_getBidiPairedBracket(s_last) != (wchar_t)source[0])
            {
                return false;
            }
            else
            {
                // OTOH, it's desirable to check strings fully enclosed in brackets like "(unsaved)"
                if (source.find_first_of((wchar_t)s_last, 1) != source.size() - 1)
                {
                    // it's more complicated, possibly something like "your {foo} on {bar}"
                    return false;
                }
            }
        }

        if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) || (!s_punct && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK)))
        {
            // quoted fragments can move around, e.g., so ignore quotes in reporting:
            //      >> Invalid value for ‘{fieldName}’​ field
            //      >> Valor inválido para el campo ‘{fieldName}’
            // TODO: count quote characters to check if used correctly in translation; don't check position
            return false;
        }

        if (s_punct && !t_punct)
        {
            item->SetIssue(CatalogItem::Issue::Warning,
                           wxString::Format(_(L"The translation should end with “%s”."), wxString(wxUniChar(s_last))));
            return true;
        }
        else if (!s_punct && t_punct)
        {
            item->SetIssue(CatalogItem::Issue::Warning,
                           wxString::Format(_(L"The translation should not end with “%s”."), wxString(wxUniChar(t_last))));
            return true;
        }
        else if (s_punct && t_punct && s_last != t_last)
        {
            if (t_last == L'…' && source.EndsWith("..."))
            {
                // as a special case, allow translating ... (3 dots) as … (ellipsis)
            }
            else if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK))
            {
                // don't check for correct quotes for now, accept any quotations marks as equal
            }
            else if (IsEquivalent(s_last, t_last))
            {
                // some characters are mostly equivalent and we shouldn't warn about them
            }
            else
            {
                item->SetIssue(CatalogItem::Issue::Warning,
                               wxString::Format(_(L"The translation ends with “%s”, but the source text ends with “%s”."),
                                                wxString(wxUniChar(t_last)), wxString(wxUniChar(s_last))));
                return true;
            }
        }

        return false;
    }
int wxStringFormatter::FindNextSymbol(wxString input)
{
	return input.find_first_of(m_symbolDelims);
}
void MacrosManager::ReplaceMacros(wxString& buffer, ProjectBuildTarget* target, bool subrequest)
{
    if (buffer.IsEmpty())
        return;

    static const wxString delim(_T("$%["));
    if ( buffer.find_first_of(delim) == wxString::npos )
        return;

    cbProject* project = target
                        ? target->GetParentProject()
                        : Manager::Get()->GetProjectManager()->GetActiveProject();
    EditorBase* editor = Manager::Get()->GetEditorManager()->GetActiveEditor();

    if (!target)
    {
        if (project)
        {
            // use the currently compiling target
            target = project->GetCurrentlyCompilingTarget();
            // if none,
            if (!target)
                // use the last known active target
                target = project->GetBuildTarget(project->GetActiveBuildTarget());
        }
    }
    if (project != m_LastProject || target != m_LastTarget || (editor && (editor->GetFilename() != m_ActiveEditorFilename)) )
        RecalcVars(project, editor, target);

    wxString search;
    wxString replace;

    if (buffer.find(_T("$if")) != wxString::npos)
    while (m_RE_If.Matches(buffer))
    {
        search = m_RE_If.GetMatch(buffer, 0);
        replace = EvalCondition(m_RE_If.GetMatch(buffer, 1), m_RE_If.GetMatch(buffer, 3), m_RE_If.GetMatch(buffer, 5), target);
        buffer.Replace(search, replace, false);
    }

    while (m_RE_Script.Matches(buffer))
    {
        search = m_RE_Script.GetMatch(buffer, 1);
        replace = Manager::Get()->GetScriptingManager()->LoadBufferRedirectOutput(m_RE_Script.GetMatch(buffer, 2));
        buffer.Replace(search, replace, false);
    }

    while (m_RE_ToAbsolutePath.Matches(buffer))
    {
        search = m_RE_ToAbsolutePath.GetMatch(buffer, 0);
        const wxString relativePath = m_RE_ToAbsolutePath.GetMatch(buffer, 1);
        wxFileName fn(relativePath);
        fn.MakeAbsolute();
        replace = fn.GetFullPath();
        buffer.Replace(search, replace, false);
    }

    while (m_RE_To83Path.Matches(buffer))
    {
        search = m_RE_To83Path.GetMatch(buffer, 0);
        const wxString path = m_RE_To83Path.GetMatch(buffer, 1);
        wxFileName fn(path);
        fn.MakeAbsolute(); // make absolute before translating to 8.3 notation
        replace = fn.GetShortPath();
        buffer.Replace(search, replace, false);
    }

    while (m_RE_Unix.Matches(buffer))
    {
        replace.Empty();

        wxString search = m_RE_Unix.GetMatch(buffer, 2);
        wxString var = m_RE_Unix.GetMatch(buffer, 3).Upper();

        if (var.GetChar(0) == _T('#'))
            replace = UnixFilename(m_UserVarMan->Replace(var));
        else
        {
            if (var.compare(const_COIN) == 0)
                replace.assign(1u, rand() & 1 ? _T('1') : _T('0'));
            else if (var.compare(const_RANDOM) == 0)
                replace = wxString::Format(_T("%d"), rand() & 0xffff);
            else
            {
                MacrosMap::iterator it;
                if ((it = m_Macros.find(var)) != m_Macros.end())
                    replace = it->second;
            }
        }

        const wxChar l = search.Last(); // make non-braced variables work
        if (l == _T('/') || l == _T('\\') || l == _T('$') || l == _T(' '))
            replace.append(l);

        if (replace.IsEmpty())
            wxGetEnv(var, &replace);

        buffer.Replace(search, replace, false);
    }

    while (m_RE_DOS.Matches(buffer))
    {
        replace.Empty();

        wxString search = m_RE_DOS.GetMatch(buffer, 2);
        wxString var = m_RE_DOS.GetMatch(buffer, 3).Upper();

        if (var.GetChar(0) == _T('#'))
            replace = UnixFilename(m_UserVarMan->Replace(var));
        else
        {
            if (var.compare(const_COIN) == 0)
                replace.assign(1u, rand() & 1 ? _T('1') : _T('0'));
            else if (var.compare(const_RANDOM) == 0)
                replace = wxString::Format(_T("%d"), rand() & 0xffff);
            else
            {
                MacrosMap::iterator it;
                if ((it = m_Macros.find(var)) != m_Macros.end())
                    replace = it->second;
            }
        }

        if (replace.IsEmpty())
            wxGetEnv(var, &replace);

        buffer.Replace(search, replace, false);
    }

    if (!subrequest)
    {
        buffer.Replace(_T("%%"), _T("%"));
        buffer.Replace(_T("$$"), _T("$"));
    }
}
Example #26
0
int wxRegExImpl::Replace(wxString *text,
                         const wxString& replacement,
                         size_t maxMatches) const
{
    wxCHECK_MSG( text, wxNOT_FOUND, wxT("NULL text in wxRegEx::Replace") );
    wxCHECK_MSG( IsValid(), wxNOT_FOUND, wxT("must successfully Compile() first") );

    // the input string
#ifndef WXREGEX_CONVERT_TO_MB
    const wxChar *textstr = text->c_str();
    size_t textlen = text->length();
#else
    const wxWX2MBbuf textstr = WXREGEX_CHAR(*text);
    if (!textstr)
    {
        wxLogError(_("Failed to find match for regular expression: %s"),
                   GetErrorMsg(0, true).c_str());
        return 0;
    }
    size_t textlen = strlen(textstr);
    text->clear();
#endif

    // the replacement text
    wxString textNew;

    // the result, allow 25% extra
    wxString result;
    result.reserve(5 * textlen / 4);

    // attempt at optimization: don't iterate over the string if it doesn't
    // contain back references at all
    bool mayHaveBackrefs =
        replacement.find_first_of(wxT("\\&")) != wxString::npos;

    if ( !mayHaveBackrefs )
    {
        textNew = replacement;
    }

    // the position where we start looking for the match
    size_t matchStart = 0;

    // number of replacement made: we won't make more than maxMatches of them
    // (unless maxMatches is 0 which doesn't limit the number of replacements)
    size_t countRepl = 0;

    // note that "^" shouldn't match after the first call to Matches() so we
    // use wxRE_NOTBOL to prevent it from happening
    while ( (!maxMatches || countRepl < maxMatches) &&
             Matches(
#ifndef WXREGEX_CONVERT_TO_MB
                    textstr + matchStart,
#else
                    textstr.data() + matchStart,
#endif
                    countRepl ? wxRE_NOTBOL : 0
                    WXREGEX_IF_NEED_LEN(textlen - matchStart)) )
    {
        // the string possibly contains back references: we need to calculate
        // the replacement text anew after each match
        if ( mayHaveBackrefs )
        {
            mayHaveBackrefs = false;
            textNew.clear();
            textNew.reserve(replacement.length());

            for ( const wxChar *p = replacement.c_str(); *p; p++ )
            {
                size_t index = (size_t)-1;

                if ( *p == wxT('\\') )
                {
                    if ( wxIsdigit(*++p) )
                    {
                        // back reference
                        wxChar *end;
                        index = (size_t)wxStrtoul(p, &end, 10);
                        p = end - 1; // -1 to compensate for p++ in the loop
                    }
                    //else: backslash used as escape character
                }
                else if ( *p == wxT('&') )
                {
                    // treat this as "\0" for compatbility with ed and such
                    index = 0;
                }

                // do we have a back reference?
                if ( index != (size_t)-1 )
                {
                    // yes, get its text
                    size_t start, len;
                    if ( !GetMatch(&start, &len, index) )
                    {
                        wxFAIL_MSG( wxT("invalid back reference") );

                        // just eat it...
                    }
                    else
                    {
                        textNew += wxString(
#ifndef WXREGEX_CONVERT_TO_MB
                                textstr
#else
                                textstr.data()
#endif
                                + matchStart + start,
                                *wxConvCurrent, len);

                        mayHaveBackrefs = true;
                    }
                }
                else // ordinary character
                {
                    textNew += *p;
                }
            }
        }

        size_t start, len;
        if ( !GetMatch(&start, &len) )
        {
            // we did have match as Matches() returned true above!
            wxFAIL_MSG( wxT("internal logic error in wxRegEx::Replace") );

            return wxNOT_FOUND;
        }

        // an insurance against implementations that don't grow exponentially
        // to ensure building the result takes linear time
        if (result.capacity() < result.length() + start + textNew.length())
            result.reserve(2 * result.length());

#ifndef WXREGEX_CONVERT_TO_MB
        result.append(*text, matchStart, start);
#else
        result.append(wxString(textstr.data() + matchStart, *wxConvCurrent, start));
#endif
        matchStart += start;
        result.append(textNew);

        countRepl++;

        matchStart += len;
    }

#ifndef WXREGEX_CONVERT_TO_MB
    result.append(*text, matchStart, wxString::npos);
#else
    result.append(wxString(textstr.data() + matchStart, *wxConvCurrent));
#endif
    *text = result;

    return countRepl;
}