Example #1
0
// replaces '\t', ' ' and '\n' with HTML markup:
static wxString LINKAGEMODE HtmlizeLinebreaks(const wxString& str)
{
    wxString out;
    out.reserve(str.length()); // we'll certainly need at least that

    const wxString::const_iterator end = str.end();
    for ( wxString::const_iterator i = str.begin(); i != end; ++i )
    {
        switch ( (*i).GetValue() )
        {
            case '<':
                while ( i != end && *i != '>' )
                {
                    out << *i++;
                }
                out << '>';
                if ( i == end )
                    return out;
                break;

            // We need to translate any line break into exactly one <br>.
            // Quoting HTML spec: "A line break is defined to be a carriage
            // return (&#x000D;), a line feed (&#x000A;), or a carriage
            // return/line feed pair."
            case '\r':
                {
                    wxString::const_iterator j(i + 1);
                    if ( j != end && *j == '\n' )
                        i = j;
                }
                // fall through
            case '\n':
                out << "<br>";
                break;

            default:
                out << *i;
                break;
        }
    }

    return out;
}
Example #2
0
void
wxPdfBarCodeCreator::Code128Draw(double x, double y, const wxString& barcode, double h, double w)
{
    //Draw bars
    double barWidth;
    double xPos = x;
    short* bars;
    size_t j;
    wxString::const_iterator ch;
    for (ch = barcode.begin(); ch != barcode.end(); ++ch)
    {
        bars = code128_bars[*ch];
        for (j = 0; j < 6 && bars[j] != 0; j = j+2)
        {
            barWidth = bars[j] * w;
            m_document->Rect(xPos, y, barWidth, h, wxPDF_STYLE_FILL);
            xPos += (bars[j]+bars[j+1]) * w;
        }
    }
}
Example #3
0
//Replace TABs with needed spaces returning a 'tabulated' string
wxString wxFixWidthImportCtrl::TabsToSpaces(const wxString& str) const
{
    wxString stRes;

    if (m_tabSize < 0)
    {
        stRes = str;
        return stRes;
    }
    if (m_tabSize == 0)
    {
        stRes = str;
        // remove tabs
        stRes.Replace(wxT("\t"), wxEmptyString);
        return stRes;
    }

    size_t pos = 0;
    size_t nSp = 0;
    wxString tabRep;
    wxChar ch;

    for ( wxString::const_iterator i = str.begin(); i != str.end(); ++i )
    {
        ch = *i;
        if ( ch == wxT('\t') )
        {
            tabRep = wxT("");
            nSp = (size_t)m_tabSize - (pos % (size_t)m_tabSize);
            tabRep.Append(wxChar(' '), nSp);
            stRes += tabRep;
            pos += nSp;
        }
        else
        {
            stRes += ch;
            pos++;
        }
    }
    return stRes;
}
Example #4
0
bool DotWriter::GetOuterTempleate(const wxString& txt, int* start, int* end)
{
    int cnt = 0;
    int pos = 0;

    for(wxString::const_iterator it = txt.begin(); it != txt.end(); ++it) {
        if(*it == wxT('<')) {
            if(cnt == 0) *start = pos;
            cnt++;
        } else if(*it == wxT('>')) {
            cnt--;
            if(cnt == 0) *end = pos;
            return true;
        }
        pos++;
    }

    *start = -1;
    *end = -1;
    return false;
}
Example #5
0
bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
{
    const wxString strExtensions = m_manager->GetExtension(m_index[0]);
    extensions.Empty();

    // one extension in the space or comma-delimited list
    wxString strExt;
    wxString::const_iterator end = strExtensions.end();
    for ( wxString::const_iterator p = strExtensions.begin(); /* nothing */; ++p )
    {
        if ( p == end || *p == wxT(' ') || *p == wxT(',') )
        {
            if ( !strExt.empty() )
            {
                extensions.Add(strExt);
                strExt.Empty();
            }
            //else: repeated spaces
            // (shouldn't happen, but it's not that important if it does happen)

            if ( p == end )
                break;
        }
        else if ( *p == wxT('.') )
        {
            // remove the dot from extension (but only if it's the first char)
            if ( !strExt.empty() )
            {
                strExt += wxT('.');
            }
            //else: no, don't append it
        }
        else
        {
            strExt += *p;
        }
    }

    return true;
}
Example #6
0
// this function is used to properly interpret '..' in path
void wxSplitPath(wxArrayString& aParts, const wxString& path)
{
  aParts.clear();

  wxString strCurrent;
  wxString::const_iterator pc = path.begin();
  for ( ;; ) {
    if ( pc == path.end() || *pc == wxCONFIG_PATH_SEPARATOR ) {
      if ( strCurrent == wxT(".") ) {
        // ignore
      }
      else if ( strCurrent == wxT("..") ) {
        // go up one level
        if ( aParts.size() == 0 )
        {
          wxLogWarning(_("'%s' has extra '..', ignored."), path);
        }
        else
        {
          aParts.erase(aParts.end() - 1);
        }

        strCurrent.Empty();
      }
      else if ( !strCurrent.empty() ) {
        aParts.push_back(strCurrent);
        strCurrent.Empty();
      }
      //else:
        // could log an error here, but we prefer to ignore extra '/'

      if ( pc == path.end() )
        break;
    }
    else
      strCurrent += *pc;

    ++pc;
  }
}
Example #7
0
// helper function translating week day/month names from English to the current
// locale
static wxString TranslateDate(const wxString& str)
{
    // small optimization: if there are no alphabetic characters in the string,
    // there is nothing to translate
    wxString::const_iterator i, end = str.end();
    for ( i = str.begin(); i != end; ++i )
    {
        if ( isalpha(*i) )
            break;
    }

    if ( i == end )
        return str;

    wxString trans(str);

    for ( wxDateTime::WeekDay wd = wxDateTime::Sun;
          wd < wxDateTime::Inv_WeekDay;
          wxNextWDay(wd) )
    {
        trans.Replace
              (
                wxDateTime::GetEnglishWeekDayName(wd, wxDateTime::Name_Abbr),
                wxDateTime::GetWeekDayName(wd, wxDateTime::Name_Abbr)
              );
    }

    for ( wxDateTime::Month mon = wxDateTime::Jan;
          mon < wxDateTime::Inv_Month;
          wxNextMonth(mon) )
    {
        trans.Replace
              (
                wxDateTime::GetEnglishMonthName(mon, wxDateTime::Name_Abbr),
                wxDateTime::GetMonthName(mon, wxDateTime::Name_Abbr)
              );
    }

    return trans;
}
Example #8
0
void wxStringTokenizer::SetString(const wxString& str,
                                  const wxString& delims,
                                  wxStringTokenizerMode mode)
{
    if ( mode == wxTOKEN_DEFAULT )
    {
        // by default, we behave like strtok() if the delimiters are only
        // whitespace characters and as wxTOKEN_RET_EMPTY otherwise (for
        // whitespace delimiters, strtok() behaviour is better because we want
        // to count consecutive spaces as one delimiter)
        wxString::const_iterator p;
        for ( p = delims.begin(); p != delims.end(); ++p )
        {
            if ( !wxIsspace(*p) )
                break;
        }

        if ( p != delims.end() )
        {
            // not whitespace char in delims
            mode = wxTOKEN_RET_EMPTY;
        }
        else
        {
            // only whitespaces
            mode = wxTOKEN_STRTOK;
        }
    }

#if wxUSE_UNICODE // FIXME-UTF8: only wc_str()
    m_delims = delims.wc_str();
#else
    m_delims = delims.mb_str();
#endif
    m_delimsLen = delims.length();

    m_mode = mode;

    Reinit(str);
}
Example #9
0
// Parse flags
//
void RegExTestCase::parseFlags(const wxString& flags)
{
    for ( wxString::const_iterator p = flags.begin(); p != flags.end(); ++p )
    {
        switch ( (*p).GetValue() ) {
            // noop
            case '-': break;

            // we don't fully support these flags, but they don't stop us
            // checking for success of failure of the match, so treat as noop
            case 'A': case 'B': case 'E': case 'H':
            case 'I': case 'L': case 'M': case 'N':
            case 'P': case 'Q': case 'R': case 'S':
            case 'T': case 'U': case '%':
                break;

            // match options
            case '^': m_matchFlags |= wxRE_NOTBOL; break;
            case '$': m_matchFlags |= wxRE_NOTEOL; break;
#if wxUSE_UNICODE
            case '*': break;
#endif
            // compile options
            case '&': m_advanced = m_basic = true; break;
            case 'b': m_basic = true; break;
            case 'e': m_extended = true; break;
            case 'i': m_compileFlags |= wxRE_ICASE; break;
            case 'o': m_compileFlags |= wxRE_NOSUB; break;
            case 'n': m_compileFlags |= wxRE_NEWLINE; break;
            case 't': if (strchr("ep", m_mode)) break; // else fall through...

            // anything else we must skip the test
            default:
                fail(wxString::Format(
                     wxT("requires unsupported flag '%c'"), *p));
        }
    }
}
Example #10
0
/* static */
wxString wxURI::Unescape(const wxString& uri)
{
    // the unescaped version can't be longer than the original one
    wxCharBuffer buf(uri.length());
    char *p = buf.data();

    for ( wxString::const_iterator i = uri.begin(); i != uri.end(); ++i, ++p )
    {
        char c = *i;
        if ( c == '%' )
        {
            int n = wxURI::DecodeEscape(i);
            if ( n == -1 )
                return wxString();

            wxASSERT_MSG( n >= 0 && n <= 0xff, "unexpected character value" );

            c = static_cast<char>(n);
        }

        *p = c;
    }

    *p = '\0';

    // by default assume that the URI is in UTF-8, this is the most common
    // practice
    wxString s = wxString::FromUTF8(buf);
    if ( s.empty() )
    {
        // if it isn't, use latin-1 as a fallback -- at least this always
        // succeeds
        s = wxCSConv(wxFONTENCODING_ISO8859_1).cMB2WC(buf);
    }

    return s;
}
Example #11
0
wxArrayString TokenizeWords(const wxString &str)
{
	wxString currChar;
	wxString nextChar;
	wxString currentWord;
	wxArrayString outputArr;
	
	wxString::const_iterator iter = str.begin();
	for(; iter != str.end(); iter++) {
		// Look ahead
		if( (iter + 1) != str.end() ) {
			 nextChar = *(iter+1);
		} else {
			// we are at the end of buffer
			nextChar = wxT('\0');
		}

		currChar = *iter;
		if(!IsWordChar( currChar, currentWord.Length() )) {
			currentWord.Clear();

		} else {

			currentWord << currChar;
			if(IsWordChar(nextChar, currentWord.Length())) {
				// do nothing

			} else {

				outputArr.Add(currentWord);
				currentWord.Clear();
			}

		}
	}
	return outputArr;
}
Example #12
0
/* static */
wxString wxMarkupParser::Quote(const wxString& text)
{
    wxString quoted;
    quoted.reserve(text.length());

    for ( wxString::const_iterator it = text.begin(); it != text.end(); ++it )
    {
        unsigned n;
        for ( n = 0; n < WXSIZEOF(xmlEntities); n++ )
        {
            const XMLEntity& xmlEnt = xmlEntities[n];
            if ( *it == xmlEnt.value )
            {
                quoted << '&' << xmlEnt.name << ';';
                break;
            }
        }

        if ( n == WXSIZEOF(xmlEntities) )
            quoted += *it;
    }

    return quoted;
}
Example #13
0
wxString 
hoxUtil::EscapeURL( const wxString& value )
{
    wxString sResult;

    //  + Percent    ("%") => "%25"
    //  + Ampersand  ("&") => "%26"
    //  + Semi-colon (";") => "%3B" 

    wxUniChar uni_ch;
    for (wxString::const_iterator it = value.begin(); it != value.end(); ++it)
    {
        uni_ch = *it;
        switch ( uni_ch.GetValue() )
        {
            case '%': sResult << "%25"; break;
            case '&': sResult << "%26"; break;
            case ';': sResult << "%3B"; break;
            default:  sResult << uni_ch; break;
        }
    }

    return sResult;
}
bool
wxPdfFontDataCore::CanShow(const wxString& s, const wxPdfEncoding* encoding) const
{
  bool canShow = true;
  const wxPdfChar2GlyphMap* usedMap = NULL;
  if (encoding != NULL)
  {
    usedMap = encoding->GetEncodingMap();
  }
  if (usedMap == NULL)
  {
    usedMap = m_encoding->GetEncodingMap();
  }
  if (usedMap != NULL)
  {
    wxPdfChar2GlyphMap::const_iterator charIter;
    wxString::const_iterator ch;
    for (ch = s.begin(); canShow && ch != s.end(); ++ch)
    {
      canShow = (usedMap->find(*ch) != usedMap->end());
    }
  }
  return canShow;
}
Example #15
0
bool
wxPdfBarCodeCreator::Code128(double x, double y, const wxString& barcode, double h, double w)
{
    // Check whether barcode text is valid
    wxString::const_iterator ch;
    for (ch = barcode.begin(); ch != barcode.end(); ++ch)
    {
        if (!Code128ValidChar(*ch))
        {
            wxLogError(wxString(wxT("wxPdfBarCodeCreator::Code128: ")) +
                       wxString::Format(_("There are illegal characters for Code128 in '%s'."), barcode.c_str()));
            return false;
        }
    }

    bool ucc = false;
    wxString bcode = Code128MakeCode(barcode, ucc);
    size_t len = bcode.length();
    if (len == 0) return false;

    Code128AddCheck(bcode);
    Code128Draw(x, y, bcode, h, w);
    return true;
}
Example #16
0
wxString wxHtmlEntitiesParser::Parse(const wxString& input) const
{
    wxString output;

    const wxString::const_iterator end(input.end());
    wxString::const_iterator c(input.begin());
    wxString::const_iterator last(c);

#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    for ( ; c < end; ++c )
    {
        if (*c == wxT('&'))
        {
            if ( output.empty() )
                output.reserve(input.length());

            if (c - last > 0)
                output.append(last, c);
            if ( ++c == end )
                break;

            wxString entity;
            const wxString::const_iterator ent_s = c;
            wxChar entity_char;

#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
            for ( ; c != end; ++c )
            {
                wxChar ch = *c;
                if ( !((ch >= wxT('a') && ch <= wxT('z')) ||
                       (ch >= wxT('A') && ch <= wxT('Z')) ||
                       (ch >= wxT('0') && ch <= wxT('9')) ||
                        ch == wxT('_') || ch == wxT('#')) )
                    break;
            }

            entity.append(ent_s, c);
            if (c == end || *c != wxT(';')) --c;
            last = c+1;
            entity_char = GetEntityChar(entity);
            if (entity_char)
                output << entity_char;
            else
            {
                output.append(ent_s-1, c+1);
                wxLogTrace(wxTRACE_HTML_DEBUG,
                           "Unrecognized HTML entity: '%s'",
                           entity);
            }
        }
    }
    if ( last == input.begin() ) // common case: no entity
        return input;
    if ( last != end )
        output.append(last, end);
    return output;
}
void CCManager::RegisterAutoLaunchChars(const wxString& chars, cbCodeCompletionPlugin* registrant)
{
    if (registrant)
        m_AutoLaunchChars[registrant] = std::set<wxChar>(chars.begin(), chars.end());
}
Example #18
0
bool StringEmptyOrWhitespace(const wxString &str) {
	return std::all_of(str.begin(), str.end(), IsWhitespace);
}
Example #19
0
static wxString GTKProcessMnemonics(const wxString& label, MnemonicsFlag flag)
{
    wxString labelGTK;
    labelGTK.reserve(label.length());
    for ( wxString::const_iterator i = label.begin(); i != label.end(); ++i )
    {
        wxChar ch = *i;

        switch ( ch )
        {
            case wxT('&'):
                if ( i + 1 == label.end() )
                {
                    // "&" at the end of string is an error
                    wxLogDebug(wxT("Invalid label \"%s\"."), label);
                    break;
                }

                if ( flag == MNEMONICS_CONVERT_MARKUP )
                {
                    bool isMnemonic = true;
                    size_t distanceFromEnd = label.end() - i;

                    // is this ampersand introducing a mnemonic or rather an entity?
                    for (size_t j=0; j < WXSIZEOF(entitiesNames); j++)
                    {
                        const char *entity = entitiesNames[j];
                        size_t entityLen = wxStrlen(entity);

                        if (distanceFromEnd >= entityLen &&
                            wxString(i, i + entityLen) == entity)
                        {
                            labelGTK << entity;
                            i += entityLen - 1;     // the -1 is because main for()
                                                    // loop already increments i
                            isMnemonic = false;

                            break;
                        }
                    }

                    if (!isMnemonic)
                        continue;
                }

                ch = *(++i); // skip '&' itself
                switch ( ch )
                {
                    case wxT('&'):
                        // special case: "&&" is not a mnemonic at all but just
                        // an escaped "&"
                        if ( flag == MNEMONICS_CONVERT_MARKUP )
                            labelGTK += wxT("&amp;");
                        else
                            labelGTK += wxT('&');
                        break;

                    case wxT('_'):
                        if ( flag != MNEMONICS_REMOVE )
                        {
                            // '_' can't be a GTK mnemonic apparently so
                            // replace it with something similar
                            labelGTK += wxT("_-");
                            break;
                        }
                        //else: fall through

                    default:
                        if ( flag != MNEMONICS_REMOVE )
                            labelGTK += wxT('_');
                        labelGTK += ch;
                }
                break;

            case wxT('_'):
                if ( flag != MNEMONICS_REMOVE )
                {
                    // escape any existing underlines in the string so that
                    // they don't become mnemonics accidentally
                    labelGTK += wxT("__");
                    break;
                }
                //else: fall through

            default:
                labelGTK += ch;
        }
    }

    return labelGTK;
}
void wxTextMeasureBase::GetMultiLineTextExtent(const wxString& text,
                                               wxCoord *width,
                                               wxCoord *height,
                                               wxCoord *heightOneLine)
{
    MeasuringGuard guard(*this);

    wxCoord widthTextMax = 0, widthLine,
            heightTextTotal = 0, heightLineDefault = 0, heightLine = 0;

    wxString curLine;
    for ( wxString::const_iterator pc = text.begin(); ; ++pc )
    {
        if ( pc == text.end() || *pc == wxS('\n') )
        {
            if ( curLine.empty() )
            {
                // we can't use GetTextExtent - it will return 0 for both width
                // and height and an empty line should count in height
                // calculation

                // assume that this line has the same height as the previous
                // one
                if ( !heightLineDefault )
                    heightLineDefault = heightLine;

                if ( !heightLineDefault )
                {
                    // but we don't know it yet - choose something reasonable
                    int dummy;
                    CallGetTextExtent(wxS("W"), &dummy, &heightLineDefault);
                }

                heightTextTotal += heightLineDefault;
            }
            else
            {
                CallGetTextExtent(curLine, &widthLine, &heightLine);
                if ( widthLine > widthTextMax )
                    widthTextMax = widthLine;
                heightTextTotal += heightLine;
            }

            if ( pc == text.end() )
            {
               break;
            }
            else // '\n'
            {
               curLine.clear();
            }
        }
        else
        {
            curLine += *pc;
        }
    }

    if ( width )
        *width = widthTextMax;
    if ( height )
        *height = heightTextTotal;
    if ( heightOneLine )
        *heightOneLine = heightLine;
}
Example #21
0
wxString wxTextBuffer::Translate(const wxString& text, wxTextFileType type)
{
    // don't do anything if there is nothing to do
    if ( type == wxTextFileType_None )
        return text;

    // nor if it is empty
    if ( text.empty() )
        return text;

    wxString eol = GetEOL(type), result;

    // optimization: we know that the length of the new string will be about
    // the same as the length of the old one, so prealloc memory to avoid
    // unnecessary relocations
    result.Alloc(text.Len());

    wxChar chLast = 0;
    for ( wxString::const_iterator i = text.begin(); i != text.end(); ++i )
    {
        wxChar ch = *i;
        switch ( ch ) {
            case wxT('\n'):
                // Dos/Unix line termination
                result += eol;
                chLast = 0;
                break;

            case wxT('\r'):
                if ( chLast == wxT('\r') ) {
                    // Mac empty line
                    result += eol;
                }
                else {
                    // just remember it: we don't know whether it is just "\r"
                    // or "\r\n" yet
                    chLast = wxT('\r');
                }
                break;

            default:
                if ( chLast == wxT('\r') ) {
                    // Mac line termination
                    result += eol;

                    // reset chLast to avoid inserting another eol before the
                    // next character
                    chLast = 0;
                }

                // add to the current line
                result += ch;
        }
    }

    if ( chLast ) {
        // trailing '\r'
        result += eol;
    }

    return result;
}
Example #22
0
/* static */
wxString wxStaticTextBase::RemoveMarkup(const wxString& text)
{
    // strip out of "text" the markup for platforms which don't support it natively
    bool inside_tag = false;

    wxString label;
    for ( wxString::const_iterator source = text.begin();
          source != text.end(); ++source )
    {
        switch ( (*source).GetValue() )
        {
            case wxT('<'):
                if (inside_tag)
                {
                    wxLogDebug(wxT("Invalid markup !"));
                    return wxEmptyString;
                }
                inside_tag = true;
                break;

            case wxT('>'):
                if (!inside_tag)
                {
                    wxLogDebug(wxT("Invalid markup !"));
                    return wxEmptyString;
                }
                inside_tag = false;
                break;

            case wxT('&'):
                {
                    if ( source+1 == text.end() )
                    {
                        wxLogDebug(wxT("Cannot use & as last character of the string '%s'"),
                                   text.c_str());
                        return wxEmptyString;
                    }

                    // is this ampersand introducing a mnemonic or rather an entity?
                    bool isMnemonic = true;
                    size_t distanceFromEnd = text.end() - source;
                    for (size_t j=0; j < wxMARKUP_ENTITY_MAX; j++)
                    {
                        const wxChar *entity = wxMarkupEntities[wxMARKUP_ELEMENT_NAME][j];
                        size_t entityLen = wxStrlen(entity);

                        if (distanceFromEnd >= entityLen &&
                            wxString(source, source + entityLen) == entity)
                        {
                            // replace the &entity; string with the entity reference
                            label << wxMarkupEntities[wxMARKUP_ELEMENT_VALUE][j];
                            // little exception: when the entity reference is
                            // "&" (i.e. when entity is "&amp;"), substitute it
                            // with && instead of a single ampersand:
                            if (*wxMarkupEntities[wxMARKUP_ELEMENT_VALUE][j] == wxT('&'))
                                label << wxT('&');
                            // the -1 is because main for() loop already
                            // increments i:
                            source += entityLen - 1;
                            isMnemonic = false;
                            break;
                        }
                    }

                    if (isMnemonic)
                        label << *source;
                }
                break;


            default:
                if (!inside_tag)
                    label << *source;
        }
    }

    return label;
}
Example #23
0
void wxHtmlWinParser::AddText(const wxString& txt)
{
#if !wxUSE_UNICODE
    if ( m_nbsp == 0 )
        m_nbsp = GetEntitiesParser()->GetCharForCode(NBSP_UNICODE_VALUE);
#endif

    if ( m_whitespaceMode == Whitespace_Normal )
    {
        int templen = 0;

        size_t lng = txt.length();
        if (lng+1 > m_tmpStrBufSize)
        {
            delete[] m_tmpStrBuf;
            m_tmpStrBuf = new wxChar[lng+1];
            m_tmpStrBufSize = lng+1;
        }
        wxChar *temp = m_tmpStrBuf;

        wxString::const_iterator i = txt.begin();
        const wxString::const_iterator end = txt.end();

        if (m_tmpLastWasSpace)
        {
            while ( (i < end) &&
                    (*i == wxT('\n') || *i == wxT('\r') || *i == wxT(' ') ||
                     *i == wxT('\t')) )
            {
                ++i;
            }
        }

        while (i < end)
        {
            size_t x = 0;
            const wxChar d = temp[templen++] = *i;
            if ((d == wxT('\n')) || (d == wxT('\r')) || (d == wxT(' ')) || (d == wxT('\t')))
            {
                ++i, ++x;
                while ( (i < end) &&
                        (*i == wxT('\n') || *i == wxT('\r') ||
                         *i == wxT(' ') || *i == wxT('\t')) )
                {
                    ++i;
                    ++x;
                }
            }
            else
            {
                ++i;
            }

            if (x)
            {
                temp[templen-1] = wxT(' ');
                FlushWordBuf(temp, templen);
                m_tmpLastWasSpace = true;
            }
        }

        if (templen && (templen > 1 || temp[0] != wxT(' ')))
        {
            FlushWordBuf(temp, templen);
            m_tmpLastWasSpace = false;
        }
    }
    else // m_whitespaceMode == Whitespace_Pre
    {
        if ( txt.find(CUR_NBSP_VALUE) != wxString::npos )
        {
            // we need to substitute spaces for &nbsp; here just like we
            // did in the Whitespace_Normal branch above
            wxString txt2(txt);
            txt2.Replace(CUR_NBSP_VALUE, ' ');
            AddPreBlock(txt2);
        }
        else
        {
            AddPreBlock(txt);
        }

        // don't eat any whitespace in <pre> block
        m_tmpLastWasSpace = false;
    }
}
Example #24
0
bool wxMarkupParser::Parse(const wxString& text)
{
    // The stack containing the names and corresponding attributes (which are
    // actually only used for <span> tags) of all of the currently opened tag
    // or none if we're not inside any tag.
    wxStack<TagAndAttrs> tags;

    // Current run of text.
    wxString current;

    const wxString::const_iterator end = text.end();
    for ( wxString::const_iterator it = text.begin(); it != end; ++it )
    {
        switch ( (*it).GetValue() )
        {
            case '<':
                {
                    // Flush the text preceding the tag, if any.
                    if ( !current.empty() )
                    {
                        m_output.OnText(current);
                        current.clear();
                    }

                    // Remember the tag starting position for the error
                    // messages.
                    const size_t pos = it - text.begin();

                    bool start = true;
                    if ( ++it != end && *it == '/' )
                    {
                        start = false;
                        ++it;
                    }

                    const wxString tag = ExtractUntil('>', it, end);
                    if ( tag.empty() )
                    {
                        wxLogDebug("%s at %lu.",
                                   it == end ? "Unclosed tag starting"
                                             : "Empty tag",
                                   pos);
                        return false;
                    }

                    if ( start )
                    {
                        wxString attrs;
                        const wxString name = tag.BeforeFirst(' ', &attrs);

                        TagAndAttrs tagAndAttrs(name);
                        const wxString err = ParseAttrs(attrs, tagAndAttrs);
                        if ( !err.empty() )
                        {
                            wxLogDebug("Bad attributes for \"%s\" "
                                       "at %lu: %s.",
                                       name, pos, err);
                            return false;
                        }

                        tags.push(tagAndAttrs);
                    }
                    else // end tag
                    {
                        if ( tags.empty() || tags.top().name != tag )
                        {
                            wxLogDebug("Unmatched closing tag \"%s\" at %lu.",
                                       tag, pos);
                            return false;
                        }
                    }

                    if ( !OutputTag(tags.top(), start) )
                    {
                        wxLogDebug("Unknown tag at %lu.", pos);
                        return false;
                    }

                    if ( !start )
                        tags.pop();
                }
                break;

            case '>':
                wxLogDebug("'>' should be escaped as \"&gt\"; at %lu.",
                           it - text.begin());
                break;

            case '&':
                // Processing is somewhat complicated: we need to recognize at
                // least the "&lt;" entity to allow escaping left square
                // brackets in the markup and, in fact, we recognize all of the
                // standard XML entities for consistency with Pango markup
                // parsing.
                //
                // However we also allow '&' to appear unescaped, i.e. directly
                // and not as "&amp;" when it is used to introduce the mnemonic
                // for the label. In this case we simply leave it alone.
                //
                // Notice that this logic makes it impossible to have a label
                // with "lt;" inside it and using "l" as mnemonic but hopefully
                // this shouldn't be a problem in practice.
                {
                    const size_t pos = it - text.begin() + 1;

                    unsigned n;
                    for ( n = 0; n < WXSIZEOF(xmlEntities); n++ )
                    {
                        const XMLEntity& xmlEnt = xmlEntities[n];
                        if ( text.compare(pos, xmlEnt.len, xmlEnt.name) == 0
                                && text[pos + xmlEnt.len] == ';' )
                        {
                            // Escape the ampersands if needed to protect them
                            // from being interpreted as mnemonics indicators.
                            if ( xmlEnt.value == '&' )
                                current += "&&";
                            else
                                current += xmlEnt.value;

                            it += xmlEnt.len + 1; // +1 for '&' itself

                            break;
                        }
                    }

                    if ( n < WXSIZEOF(xmlEntities) )
                        break;
                    //else: fall through, '&' is not special
                }

            default:
                current += *it;
        }
    }

    if ( !tags.empty() )
    {
        wxLogDebug("Missing closing tag for \"%s\"", tags.top().name);
        return false;
    }

    if ( !current.empty() )
        m_output.OnText(current);

    return true;
}
Example #25
0
wxString wxHtmlHelpData::FindPageByName(const wxString& x)
{
    int i;

    bool has_non_ascii = false;
    wxString::const_iterator it;
    for (it = x.begin(); it != x.end(); ++it)
    {
        wxUniChar ch = *it;
        if (!ch.IsAscii())
        {
            has_non_ascii = true;
            break;
        }
    }

    int cnt = m_bookRecords.GetCount();

    if (!has_non_ascii)
    {
      wxFileSystem fsys;
      wxFSFile *f;
      // 1. try to open given file:
      for (i = 0; i < cnt; i++)
      {
        f = fsys.OpenFile(m_bookRecords[i].GetFullPath(x));
        if (f)
        {
            wxString url = m_bookRecords[i].GetFullPath(x);
            delete f;
            return url;
        }
      }
    }


    // 2. try to find a book:
    for (i = 0; i < cnt; i++)
    {
        if (m_bookRecords[i].GetTitle() == x)
            return m_bookRecords[i].GetFullPath(m_bookRecords[i].GetStart());
    }

    // 3. try to find in contents:
    cnt = m_contents.size();
    for (i = 0; i < cnt; i++)
    {
        if (m_contents[i].name == x)
            return m_contents[i].GetFullPath();
    }


    // 4. try to find in index:
    cnt = m_index.size();
    for (i = 0; i < cnt; i++)
    {
        if (m_index[i].name == x)
            return m_index[i].GetFullPath();
    }

    // 4b. if still not found, try case-insensitive comparison
    for (i = 0; i < cnt; i++)
    {
        if (m_index[i].name.CmpNoCase(x) == 0)
            return m_index[i].GetFullPath();
    }

    return wxEmptyString;
}
Example #26
0
void GetTextExtent( const wxFont& font, const wxString& str, wxCoord *width, wxCoord *height,
                            wxCoord *descent, wxCoord *externalLeading )
{
    HDC dc = GetDC(0);
    WXHFONT hFont = font.GetHFONT();
    ::SelectObject(dc, hFont);

    HFONT hfontOld;
    if ( font != wxNullFont )
    {
        wxASSERT_MSG( font.Ok(), _T("invalid font in wxDC::GetTextExtent") );

        hfontOld = (HFONT)::SelectObject(dc, hFont);
    }
    else // don't change the font
    {
        hfontOld = 0;
    }

    SIZE sizeRect;
    const size_t len = str.length();
    if ( !::GetTextExtentPoint32(dc, str, len, &sizeRect) )
    {
        wxLogLastError(_T("GetTextExtentPoint32()"));
    }

#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
    // the result computed by GetTextExtentPoint32() may be too small as it
    // accounts for under/overhang of the first/last character while we want
    // just the bounding rect for this string so adjust the width as needed
    // (using API not available in 2002 SDKs of WinCE)
    if ( len > 1 )
    {
        ABC width;
        const wxChar chFirst = *str.begin();
        if ( ::GetCharABCWidths(dc, chFirst, chFirst, &width) )
        {
            if ( width.abcA < 0 )
                sizeRect.cx -= width.abcA;

            if ( len > 1 )
            {
                const wxChar chLast = *str.rbegin();
                ::GetCharABCWidths(dc, chLast, chLast, &width);
            }
            //else: we already have the width of the last character

            if ( width.abcC < 0 )
                sizeRect.cx -= width.abcC;
        }
        //else: GetCharABCWidths() failed, not a TrueType font?
    }
#endif // !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)

    TEXTMETRIC tm;
    ::GetTextMetrics(dc, &tm);

    if (width)
        *width = sizeRect.cx;
    if (height)
        *height = sizeRect.cy;
    if (descent)
        *descent = tm.tmDescent;
    if (externalLeading)
        *externalLeading = tm.tmExternalLeading;

    if ( hfontOld )
    {
        ::SelectObject(dc, hfontOld);
    }
    
    ReleaseDC(0, dc);
}
Example #27
0
wxHtmlTagsCache::wxHtmlTagsCache(const wxString& source)
{
    m_Cache = new wxHtmlTagsCacheData;
    m_CachePos = 0;

    wxChar tagBuffer[256];

    const wxString::const_iterator end = source.end();
    for ( wxString::const_iterator pos = source.begin(); pos < end; ++pos )
    {
        if (*pos != wxT('<'))
            continue;

        // possible tag start found:

        // don't cache comment tags
        if ( wxHtmlParser::SkipCommentTag(pos, end) )
            continue;

        // Remember the starting tag position.
        wxString::const_iterator stpos = pos++;

        // And look for the ending one.
        int i;
        for ( i = 0;
              pos < end && i < (int)WXSIZEOF(tagBuffer) - 1 &&
              *pos != wxT('>') && !wxIsspace(*pos);
              ++i, ++pos )
        {
            tagBuffer[i] = (wxChar)wxToupper(*pos);
        }
        tagBuffer[i] = wxT('\0');

        while (pos < end && *pos != wxT('>'))
            ++pos;

        if ( pos == end )
        {
            // We didn't find a closing bracket, this is not a valid tag after
            // all. Notice that we need to roll back pos to avoid creating an
            // invalid iterator when "++pos" is done in the loop statement.
            --pos;

            continue;
        }

        // We have a valid tag, add it to the cache.
        size_t tg = Cache().size();
        Cache().push_back(wxHtmlCacheItem());
        Cache()[tg].Key = stpos;
        Cache()[tg].Name = new wxChar[i+1];
        memcpy(Cache()[tg].Name, tagBuffer, (i+1)*sizeof(wxChar));

        if ((stpos+1) < end && *(stpos+1) == wxT('/')) // ending tag:
        {
            Cache()[tg].type = wxHtmlCacheItem::Type_EndingTag;
            // find matching begin tag:
            for (i = tg; i >= 0; i--)
            {
                if ((Cache()[i].type == wxHtmlCacheItem::Type_NoMatchingEndingTag) && (wxStrcmp(Cache()[i].Name, tagBuffer+1) == 0))
                {
                    Cache()[i].type = wxHtmlCacheItem::Type_Normal;
                    Cache()[i].End1 = stpos;
                    Cache()[i].End2 = pos + 1;
                    break;
                }
            }
        }
        else
        {
            Cache()[tg].type = wxHtmlCacheItem::Type_NoMatchingEndingTag;

            if (wxIsCDATAElement(tagBuffer))
            {
                // store the orig pos in case we are missing the closing
                // tag (see below)
                const wxString::const_iterator old_pos = pos;
                bool foundCloseTag = false;

                // find next matching tag
                int tag_len = wxStrlen(tagBuffer);
                while (pos < end)
                {
                    // find the ending tag
                    while (pos + 1 < end &&
                           (*pos != '<' || *(pos+1) != '/'))
                        ++pos;
                    if (*pos == '<')
                        ++pos;

                    // see if it matches
                    int match_pos = 0;
                    while (pos < end && match_pos < tag_len )
                    {
                        wxChar c = *pos;
                        if ( c == '>' || c == '<' )
                            break;

                        // cast to wxChar needed to suppress warning in
                        // Unicode build
                        if ((wxChar)wxToupper(c) == tagBuffer[match_pos])
                        {
                            ++match_pos;
                        }
                        else if (c == wxT(' ') || c == wxT('\n') ||
                            c == wxT('\r') || c == wxT('\t'))
                        {
                            // need to skip over these
                        }
                        else
                        {
                            match_pos = 0;
                        }
                        ++pos;
                    }

                    // found a match
                    if (match_pos == tag_len)
                    {
                        pos = pos - tag_len - 3;
                        foundCloseTag = true;
                        break;
                    }
                    else // keep looking for the closing tag
                    {
                        ++pos;
                    }
                }
                if (!foundCloseTag)
                {
                    // we didn't find closing tag; this means the markup
                    // is incorrect and the best thing we can do is to
                    // ignore the unclosed tag and continue parsing as if
                    // it didn't exist:
                    pos = old_pos;
                }
            }
        }
    }

    // ok, we're done, now we'll free .Name members of cache - we don't need it anymore:
    for ( wxHtmlTagsCacheData::iterator i = Cache().begin();
          i != Cache().end(); ++i )
    {
        wxDELETEA(i->Name);
    }
}
Example #28
0
//Fill array with string passed
void wxFixWidthImportCtrl::LoadText(const wxString& textInside)
{
    wxString singleLine, tabRep;
    wxChar ch;
    bool at_eol = false;
    size_t pos = 0;
    size_t nSp = 0;

    m_Lines.Clear();
    m_maxLen = 0;

    //Use code similar to wxTextBuffer::Translate
    wxChar chLast = 0;
    for ( wxString::const_iterator i = textInside.begin(); i != textInside.end(); ++i )
    {
        ch = *i;
        if ( ch == wxT('\n') )
        {
            at_eol = true;
            chLast = 0;
        }
        else if (ch == wxT('\r') )
        {
            if ( chLast == wxT('\r') )
            {// Mac empty line
                at_eol = true;
            }
            else
            {// just remember it: we don't know whether it is just "\r" or "\r\n" yet
                chLast = wxT('\r');
            }
        }
        else
        {
            if ( chLast == wxT('\r') )
            {// Mac line termination
                at_eol = true;
                chLast = 0;
            }
        }
        if ( at_eol )
        {
            if (singleLine.Len() > m_maxLen)
                m_maxLen = singleLine.Len();

            m_Lines.Add(singleLine);
            singleLine = wxT("");
            at_eol = false;
            pos = 0;
        }
        if ( ch != wxT('\n') && ch != wxT('\r') )
        {
            if (m_tabSize > -1 && ch == wxT('\t') )
            {//insert needed spaces so text becomes 'tabulated'
                if ( m_tabSize > 0) //m_tabSize=0 means 'erase this TAB'
                {   tabRep = wxT("");
                    nSp = (size_t)m_tabSize - (pos % (size_t)m_tabSize);
                    tabRep.Append(wxChar(' '), nSp);
                    singleLine += tabRep;
                    pos += nSp;
                }
            }
            else
            {
                singleLine += ch;
                pos++;
            }
        }
    }
    //Check if we are at a last Mac line
    if (chLast == wxT('\r') )
    {
        m_Lines.Add(singleLine);
        if (singleLine.Len() > m_maxLen)
            m_maxLen = singleLine.Len();
        singleLine = wxT("");
    }
    if (singleLine.Len() > 0) //pending line
    {   m_Lines.Add(singleLine);
        if (singleLine.Len() > m_maxLen)
            m_maxLen = singleLine.Len();
    }

    m_curposX = m_curposL = m_markedL = m_LAct = 0;
    AdjustScrollbars();
    Refresh();
    FireEvent();
}
void LocationPanel::indentStructure ( wxString& structure )
{
	wxString indented;
	wxString::const_iterator s = structure.begin();
	int indent = 0;
	const static wxString indentMark ( _T("\t") );

	int count = 0;
	bool justSeenContent = false;
	for ( ; *s; ++s, count++)
	{
		if (*s == '(')
		{
			if ( count && justSeenContent )
			{
				indented += '\n';
			}
			else if (!justSeenContent)
				indented += *s;
			for ( int i = 0; i < indent; i++ )
			{
				indented += indentMark;
			}
			if (justSeenContent)
				indented += *s;

			indent++;

			indented += '\n';
		
			for (int i = 0; indent && i < indent; i++)
				indented += indentMark;
			justSeenContent = false;
		}
		else if (*s == ')')
		{
			if ( justSeenContent )
			{
				indented += '\n';
			}
			indent--;
			for (int i = 0; indent && i < indent; i++)
				indented += indentMark;
			indented += *s;
			indented += '\n';
			if (*( s + 1 ) && *(s + 1) != ')' )
			{
				for (int i = 0; i < indent; i++)
					indented += indentMark;
			}
			justSeenContent = false;
		}
		else
		{
            if ( *s == '|' && justSeenContent)
               indented += ' ';
			indented += *s;
			if ( *s == ',' || *s == '|' )
			   indented += ' ';
			justSeenContent = true;
		}
	}
	structure = indented;
}
Example #30
0
/* static */
wxArrayString
wxCmdLineParser::ConvertStringToArgs(const wxString& cmdline,
                                     wxCmdLineSplitType type)
{
    wxArrayString args;

    wxString arg;
    arg.reserve(1024);

    const wxString::const_iterator end = cmdline.end();
    wxString::const_iterator p = cmdline.begin();

    for ( ;; )
    {
        // skip white space
        while ( p != end && (*p == ' ' || *p == '\t') )
            ++p;

        // anything left?
        if ( p == end )
            break;

        // parse this parameter
        bool lastBS = false,
             isInsideQuotes = false;
        wxChar chDelim = '\0';
        for ( arg.clear(); p != end; ++p )
        {
            const wxChar ch = *p;

            if ( type == wxCMD_LINE_SPLIT_DOS )
            {
                if ( ch == '"' )
                {
                    if ( !lastBS )
                    {
                        isInsideQuotes = !isInsideQuotes;

                        // don't put quote in arg
                        continue;
                    }
                    //else: quote has no special meaning but the backslash
                    //      still remains -- makes no sense but this is what
                    //      Windows does
                }
                // note that backslash does *not* quote the space, only quotes do
                else if ( !isInsideQuotes && (ch == ' ' || ch == '\t') )
                {
                    ++p;    // skip this space anyhow
                    break;
                }

                lastBS = !lastBS && ch == '\\';
            }
            else // type == wxCMD_LINE_SPLIT_UNIX
            {
                if ( !lastBS )
                {
                    if ( isInsideQuotes )
                    {
                        if ( ch == chDelim )
                        {
                            isInsideQuotes = false;

                            continue;   // don't use the quote itself
                        }
                    }
                    else // not in quotes and not escaped
                    {
                        if ( ch == '\'' || ch == '"' )
                        {
                            isInsideQuotes = true;
                            chDelim = ch;

                            continue;   // don't use the quote itself
                        }

                        if ( ch == ' ' || ch == '\t' )
                        {
                            ++p;    // skip this space anyhow
                            break;
                        }
                    }

                    lastBS = ch == '\\';
                    if ( lastBS )
                        continue;
                }
                else // escaped by backslash, just use as is
                {
                    lastBS = false;
                }
            }

            arg += ch;
        }

        args.push_back(arg);
    }

    return args;
}