示例#1
0
void wxStaticText::DrawParagraph(wxDC &dc, wxString paragraph, int &y)
{
    long width, height ;
  
    if (paragraph.Length() == 0)
    {
        // empty line
        dc.GetTextExtent( wxT("H"), &width, &height );
        y += height;
        
        return;
    }

    int x = 0 ;

    bool linedrawn = true;
    while( paragraph.Length() > 0 )
    {
        dc.GetTextExtent( paragraph , &width , &height ) ;
        
        if ( width > m_width )
        {
            for ( size_t p = paragraph.Length() - 1 ; p > 0 ; --p )
            {
                if ((punct.Find(paragraph[p]) != wxNOT_FOUND) || !linedrawn)
                {
                    int blank = (paragraph[p] == ' ') ? 0 : 1;
                    
                    dc.GetTextExtent( paragraph.Left(p + blank) , &width , &height ) ;
                    
                    if ( width <= m_width )
                    {
                        int pos = x ;
                        if ( HasFlag( wxALIGN_CENTER ) )
                        {
                            pos += ( m_width - width ) / 2 ;
                        }
                        else if ( HasFlag( wxALIGN_RIGHT ) )
                        {
                            pos += ( m_width - width ) ;
                        }
                        
                        dc.DrawText( paragraph.Left(p + blank), pos , y) ;
                        y += height ;
                        paragraph = paragraph.Mid(p+1) ;
                        linedrawn = true;
                        break ;
                    }
                }
            }
            
            linedrawn = false;
        }
        else
        {
            int pos = x ;
            if ( HasFlag( wxALIGN_CENTER ) )
            {
                pos += ( m_width - width ) / 2 ;
            }
            else if ( HasFlag( wxALIGN_RIGHT ) )
            {
                pos += ( m_width - width ) ;
            }
            
            dc.DrawText( paragraph, pos , y) ;
            paragraph=wxEmptyString;
            y += height ;
        }
    }
}
示例#2
0
/** This function determines the caracteristics of a given strLine (bCode strLine, bComment strLine etc...).
 *  It is called by the "CountLines" function.
 *  @see CountLines
 */
void Counter::analyseLine2(CounterRule* pRule, wxString strLine, bool& bScriptMode, bool &bComment, bool &bCode, bool &bDelimitedCommentMode)
{
    int nIdxFirstScriptBegin, nIdxFirstScriptEnd;
    int nIdxFirstSglLnComm, nIdxFirstMltLnCommBegin, nIdxFirstMltLnCommEnd;

    //
    // Delete first and trailing spaces
    //
    strLine = strLine.Trim(true);
    strLine = strLine.Trim(false);

    if (strLine.IsEmpty())
        return;

    //
    // Searching for script signs
    //
    if (pRule->m_strScriptBegin.Len() > 0)
        nIdxFirstScriptBegin = strLine.Find(pRule->m_strScriptBegin);
    else nIdxFirstScriptBegin = -1;
    if (pRule->m_strScriptEnd.Len() > 0)
        nIdxFirstScriptEnd = strLine.Find(pRule->m_strScriptEnd);
    else nIdxFirstScriptEnd = -1;

    //
    // Searching for single and multi-lines bComment signs
    //
    if (pRule->m_strSglLnComm.Len() > 0)
        nIdxFirstSglLnComm = strLine.Find(pRule->m_strSglLnComm);
    else nIdxFirstSglLnComm = -1;
    if (pRule->m_strMltLnCommBegin.Len() > 0)
        nIdxFirstMltLnCommBegin = strLine.Find(pRule->m_strMltLnCommBegin);
    else nIdxFirstMltLnCommBegin = -1;
    if (pRule->m_strMltLnCommEnd.Len() > 0)
        nIdxFirstMltLnCommEnd = strLine.Find(pRule->m_strMltLnCommEnd);
    else nIdxFirstMltLnCommEnd = -1;

    //
    // Analyse
    //


    if (bScriptMode)
    {
        // We are in a multiple strLine Comment => finding the "end of multiple Line Comment" sign
        if (bDelimitedCommentMode)
        {
            bComment = true;
            if (nIdxFirstMltLnCommEnd > -1)
            {
                bDelimitedCommentMode = false;
                if (nIdxFirstMltLnCommEnd + pRule->m_strMltLnCommEnd.Len() < strLine.Length())
                    analyseLine2(pRule, strLine.Mid(nIdxFirstMltLnCommEnd + pRule->m_strMltLnCommEnd.Length()),
                                 bScriptMode, bComment, bCode, bDelimitedCommentMode);
            }
        }
        // We are not in a multiple strLine bComment
        else if (!bDelimitedCommentMode)
        {
            // First bComment sign found is a single strLine bComment sign
            if ( (nIdxFirstSglLnComm>-1)
                    &&((nIdxFirstMltLnCommBegin==-1)
                       ||((nIdxFirstMltLnCommBegin>-1)&&(nIdxFirstSglLnComm<nIdxFirstMltLnCommBegin))) )
            {
                bComment = true;
                if (nIdxFirstSglLnComm > 0)
                    bCode = true;
            }
            // First bComment sign found is a multi-strLine bComment begin sign
            else if (nIdxFirstMltLnCommBegin>-1)
            {
                bDelimitedCommentMode = true;
                bComment = true;
                if (nIdxFirstMltLnCommBegin > 0)
                    bCode = true;
                if (nIdxFirstMltLnCommBegin+pRule->m_strMltLnCommBegin.Len() < strLine.Length())
                    analyseLine2(pRule, strLine.Mid(nIdxFirstMltLnCommBegin + pRule->m_strMltLnCommBegin.Length()),
                                 bScriptMode, bComment, bCode, bDelimitedCommentMode);
            }
            else
            {
                bCode = true;
            }
        }

    }
    else if (!bScriptMode)
    {
        if (nIdxFirstScriptBegin > -1)
        {
            bScriptMode = true;

            if (nIdxFirstScriptEnd > -1)
            {
                bScriptMode = false;
                if (nIdxFirstScriptEnd + pRule->m_strScriptEnd.Len() < strLine.Len())
                {
                    analyseLine2(pRule, strLine.Mid(nIdxFirstScriptEnd + pRule->m_strScriptEnd.Length()),
                                 bScriptMode, bComment, bCode, bDelimitedCommentMode);
                }
            }
        }
    }


}
示例#3
0
void pgHbaConfigLine::Init(const wxString &line)
{
	connectType = PGC_INVALIDCONF;
	changed = false;

	if (line.IsEmpty())
		return;

	text = line;

	const wxChar *p0 = line.c_str();

	if (*p0 == '#')
	{
		isComment = true;
		p0++;
		SkipSpace(p0);
	}
	else
		isComment = false;


	const wxChar *p1 = p0;
	SkipNonspace(p1);

	wxString str = line.Mid(p0 - line.c_str(), p1 - p0);

	int i = FindToken(str, pgHbaConnectTypeStrings);

	if (i >= 0)
		connectType = (pgHbaConnectType)i;
	else
	{
		connectType = PGC_INVALIDCONF;
		isComment = true;
		return;
	}

	SkipSpace(p1);

	const wxChar *p2 = p1;
	bool quoted = false;

	while (*p2)
	{
		if (!quoted && IsSpaceChar(*p2))
			break;
		if (*p2 == '"')
			quoted = !quoted;
		p2++;
	}

	database = line.Mid(p1 - line.c_str(), p2 - p1);

	SkipSpace(p2);

	const wxChar *p3 = p2;

	quoted = false;
	while (*p3)
	{
		if (!quoted && IsSpaceChar(*p3))
			break;
		if (*p3 == '"')
			quoted = !quoted;
		p3++;
	}

	user = line.Mid(p2 - line.c_str(), p3 - p2);

	SkipSpace(p3);

	const wxChar *p4 = p3;

	if (connectType == PGC_LOCAL)
	{
		// no ip address
	}
	else
	{
		bool hasCidr = false;
		while (*p4 && !IsSpaceChar(*p4))
		{
			if (*p4 == '/')
				hasCidr = true;
			p4++;
		}
		if (!hasCidr)
		{
			SkipSpace(p4);
			SkipNonspace(p4);
		}

		ipaddress = line.Mid(p3 - line.c_str(), p4 - p3);
		SkipSpace(p4);
	}

	const wxChar *p5 = p4;
	SkipNonspace(p5);

	str = line.Mid(p4 - line.c_str(), p5 - p4);

	i = FindToken(str, pgHbaMethodStrings);

	if (i >= 0)
		method = (pgHbaMethod)i;
	else
	{
		connectType = PGC_INVALIDCONF;
		isComment = true;
		return;
	}
	SkipSpace(p5);
	option = p5;
}
wxString CRCppEmitter::MakeFirstCharLowerCase (const wxString &str) const
{
    wxString firstChar = str.Mid(0, 1).Lower();
    return firstChar + str.Mid(1);
}
示例#5
0
bool CSiteManager::GetBookmarks(wxString sitePath, std::list<wxString> &bookmarks)
{
	wxChar c = sitePath[0];
	if (c != '0' && c != '1')
		return false;

	sitePath = sitePath.Mid(1);

	// We have to synchronize access to sitemanager.xml so that multiple processed don't write
	// to the same file or one is reading while the other one writes.
	CInterProcessMutex mutex(MUTEX_SITEMANAGER);

	CXmlFile file;
	TiXmlElement* pDocument = 0;

	if (c == '0')
		pDocument = file.Load(_T("sitemanager"));
	else
	{
		const wxString& defaultsDir = wxGetApp().GetDefaultsDir();
		if (defaultsDir == _T(""))
			return false;
		pDocument = file.Load(wxFileName(defaultsDir, _T("fzdefaults.xml")));
	}

	if (!pDocument)
	{
		wxMessageBox(file.GetError(), _("Error loading xml file"), wxICON_ERROR);

		return false;
	}

	TiXmlElement* pElement = pDocument->FirstChildElement("Servers");
	if (!pElement)
		return false;

	std::list<wxString> segments;
	if (!UnescapeSitePath(sitePath, segments))
	{
		wxMessageBox(_("Site path is malformed."), _("Invalid site path"));
		return 0;
	}

	TiXmlElement* pChild = GetElementByPath(pElement, segments);
	if (!pChild || strcmp(pChild->Value(), "Server"))
		return 0;

	// Bookmarks
	for (TiXmlElement* pBookmark = pChild->FirstChildElement("Bookmark"); pBookmark; pBookmark = pBookmark->NextSiblingElement("Bookmark"))
	{
		TiXmlHandle handle(pBookmark);

		wxString name = GetTextElement_Trimmed(pBookmark, "Name");
		if (name.empty())
			continue;

		wxString localPath;
		CServerPath remotePath;
		TiXmlText* localDir = handle.FirstChildElement("LocalDir").FirstChild().Text();
		if (localDir)
			localPath = ConvLocal(localDir->Value());
		TiXmlText* remoteDir = handle.FirstChildElement("RemoteDir").FirstChild().Text();
		if (remoteDir)
			remotePath.SetSafePath(ConvLocal(remoteDir->Value()));

		if (localPath.empty() && remotePath.IsEmpty())
			continue;

		bookmarks.push_back(name);
	}

	return true;
}
wxInt32 NaturalCompare(wxString String1, wxString String2, bool CaseSensitive = false)
{
    wxInt32 StringCounter1 = 0, StringCounter2 = 0;
    wxInt32 String1Zeroes = 0, String2Zeroes = 0;
    wxChar String1Char, String2Char;
    wxInt32 Result;

    if (!CaseSensitive)
    {
        String1.MakeLower();
        String2.MakeLower();
    }

    while (true)
    {
        String1Zeroes = 0;
        String2Zeroes = 0;

        String1Char = String1[StringCounter1];
        String2Char = String2[StringCounter2];

        // skip past whitespace or zeroes in first string
        while (wxIsspace(String1Char) || String1Char == '0' )
        {
            if (String1Char == '0')
            {
                String1Zeroes++;
            }
            else
            {
                String1Zeroes = 0;
            }

            String1Char = String1[++StringCounter1];
        }

        // skip past whitespace or zeroes in second string
        while (wxIsspace(String2Char) || String2Char == '0')
        {
            if (String2Char == '0')
            {
                String2Zeroes++;
            }
            else
            {
                String2Zeroes = 0;
            }

            String2Char = String2[++StringCounter2];
        }

        // We encountered some digits, compare these.
        if (wxIsdigit(String1Char) && wxIsdigit(String2Char))
        {
            if ((Result = NaturalCompareWorker(
                              String1.Mid(StringCounter1),
                              String2.Mid(StringCounter2))) != 0)
            {
                return Result;
            }
        }

        if ((String1Char == 0) && (String2Char == 0))
        {
            return (String1Zeroes - String2Zeroes);
        }

        if (String1Char < String2Char)
        {
            return -1;
        }
        else if (String1Char > String2Char)
        {
            return 1;
        }

        ++StringCounter1;
        ++StringCounter2;
    }
}
 PartialPacketDynamicString( const wxString &pkt )
 {
     if( pkt.size() > 2 )
         Tokenize( pkt.Mid(1,pkt.size()-2) );
 }
示例#8
0
wxString Localization::GetCountryCodeOnly(const wxString& canonicalName) {
  if (canonicalName.Len() <= 2) return wxEmptyString;
  return canonicalName.Mid(3, 2);
}
     /**
      * COOKIE文字列の切り出し処理を行う
      */
     void SubstringCookie(wxString& cookie) {
	  if (cookie.Len() > 0) {
	       cookie = cookie.Mid(0, cookie.Find(wxT(";")));
	  }
     };
示例#10
0
myAttachment::myAttachment(wxString sData)
:   m_sContentType(wxT("text/html")),
    m_pData(0L),
    m_dataLen(0L)
{
    wxString sTmpFile;
    wxString        sHeader;
    wxArrayString   sHeadArray;
    wxString        sContentType;
    wxString        sTmp, sTmp2;

    size_t lastOffset;

#ifdef  ENABLE_FORM_DUMP
    /* Dump the file to temporary file */
    if (!(sTmpFile = wxFileName::CreateTempFileName(wxT("att"), &m_tmpFile)).IsEmpty()) {
        D(debug("Created temporary file %s\n", sTmpFile.c_str()));

        if (m_tmpFile.IsOpened()) {
            m_tmpFile.Write( sData.GetData(), sData.Length() );
            m_tmpFile.Close();
    }
}
#endif

    wxStringTokenizer       partToke( sData, wxT("\n"));

    while ((sHeader = partToke.GetNextToken()) != wxT("\r")) {
        //D(debug("-- header %s\n", sHeader.c_str()));

        sHeadArray.Add( sHeader );

        wxStringTokenizer hdrToke( sHeader, wxT(":") );

        sTmp = hdrToke.GetNextToken();
        //D(debug("-- sTMP %s\n", sTmp.c_str()));

        if (sTmp.CmpNoCase(wxT("content-disposition")) == 0) {
            wxString sFields = hdrToke.GetNextToken();
            //D(debug("-- found content disposition!\n"));

            sFields.Trim(true);
            sFields.Trim(false);

            //D(debug("fields = [%s]\n", sFields.c_str()));

            wxStringTokenizer attributes( sFields, wxT(";") );

            sTmp2 = attributes.GetNextToken();
            sTmp2.Trim(true);
            sTmp2.Trim(false);

//            D(debug("sTmp2 = [%s]\n", sTmp2.c_str()));

            if (sTmp2.CmpNoCase(wxT("form-data")) == 0) {
                while (attributes.HasMoreTokens()) {
                    wxString sAttName, sAttValue;
                    wxString subAttr = attributes.GetNextToken().Trim(false).Trim();

                    //D(debug("---- sub attribute = %s\n", subAttr.c_str()));

                    wxStringTokenizer subToke( subAttr, wxT("=") );

                    sAttName = subToke.GetNextToken().Trim(false).Trim();
                    sAttValue = subToke.GetNextToken().Trim(false).Trim();

                    D(debug("Attribute name [%s] value [%s]\n", sAttName.c_str(), sAttValue.c_str()));

                    if (sAttName.CmpNoCase(wxT("name")) == 0) {
                        m_sName = sAttValue;
                        m_sName.Replace(wxT("\""), wxEmptyString);
                    } else if (sAttName.CmpNoCase(wxT("filename")) == 0) {
                        m_sFilename = sAttValue;
                        m_sFilename.Replace(wxT("\""), wxEmptyString);
                    } else {
                        /* */
                    }
                }
            }
        } else if (sTmp.CmpNoCase(wxT("content-type"))  == 0) {
            m_sContentType = hdrToke.GetNextToken().Trim(false).Trim();
            D(debug("-- Found content type of %s\n", m_sContentType.c_str()));
        }

    }
    lastOffset = partToke.GetPosition();

    //D(debug("-- last offset @ %ld\n", lastOffset));

    sData = sData.Mid( lastOffset );

    m_pData     = (unsigned char*)malloc( sData.Length() );
    m_dataLen   = sData.Length();

    memcpy( m_pData, sData.GetData(), sData.Length() );

//  write_file();

    return;
}
示例#11
0
wxString Localization::GetLanguageCodeOnly(const wxString& canonicalName) {
  if (canonicalName.Len() < 2) return canonicalName;
  return canonicalName.Mid(0, 2);
}
示例#12
0
void wxRibbonMetroArtProvider::DrawButtonBarButtonForeground(
                        wxDC& dc,
                        const wxRect& rect,
                        wxRibbonButtonKind kind,
                        long state,
                        const wxString& label,
                        const wxBitmap& bitmap_large,
                        const wxBitmap& bitmap_small)
{
    switch(state & wxRIBBON_BUTTONBAR_BUTTON_SIZE_MASK)
    {
    case wxRIBBON_BUTTONBAR_BUTTON_LARGE:
        {
            const int padding = 2;
            dc.DrawBitmap(bitmap_large,
                rect.x + (rect.width - bitmap_large.GetWidth()) / 2,
                rect.y + padding, true);
            int ypos = rect.y + padding + bitmap_large.GetHeight() + padding;
            int arrow_width = kind == wxRIBBON_BUTTON_NORMAL ? 0 : 8;
            wxCoord label_w, label_h;
            dc.GetTextExtent(label, &label_w, &label_h);
            if(label_w + 2 * padding <= rect.width)
            {
                dc.DrawText(label, rect.x + (rect.width - label_w) / 2, ypos);
                if(arrow_width != 0)
                {
                    DrawDropdownArrow(dc, rect.x + rect.width / 2,
                        ypos + (label_h * 3) / 2,
                        m_button_bar_label_colour);
                }
            }
            else
            {
                size_t breaki = label.Len();
                do
                {
                    --breaki;
                    if(wxRibbonCanLabelBreakAtPosition(label, breaki))
                    {
                        wxString label_top = label.Mid(0, breaki);
                        dc.GetTextExtent(label_top, &label_w, &label_h);
                        if(label_w + 2 * padding <= rect.width)
                        {
                            dc.DrawText(label_top,
                                rect.x + (rect.width - label_w) / 2, ypos);
                            ypos += label_h;
                            wxString label_bottom = label.Mid(breaki + 1);
                            dc.GetTextExtent(label_bottom, &label_w, &label_h);
                            label_w += arrow_width;
                            int iX = rect.x + (rect.width - label_w) / 2;
                            dc.DrawText(label_bottom, iX, ypos);
                            if(arrow_width != 0)
                            {
                                DrawDropdownArrow(dc,
                                    iX + 2 +label_w - arrow_width,
                                    ypos + label_h / 2 + 1,
                                    m_button_bar_label_colour);
                            }
                            break;
                        }
                    }
                } while(breaki > 0);
            }
        }
        break;
    case wxRIBBON_BUTTONBAR_BUTTON_MEDIUM:
        {
            int x_cursor = rect.x + 2;
            dc.DrawBitmap(bitmap_small, x_cursor,
                    rect.y + (rect.height - bitmap_small.GetHeight())/2, true);
            x_cursor += bitmap_small.GetWidth() + 2;
            wxCoord label_w, label_h;
            dc.GetTextExtent(label, &label_w, &label_h);
            dc.DrawText(label, x_cursor,
                rect.y + (rect.height - label_h) / 2);
            x_cursor += label_w + 3;
            if(kind != wxRIBBON_BUTTON_NORMAL)
            {
                DrawDropdownArrow(dc, x_cursor, rect.y + rect.height / 2,
                    m_button_bar_label_colour);
            }
            break;
        }
    default:
        // TODO
        break;
    }
}
示例#13
0
void SearchThread::DoSearchLine(const wxString& line, const int lineNum, const int lineOffset, const wxString& fileName,
                                const SearchData* data, const wxString& findWhat, const wxArrayString& filters,
                                TextStatesPtr statesPtr)
{
    wxString modLine = line;

    if(!data->IsMatchCase()) { modLine.MakeLower(); }

    int pos = 0;
    int col = 0;
    int iCorrectedCol = 0;
    int iCorrectedLen = 0;
    while(pos != wxNOT_FOUND) {
        pos = modLine.Find(findWhat);
        if(pos != wxNOT_FOUND) {
            col += pos;

            // Pipe support
            bool allFiltersOK = true;
            if(!filters.IsEmpty()) {
                // Apply the filters
                for(size_t i = 0; i < filters.size() && allFiltersOK; ++i) {
                    allFiltersOK = (modLine.Find(filters.Item(i)) != wxNOT_FOUND);
                }
            }

            // Pipe filtes OK?
            if(!allFiltersOK) return;

            // we have a match
            if(data->IsMatchWholeWord()) {

                // make sure that the word before is not in the wordChars map
                if((pos > 0) && (m_wordCharsMap.find(modLine.GetChar(pos - 1)) != m_wordCharsMap.end())) {
                    if(!AdjustLine(modLine, pos, findWhat)) {

                        break;
                    } else {
                        col += (int)findWhat.Length();
                        continue;
                    }
                }
                // if we have more characters to the right, make sure that the first char does not match any
                // in the wordCharsMap
                if(pos + findWhat.Length() <= modLine.Length()) {
                    wxChar nextCh = modLine.GetChar(pos + findWhat.Length());
                    if(m_wordCharsMap.find(nextCh) != m_wordCharsMap.end()) {
                        if(!AdjustLine(modLine, pos, findWhat)) {

                            break;
                        } else {
                            col += (int)findWhat.Length();
                            continue;
                        }
                    }
                }
            }

            // Notify our match
            // correct search Pos and Length owing to non plain ASCII multibyte characters
            iCorrectedCol = FileUtils::UTF8Length(line.c_str(), col);
            iCorrectedLen = FileUtils::UTF8Length(findWhat.c_str(), findWhat.Length());
            SearchResult result;
            result.SetPosition(lineOffset + col);
            result.SetColumnInChars(col);
            result.SetColumn(iCorrectedCol);
            result.SetLineNumber(lineNum);
            // Dont use match pattern larger than 500 chars
            result.SetPattern(line.length() > 500 ? line.Mid(0, 500) : line);
            result.SetFileName(fileName);
            result.SetLenInChars((int)findWhat.Length());
            result.SetLen(iCorrectedLen);
            result.SetFindWhat(data->GetFindString());
            result.SetFlags(data->m_flags);

            int position(wxNOT_FOUND);
            bool canAdd(true);

            if(statesPtr) {
                position = statesPtr->LineToPos(lineNum - 1);
                position += iCorrectedCol;
            }

            // Make sure our match is not on a comment
            if(statesPtr && position != wxNOT_FOUND && data->GetSkipComments()) {
                if(statesPtr->states.size() > (size_t)position) {
                    short state = statesPtr->states.at(position).state;
                    if(state == CppWordScanner::STATE_CPP_COMMENT || state == CppWordScanner::STATE_C_COMMENT) {
                        canAdd = false;
                    }
                }
            }

            if(statesPtr && position != wxNOT_FOUND && data->GetSkipStrings()) {
                if(statesPtr->states.size() > (size_t)position) {
                    short state = statesPtr->states.at(position).state;
                    if(state == CppWordScanner::STATE_DQ_STRING || state == CppWordScanner::STATE_SINGLE_STRING) {
                        canAdd = false;
                    }
                }
            }

            result.SetMatchState(CppWordScanner::STATE_NORMAL);
            if(canAdd && statesPtr && position != wxNOT_FOUND && data->GetColourComments()) {
                // set the match state
                if(statesPtr->states.size() > (size_t)position) {
                    short state = statesPtr->states.at(position).state;
                    if(state == CppWordScanner::STATE_C_COMMENT || state == CppWordScanner::STATE_CPP_COMMENT) {
                        result.SetMatchState(state);
                    }
                }
            }

            if(canAdd) {
                m_results.push_back(result);
                m_summary.SetNumMatchesFound(m_summary.GetNumMatchesFound() + 1);
            }

            if(!AdjustLine(modLine, pos, findWhat)) { break; }
            col += (int)findWhat.Length();
        }
    }
}
示例#14
0
bool CWrapEngine::WrapText(wxWindow* parent, wxString& text, unsigned long maxLength)
{
	/*
	This function wraps the given string so that it's width in pixels does
	not exceed maxLength.
	In the general case, wrapping is done on word boundaries. Thus we scan the
	string for spaces, measuer the length of the words and wrap if line becomes
	too long.
	It has to be done wordwise, as with some languages/fonts, the width in
	pixels of a line is smaller than the sum of the widths of every character.

	A special case are some languages, e.g. Chinese, which don't separate words
	with spaces. In such languages it is allowed to break lines after any
	character.

	Though there are a few exceptions:
	- Don't wrap before punctuation marks
	- Wrap embedded English text fragments only on spaces

	For this kind of languages, a different wrapping algorithm is used.
	*/

	if (!m_font.IsOk())
		m_font = parent->GetFont();

#ifdef __WXDEBUG__
	const wxString original = text;
#endif

	if (m_wrapOnEveryChar)
	{
		bool res = WrapTextChinese(parent, text, maxLength);
#ifdef __WXDEBUG__
		wxString unwrapped = UnwrapText(text);
		wxASSERT(original == unwrapped);
#endif
		return res;
	}

	wxString wrappedText;

	int width = 0, height = 0;

	int spaceWidth = 0;
	parent->GetTextExtent(_T(" "), &spaceWidth, &height, 0, 0, &m_font);

	int strLen = text.Length();
	int wrapAfter = -1;
	int start = 0;
	unsigned int lineLength = 0;

	bool url = false;
	bool containsURL = false;
	for (int i = 0; i <= strLen; i++)
	{
		if ((text[i] == ':' && text[i + 1] == '/' && text[i + 2] == '/') || // absolute
			(text[i] == '/' && (!i || text[i - 1] == ' '))) // relative
		{
			url = true;
			containsURL = true;
		}
		if (text[i] != ' ' && text[i] != 0)
		{
			// If url, wrap on slashes and ampersands, but not first slash of something://
			if (!url ||
				 ((text[i] != '/' || text[i + 1] == '/') && (text[i] != '&' || text[i + 1] == '&') && text[i] != '?'))
			continue;
		}

		wxString segment;
		if (wrapAfter == -1)
		{
			if (text[i] == '/' || text[i] == '?' || text[i] == '&')
				segment = text.Mid(start, i - start + 1);
			else
				segment = text.Mid(start, i - start);
			wrapAfter = i;
		}
		else
		{
			if (text[i] == '/' || text[i] == '?' || text[i] == '&')
				segment = text.Mid(wrapAfter + 1, i - wrapAfter);
			else
				segment = text.Mid(wrapAfter + 1, i - wrapAfter - 1);
		}

		segment = wxStripMenuCodes(segment);
		parent->GetTextExtent(segment, &width, &height, 0, 0, &m_font);

		if (lineLength + spaceWidth + width > maxLength)
		{
			// Cannot be appended to current line without overflow, so start a new line
			if (wrappedText != _T(""))
				wrappedText += _T("\n");
			wrappedText += text.Mid(start, wrapAfter - start);
			if (text[wrapAfter] != ' ' && text[wrapAfter] != '\0')
				wrappedText += text[wrapAfter];

			if (width + spaceWidth >= (int)maxLength)
			{
				// Current segment too big to even fit into a line just by itself

				if( i != wrapAfter )
				{
					if (wrappedText != _T(""))
						wrappedText += _T("\n");
					wrappedText += text.Mid(wrapAfter + 1, i - wrapAfter - 1);
				}

				start = i + 1;
				wrapAfter = -1;
				lineLength = 0;
			}
			else
			{
				start = wrapAfter + 1;
				wrapAfter = i;
				lineLength = width;
			}
		}
		else if (lineLength + spaceWidth + width + spaceWidth >= maxLength)
		{
			if (wrappedText != _T(""))
				wrappedText += _T("\n");
			wrappedText += text.Mid(start, i - start);
			if (text[i] != ' ' && text[i] != '\0')
				wrappedText += text[i];
			start = i + 1;
			wrapAfter = -1;
			lineLength = 0;
		}
		else
		{
			if (lineLength)
				lineLength += spaceWidth;
			lineLength += width;
			wrapAfter = i;
		}

		if (text[i] == ' ')
			url = false;
	}
	if (start < strLen)
	{
		if (wrappedText != _T(""))
			wrappedText += _T("\n");
		wrappedText += text.Mid(start);
	}

	text = wrappedText;

#ifdef __WXDEBUG__
		wxString unwrapped = UnwrapText(text);
		wxASSERT(original == unwrapped || containsURL);
#endif

	return true;
}
void DebugManager::ProcSocketData(wxString data) {
    if (data.StartsWith("subtitulo ")) {
        subtitles->AddMessage(current_line,current_inst,data.Mid(10));
    }
    if (data.StartsWith("proceso ")) {
        current_proc_name=data.Mid(8);
    } else if (data.StartsWith("linea ")) {
        long l=-1,i=-1;
        if (data.Contains(":")) {
            data.Mid(6).BeforeFirst(':').ToLong(&l);
            data.AfterLast(':').ToLong(&i);
        } else {
            data.Mid(6).ToLong(&l);
        }
        if (l>=0 && source!=NULL) source->SetDebugLine(l-1,i-1);
        if (do_desktop_test) desktop_test->SetLine(current_proc_name,l,i);
        current_line=l;
        current_inst=i;
    } else if (data.StartsWith("autoevaluacion ")) {
        long l=-1;
        data.Mid(15).BeforeFirst(' ').ToLong(&l);
        desktop_test->SetAutoevaluation(l,data.Mid(15).AfterFirst(' '));
    } else if (data.StartsWith("estado ")) {
        wxString state = data.AfterFirst(' ');
        if (state=="inicializado") {
            // cargar la prueba de escritorio
            do_desktop_test=debug_panel->IsDesktopTestEnabled();
            if (do_desktop_test) {
                const wxArrayString &vars  = desktop_test->GetDesktopVars();
                for (unsigned int i=0; i<vars.GetCount(); i++) {
                    wxString str(wxString("autoevaluar ")<<vars[i]<<"\n");
                    socket->Write(str.c_str(),str.Len());
                }
            }
            // configurar el tipo de paso a paso (step in o step over)
            wxString str1("subprocesos ");
            str1<<(step_in?1:0)<<"\n";
            socket->Write(str1.c_str(),str1.Len());
            wxString str2("subtitulos ");
            str2<<(subtitles_on?1:0)<<"\n";
            socket->Write(str2.c_str(),str2.Len());
            // iniciar la ejecución
            if ((paused=should_pause)) {
                wxString str("paso\n");
                socket->Write(str.c_str(),str.Len());
            }	else {
                wxString str("comenzar\n");
                socket->Write(str.c_str(),str.Len());
            }
        } else if (state=="pausa") {
            debug_panel->SetState(DS_PAUSED);
            if (source) source->SetDebugPause();
        } else if (state=="paso")
            debug_panel->SetState(DS_STEP);
        else if (state=="ejecutando")
            debug_panel->SetState(DS_RESUMED);
        else if (state=="finalizado") {
            debug_panel->SetState(DS_FINALIZED);
            if (source) source->SetDebugLine();
        } else {
            if (source) source->SetDebugLine();
            debug_panel->SetState(DS_NONE);
        }
    } else if (data.StartsWith("evaluacion ")) {
        RunLambda(data.AfterFirst(' ').BeforeFirst(' '),data.AfterFirst(' ').AfterFirst(' '));
    }
}
示例#16
0
// Checks whether an odamex-style address format is valid, also gives the
// separated ip/hostname and port number back to the caller
_oda_iav_err_t dlgMain::IsAddressValid(wxString Address, wxString &OutIPHost,
    long &OutPort)
{
    wxInt32 Colon;
    wxString RegEx;
    wxRegEx ReValIP;
    wxString IPHost;
    long Port = 10666;

    // Get rid of any whitespace on either side of the string
    Address.Trim(false);
    Address.Trim(true);

    // Don't accept nothing
    if (Address.IsEmpty() == true)
    {
        return _oda_iav_emptystr;
    }

    // Set the regular expression and load it in
    RegEx = wxT("^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4]"
                    "[0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]"
                    "[0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");

    ReValIP.Compile(RegEx);

    if (ReValIP.IsValid() == false)
    {
        return _oda_iav_interr;
    }

    // Find the colon that separates the address and the port number
    Colon = Address.Find(wxT(':'), true);

    if (Colon != wxNOT_FOUND)
    {
        wxString PortStr;
        bool IsGood;

        // Try to convert the substring after the : to a port number
        PortStr = Address.Mid(Colon + 1);

        IsGood = PortStr.ToLong(&Port);

        // Check if there is something after the colon and if its actually a
        // numeric value
        if ((Colon + 1 >= Address.Len()) || (IsGood == false) || (Port <= 0))
        {
            return _oda_iav_colerr;
        }

    }

    // Finally get the address portion from the main string
    IPHost = Address.Mid(0, Colon);

    // Finally do the comparison
    if (ReValIP.Matches(IPHost) == true)
    {
        OutIPHost = IPHost;
        OutPort = Port;

        return _oda_iav_SUCCESS;
    }
    else
    {
        struct hostent *he;

        // Check to see if its a hostname rather than an IP address
        he = gethostbyname((const char *)IPHost.char_str());

        if (he != NULL)
        {
            OutIPHost = IPHost;
            OutPort = Port;

            return _oda_iav_SUCCESS;
        }
        else
            return _oda_iav_FAILURE;
    }
}
示例#17
0
bool CLocalListView::DisplayDir(wxString dirname)
{
	wxString focused;
	std::list<wxString> selectedNames;
	if (m_dir != dirname)
	{
		// Clear selection
		int item = -1;
		while (true)
		{
			item = GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED);
			if (item == -1)
				break;
			SetItemState(item, 0, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED);
		}
		focused = _T("..");

		if (GetItemCount())
			EnsureVisible(0);
		m_dir = dirname;
	}
	else
	{
		// Remember which items were selected
		selectedNames = RememberSelectedItems(focused);
	}

	const int oldItemCount = m_indexMapping.size();

	m_fileData.clear();
	m_indexMapping.clear();

	m_hasParent = CState::LocalDirHasParent(dirname);

	if (m_hasParent)
	{
		t_fileData data;
		data.dir = true;
		data.icon = -2;
		data.name = _T("..");
		data.size = -1;
		data.hasTime = 0;
		m_fileData.push_back(data);
		m_indexMapping.push_back(0);
	}

#ifdef __WXMSW__
	if (dirname == _T("\\"))
	{
		DisplayDrives();
	}
	else if (dirname.Left(2) == _T("\\\\"))
	{
		int pos = dirname.Mid(2).Find('\\');
		if (pos != -1 && pos + 3 != (int)dirname.Len())
			goto regular_dir;

		// UNC path without shares
		DisplayShares(dirname);
	}
	else
#endif
	{
#ifdef __WXMSW__
regular_dir:
#endif
		CFilterDialog filter;

		wxDir dir(dirname);
		if (!dir.IsOpened())
		{
			SetItemCount(1);
			return false;
		}
		wxString file;
		bool found = dir.GetFirst(&file);
		int num = m_fileData.size();
		while (found)
		{
			if (file == _T(""))
			{
				wxGetApp().DisplayEncodingWarning();
				found = dir.GetNext(&file);
				continue;
			}
			t_fileData data;

			data.dir = wxFileName::DirExists(dirname + file);
			data.icon = -2;
			data.name = file;

			wxStructStat buf;
			int result;
			result = wxStat(dirname + file, &buf);

			if (!result)
			{
				data.hasTime = true;
				data.lastModified = wxDateTime(buf.st_mtime);
			}
			else
				data.hasTime = false;

			if (data.dir)
				data.size = -1;
			else
				data.size = result ? -1 : buf.st_size;

			m_fileData.push_back(data);
			if (!filter.FilenameFiltered(data.name, data.dir, data.size, true))
				m_indexMapping.push_back(num);
			num++;

			found = dir.GetNext(&file);
		}
	}

	if (m_dropTarget != -1)
	{
		t_fileData* data = GetData(m_dropTarget);
		if (!data || !data->dir)
		{
			SetItemState(m_dropTarget, 0, wxLIST_STATE_DROPHILITED);
			m_dropTarget = -1;
		}
	}

	const int count = m_indexMapping.size();
	if (oldItemCount != count)
		SetItemCount(count);

	SortList();

	ReselectItems(selectedNames, focused);

	Refresh();

	return true;
}
示例#18
0
/****************************************************************************
PARAMETERS:
str        - text of #if statement

RETURNS:
true or false depending on how it evaluated

REMARKS:
TODO: rewrite this whole thing using regular expressions when they are done.

SEE ALSO:
wxIfElseVariable
****************************************************************************/
bool ParseIfStatementValue(
    wxString &str)
{
    // Find out if the tag has parenthesis
    // recursive to parse the text within the parenthesis,
    // replacing the text with 1 or 0, (hardcoded true or false)
    int b;
    while ((b = str.Find('(')) != -1) {
        int e;
        // Find the matching parenthesis
        int nextbeg, nextend;
        int parencount = 1, min = b+1;
        do {
            nextbeg = str.find('(', min);
            nextend = str.find(')', min);
            if (nextbeg < nextend && nextbeg != wxString::npos) {
                parencount++;
                min = nextbeg+1;
                }
            else {
                parencount--;
                min = nextend+1;
                }

            if (nextend == wxString::npos) {
#ifdef CHECKED		
                wxMessageBox("wxHTML #if\\else error: Unmatched parenthesis in #if expression.","Error",wxICON_ERROR);
#endif
                return true;
                }
            // once parencount reaches 0 again we have found our matchin )
            } while (parencount > 0);

        e = nextend;

        // Extract the expression from the parenthesis block and recurse
        // to solve it.
        wxString tag;
        tag = str.Mid(b+1, e-b-1);
        bool val = ParseIfStatementValue(tag);
        // Add extra spaces just in case of NOT(VAL)
        if (val) str = str.Mid(0, b) + " 1" + str.Mid(e+1);
        else str = str.Mid(0, b) + " 0" + str.Mid(e+1);
        }

    // Remove spaces from left and right
    str.Trim(false);
    str.Trim(true);

    // Convert text method of operators "AND" and "OR" to c style
    // this makes only one special case necessary for each later on
    str.Replace(" AND ", "&&");
    str.Replace(" OR ", "||");
    str.Replace(" EQUALS ", "==");

    // Check for equals statements
    // == statements are special because they are evaluated as a single block
    int equ;
    equ = str.find("==");
    while (equ != wxString::npos) {
        int begin, end;
        int begin2, end2; // ends of words
        begin = equ-1;
        end = equ+2;

        // remove spaces, find extents
        while (end < str.Length() && str.GetChar(end) == ' ')
            end++;
        while (begin >= 0 && str.GetChar(begin) == ' ')
            begin--;
        end2 = end;
        begin2 = begin;
        if (str.GetChar(end2) == '\'' || str.GetChar(end2) == '\"') {
            end2++;
            while (end2 < str.Length() && str.GetChar(end2) != '\'' && str.GetChar(end2) != '\"' )
                end2++;
            end2++;
            }
        else {
            while (end2 < str.Length() && IsLetter(str.GetChar(end2)))
                end2++;
            }
        while (begin >= 0 && IsLetter(str.GetChar(begin)))
            begin--;

        if (begin < 0) begin = 0;
        else begin++;
        if (end2 >= str.Length()) end2 = str.Length();

        wxString tmpeq = GetEquals(str.Mid(begin, begin2-begin+1), str.Mid(end, end2-end));
        str = str.Mid(0, begin) + wxString(" ") + tmpeq + wxString(" ") +
            str.Mid(end2);
        equ = str.find("==");

        // Remove spaces from left and right
        str.Trim(false);
        str.Trim(true);
        }

    // We use ReverseFind so that the whole left expression gets evaluated agains
    // the right single item, creating a left -> right evaluation
    // Search for || operators, recurse to solve (so we don't have to handle special cases here)
    int and, or;
    and = ReverseFind(str, "&&");
    or = ReverseFind(str, "||");
    if ( (and != -1) || (or != -1) ) {
        wxString tag1, tag2;
        // handle the rightmost first to force left->right evaluation
        if ( (and > or) ) {
            return (
                ParseIfStatementValue(tag2 = str.Mid(and+2)) &&
                ParseIfStatementValue(tag1 = str.Mid(0, and)) );
            }
        else {
            return (
                ParseIfStatementValue(tag2 = str.Mid(or+2)) ||
                ParseIfStatementValue(tag1 = str.Mid(0, or)) );
            }
        }

    // By the time we get to this place in the function we are guarenteed to have a single
    // variable operation, perhaps with a NOT or ! operator
    bool notval = false;

    // search for a NOT or ! operator
    if (str.Mid(0, 1) == "!") {
        str.Remove(0, 1);
        str.Trim(false); // trim spaces from left
        notval = true;
        }
    else if (str.Mid(0,4).CmpNoCase("NOT ") == 0) {
        str.Remove(0, 4);
        str.Trim(false); // trim any extra spaces from left
        notval = true;
        }

    // now all we have left is the name of the class or a hardcoded 0 or 1
    if (str == "") {
#ifdef CHECKED		
        wxMessageBox("wxHTML #if\\else error: Empty expression in #if\\#elif statement.","Error",wxICON_ERROR);
#endif
        return true;
        }

    // check for hardcoded 0 and 1 cases, (these are used by parenthesis catcher)
    // this just decomplicates the recursion algorithm
    if (str == "0") return notval;
    if (str == "1") return !notval;

    // Grab the value from the variable class identified by cname
    bool value = wxIfElseVariable::GetValue(str);
    if (notval) value = !value;
    return value;

}
示例#19
0
void CCodeParser::ParseSourceFunctions(wxString code)
{
    int functionStart = 0;
    int functionEnd = 0;
    int previousFunctionEnd = 0;
    wxString funcName, funcArg;
    Function *func;
    wxString Str, R;

    int loop = 0;
    while (1)
    {
        //find the begining of the function name
        Str = m_className + wxT("::");
        functionStart = code.find(Str, previousFunctionEnd);
        if (functionStart == wxNOT_FOUND)
        {
            //Get the last bit of remaining code after the last function in the file
            m_trailingCode = code.Mid(previousFunctionEnd);
            m_trailingCode.RemoveLast();
            return;
        }
        //found a function now creat a new function class
        func = new Function();

        //find the begining of the line on which the function name resides
        functionStart = code.rfind('\n', functionStart);
        func->SetDocumentation(code.Mid(previousFunctionEnd, functionStart - previousFunctionEnd));
        functionStart++;

        functionEnd = code.find('{', functionStart);
        wxString heading = code.Mid(functionStart, functionEnd - functionStart);
        if(heading.Right(1) == '\n')
        {
            heading.RemoveLast();
        }
        func->SetHeading(heading);

        m_functions[RemoveWhiteSpace(heading)] = func;

        //find the opening brackets of the function
        func->SetContents(ParseBrackets(code,  functionStart));
        if (functionStart != wxNOT_FOUND)
        {
            functionEnd = functionStart;
        }
        else
        {
            wxMessageBox(wxT("Brackets Missing in Source File!"));
            code.insert(functionEnd +1, wxT("//The Following Block is missing a closing bracket\n//and has been set aside by wxFormbuilder\n"));
            func->SetContents(wxT(""));
        }

        previousFunctionEnd = functionEnd;
        if (loop == 100)
        {
            return;
        }
        loop++;
    }
}
示例#20
0
文件: misc.cpp 项目: idgaf/FileZilla3
bool IsRoutableAddress(const wxString& address, enum CSocket::address_family family)
{
	if (family == CSocket::ipv6)
	{
		wxString long_address = GetIPV6LongForm(address);
		if (long_address.empty())
			return false;
		if (long_address[0] == '0')
		{
			// ::/128
			if (long_address == _T("0000:0000:0000:0000:0000:0000:0000:0000"))
				return false;
			// ::1/128
			if (long_address == _T("0000:0000:0000:0000:0000:0000:0000:0001"))
				return false;

			if (long_address.Left(30) == _T("0000:0000:0000:0000:0000:ffff:"))
			{
				// IPv4 mapped
				wxString ipv4 = wxString::Format(_T("%d.%d.%d.%d"),
						DigitHexToDecNum(long_address[30]) * 16 + DigitHexToDecNum(long_address[31]),
						DigitHexToDecNum(long_address[32]) * 16 + DigitHexToDecNum(long_address[33]),
						DigitHexToDecNum(long_address[35]) * 16 + DigitHexToDecNum(long_address[36]),
						DigitHexToDecNum(long_address[37]) * 16 + DigitHexToDecNum(long_address[38]));
				return IsRoutableAddress(ipv4, CSocket::ipv4);
			}

			return true;
		}
		if (long_address[0] == 'f')
		{
			if (long_address[1] == 'e')
			{
				// fe80::/10 (link local)
				const wxChar& c = long_address[2];
				int v;
				if (c >= 'a')
					v = c - 'a' + 10;
				else
					v = c - '0';
				if ((v & 0xc) == 0x8)
					return false;

				return true;
			}
			else if (long_address[1] == 'c' || long_address[1] == 'd')
			{
				// fc00::/7 (site local)
				return false;
			}
		}

		return true;
	}
	else
	{
		// Assumes address is already a valid IP address
		if (address.Left(3) == _T("127") ||
			address.Left(3) == _T("10.") ||
			address.Left(7) == _T("192.168") ||
			address.Left(7) == _T("169.254"))
			return false;

		if (address.Left(3) == _T("172"))
		{
			wxString middle = address.Mid(4);
			int pos = address.Find(_T("."));
			wxASSERT(pos != -1);
			long part;
			middle.Left(pos).ToLong(&part);

			if (part >= 16 && part <= 31)
				return false;
		}

		return true;
	}
}
示例#21
0
bool CServer::ParseUrl(wxString host, unsigned int port, wxString user, wxString pass, wxString &error, CServerPath &path)
{
	m_type = DEFAULT;

	if (host == _T(""))
	{
		error = _("No host given, please enter a host.");
		return false;
	}

	int pos = host.Find(_T("://"));
	if (pos != -1)
	{
		wxString protocol = host.Left(pos).Lower();
		host = host.Mid(pos + 3);
		if (protocol.Left(3) == _T("fz_"))
			protocol = protocol.Mid(3);
		m_protocol = GetProtocolFromPrefix(protocol.Lower());
		if (m_protocol == UNKNOWN)
		{
			// TODO: http:// once WebDAV is officially supported
			error = _("Invalid protocol specified. Valid protocols are:\nftp:// for normal FTP,\nsftp:// for SSH file transfer protocol,\nftps:// for FTP over SSL (implicit) and\nftpes:// for FTP over SSL (explicit).");
			return false;
		}
	}

	pos = host.Find('@');
	if (pos != -1)
	{
		// Check if it's something like
		//   user@name:password@host:port/path
		// => If there are multiple at signs, username/port ends at last at before
		// the first slash. (Since host and port never contain any at sign)

		int slash = host.Mid(pos + 1).Find('/');
		if (slash != -1)
			slash += pos + 1;

		int next_at = host.Mid(pos + 1).Find('@');
		while (next_at != -1)
		{
			next_at += pos + 1;
			if (slash != -1 && next_at > slash)
				break;

			pos = next_at;
			next_at = host.Mid(pos + 1).Find('@');
		}

		user = host.Left(pos);
		host = host.Mid(pos + 1);

		// Extract password (if any) from username
		pos = user.Find(':');
		if (pos != -1)
		{
			pass = user.Mid(pos + 1);
			user = user.Left(pos);
		}

		// Remove leading and trailing whitespace
		user.Trim(true);
		user.Trim(false);

		if (user == _T(""))
		{
			error = _("Invalid username given.");
			return false;
		}
	}
	else
	{
		// Remove leading and trailing whitespace
		user.Trim(true);
		user.Trim(false);

		if (user == _T(""))
		{
			user = _T("anonymous");
			pass = _T("*****@*****.**");
		}
	}

	pos = host.Find('/');
	if (pos != -1)
	{
		path = CServerPath(host.Mid(pos));
		host = host.Left(pos);
	}

	pos = host.Find(':');
	if (pos != -1)
	{
		if (!pos)
		{
			error = _("No host given, please enter a host.");
			return false;
		}

		long tmp;
		if (!host.Mid(pos + 1).ToLong(&tmp) || tmp < 1 || tmp > 65535)
		{
			error = _("Invalid port given. The port has to be a value from 1 to 65535.");
			return false;
		}
		port = tmp;

		host = host.Left(pos);
	}
	else
	{
		if (!port)
			port = GetDefaultPort(m_protocol);
		else if (port > 65535)
		{
			error = _("Invalid port given. The port has to be a value from 1 to 65535.");
			return false;
		}
	}

	host.Trim(true);
	host.Trim(false);

	if (host == _T(""))
	{
		error = _("No host given, please enter a host.");
		return false;
	}

	m_host = host;
	m_port = port;
	m_user = user;
	m_pass = pass;
	m_account = _T("");
	if (m_user == _T("") || m_user == _T("anonymous"))
		m_logonType = ANONYMOUS;
	else
		m_logonType = NORMAL;

	if (m_protocol == UNKNOWN)
		m_protocol = GetProtocolFromPort(port);

	return true;
}
示例#22
0
文件: misc.cpp 项目: idgaf/FileZilla3
wxString GetIPV6LongForm(wxString short_address)
{
	if (short_address[0] == '[')
	{
		if (short_address.Last() != ']')
			return _T("");
		short_address.RemoveLast();
		short_address = short_address.Mid(1);
	}
	short_address.MakeLower();

	wxChar buffer[40] = { '0', '0', '0', '0', ':',
						  '0', '0', '0', '0', ':',
						  '0', '0', '0', '0', ':',
						  '0', '0', '0', '0', ':',
						  '0', '0', '0', '0', ':',
						  '0', '0', '0', '0', ':',
						  '0', '0', '0', '0', ':',
						  '0', '0', '0', '0', 0
						};
	wxChar* out = buffer;

	const unsigned int len = short_address.Len();
	if (len > 39)
		return _T("");

	// First part, before possible ::
	unsigned int i = 0;
	unsigned int grouplength = 0;
	for (i = 0; i < len + 1; i++)
	{
		const wxChar& c = short_address[i];
		if (c == ':' || !c)
		{
			if (!grouplength)
			{
				// Empty group length, not valid
				if (!c || short_address[i + 1] != ':')
					return _T("");
				i++;
				break;
			}

			out += 4 - grouplength;
			for (unsigned int j = grouplength; j > 0; j--)
				*out++ = short_address[i - j];
			// End of string...
			if (!c)
			{
				if (!*out)
					// ...on time
					return buffer;
				else
					// ...premature
					return _T("");
			}
			else if (!*out)
			{
				// Too long
				return _T("");
			}

			out++;

			grouplength = 0;
			if (short_address[i + 1] == ':')
			{
				i++;
				break;
			}
			continue;
		}
		else if ((c < '0' || c > '9') &&
				 (c < 'a' || c > 'f'))
		{
			// Invalid character
			return _T("");
		}
		// Too long group
		if (++grouplength > 4)
			return _T("");
	}

	// Second half after ::

	wxChar* end_first = out;
	out = &buffer[38];
	unsigned int stop = i;
	for (i = len - 1; i > stop; i--)
	{
		if (out < end_first)
		{
			// Too long
			return _T("");
		}

		const wxChar& c = short_address[i];
		if (c == ':')
		{
			if (!grouplength)
			{
				// Empty group length, not valid
				return _T("");
			}

			out -= 5 - grouplength;

			grouplength = 0;
			continue;
		}
		else if ((c < '0' || c > '9') &&
				 (c < 'a' || c > 'f'))
		{
			// Invalid character
			return _T("");
		}
		// Too long group
		if (++grouplength > 4)
			return _T("");
		*out-- = c;
	}
	if (!grouplength)
	{
		// Empty group length, not valid
		return _T("");
	}
	out -= 5 - grouplength;
	out += 2;

	int diff = out - end_first;
	if (diff < 0 || diff % 5)
		return _T("");

	return buffer;
}
示例#23
0
wxsNewWindowDlg::wxsNewWindowDlg(wxWindow* parent,const wxString& ResType,wxsProject* Project):
    m_SourceNotTouched(true),
    m_HeaderNotTouched(true),
    m_XrcNotTouched(true),
    m_BlockText(false),
    m_AdvOpsShown(true),
    m_Type(ResType),
    m_Project(Project)
{
    //(*Initialize(wxsNewWindowDlg)
    wxStaticText* StaticText10;
    wxStaticText* StaticText9;
    wxStaticText* StaticText2;
    wxStaticText* StaticText6;
    wxStaticText* StaticText8;
    wxStaticText* StaticText11;
    wxStaticText* StaticText1;
    wxStaticText* StaticText3;
    wxStaticText* StaticText5;
    wxStaticText* StaticText7;
    wxStaticText* StaticText4;

    Create(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE, _T("wxID_ANY"));
    m_RootSizer = new wxBoxSizer(wxVERTICAL);
    StaticBoxSizer3 = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Options"));
    FlexGridSizer1 = new wxFlexGridSizer(0, 2, 5, 5);
    FlexGridSizer1->AddGrowableCol(1);
    StaticText1 = new wxStaticText(this, wxID_ANY, _("Class Name:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer1->Add(StaticText1, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_Class = new wxTextCtrl(this, ID_TEXTCTRL1, wxEmptyString, wxDefaultPosition, wxSize(80,-1), 0, wxDefaultValidator, _T("ID_TEXTCTRL1"));
    FlexGridSizer1->Add(m_Class, 0, wxEXPAND|wxALIGN_LEFT|wxALIGN_TOP, 5);
    StaticText2 = new wxStaticText(this, wxID_ANY, _("Header file:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer1->Add(StaticText2, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_Header = new wxTextCtrl(this, ID_TEXTCTRL2, wxEmptyString, wxDefaultPosition, wxSize(80,-1), 0, wxDefaultValidator, _T("ID_TEXTCTRL2"));
    FlexGridSizer1->Add(m_Header, 0, wxEXPAND|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    StaticText3 = new wxStaticText(this, wxID_ANY, _("Source file:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer1->Add(StaticText3, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_Source = new wxTextCtrl(this, ID_TEXTCTRL3, wxEmptyString, wxDefaultPosition, wxSize(80,-1), 0, wxDefaultValidator, _T("ID_TEXTCTRL3"));
    FlexGridSizer1->Add(m_Source, 0, wxEXPAND|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_UseXrc = new wxCheckBox(this, ID_CHECKBOX1, _("Xrc File:"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1"));
    m_UseXrc->SetValue(false);
    FlexGridSizer1->Add(m_UseXrc, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_Xrc = new wxTextCtrl(this, ID_TEXTCTRL4, wxEmptyString, wxDefaultPosition, wxSize(80,-1), 0, wxDefaultValidator, _T("ID_TEXTCTRL4"));
    FlexGridSizer1->Add(m_Xrc, 0, wxEXPAND|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer1->Add(10,6,1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_XRCAutoload = new wxCheckBox(this, ID_CHECKBOX3, _("Add XRC file to autoload list"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX3"));
    m_XRCAutoload->SetValue(false);
    m_XRCAutoload->Disable();
    FlexGridSizer1->Add(m_XRCAutoload, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StaticBoxSizer3->Add(FlexGridSizer1, 1, wxALL|wxEXPAND|wxALIGN_LEFT|wxALIGN_TOP, 0);
    m_RootSizer->Add(StaticBoxSizer3, 0, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    m_AdvOps = new wxButton(this, ID_BUTTON1, _("+ Advanced options"), wxDefaultPosition, wxDefaultSize, wxBU_LEFT|wxNO_BORDER, wxDefaultValidator, _T("ID_BUTTON1"));
    m_RootSizer->Add(m_AdvOps, 0, wxLEFT|wxRIGHT|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    m_AdvancedOptionsSizer = new wxStaticBoxSizer(wxVERTICAL, this, wxEmptyString);
    FlexGridSizer2 = new wxFlexGridSizer(0, 2, 5, 5);
    FlexGridSizer2->AddGrowableCol(1);
    m_UsePCH = new wxCheckBox(this, ID_CHECKBOX2, _("Use PCH:"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX2"));
    m_UsePCH->SetValue(false);
    FlexGridSizer2->Add(m_UsePCH, 1, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_Pch = new wxComboBox(this, ID_COMBOBOX1, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, 0, 0, wxDefaultValidator, _T("ID_COMBOBOX1"));
    FlexGridSizer2->Add(m_Pch, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    BoxSizer1 = new wxBoxSizer(wxHORIZONTAL);
    BoxSizer1->Add(21,16,0, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    StaticText11 = new wxStaticText(this, wxID_ANY, _("PCH guard define:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    BoxSizer1->Add(StaticText11, 1, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 0);
    FlexGridSizer2->Add(BoxSizer1, 0, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    m_PchGuard = new wxTextCtrl(this, ID_TEXTCTRL8, _("WX_PRECOMP"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL8"));
    FlexGridSizer2->Add(m_PchGuard, 0, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    m_UseInitFunc = new wxCheckBox(this, ID_CHECKBOX4, _("Init code in function:"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX4"));
    m_UseInitFunc->SetValue(false);
    FlexGridSizer2->Add(m_UseInitFunc, 1, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_InitFunc = new wxTextCtrl(this, ID_TEXTCTRL5, _("BuildContent"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL5"));
    m_InitFunc->Disable();
    FlexGridSizer2->Add(m_InitFunc, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StaticText4 = new wxStaticText(this, wxID_ANY, _("Base class name:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer2->Add(StaticText4, 1, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_BaseClass = new wxTextCtrl(this, ID_TEXTCTRL6, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL6"));
    FlexGridSizer2->Add(m_BaseClass, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StaticText7 = new wxStaticText(this, wxID_ANY, _("Scopes:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer2->Add(StaticText7, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 0);
    FlexGridSizer4 = new wxFlexGridSizer(0, 3, 0, 5);
    FlexGridSizer4->AddGrowableCol(0);
    FlexGridSizer4->AddGrowableCol(1);
    FlexGridSizer4->AddGrowableCol(2);
    StaticText8 = new wxStaticText(this, wxID_ANY, _("IDs:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer4->Add(StaticText8, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StaticText9 = new wxStaticText(this, wxID_ANY, _("Members:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer4->Add(StaticText9, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StaticText10 = new wxStaticText(this, wxID_ANY, _("Handlers:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer4->Add(StaticText10, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_ScopeIds = new wxButton(this, ID_BUTTON2, _("Public"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON2"));
    FlexGridSizer4->Add(m_ScopeIds, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_ScopeMembers = new wxButton(this, ID_BUTTON3, _("Public"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON3"));
    FlexGridSizer4->Add(m_ScopeMembers, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_ScopeHandlers = new wxButton(this, ID_BUTTON4, _("Public"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON4"));
    FlexGridSizer4->Add(m_ScopeHandlers, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer2->Add(FlexGridSizer4, 0, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
    StaticText5 = new wxStaticText(this, wxID_ANY, _("Constructor arguments:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer2->Add(StaticText5, 1, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer3 = new wxFlexGridSizer(0, 2, 0, 10);
    FlexGridSizer3->AddGrowableCol(0);
    m_CtorParent = new wxCheckBox(this, ID_CHECKBOX5, _("Parent"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX5"));
    m_CtorParent->SetValue(true);
    FlexGridSizer3->Add(m_CtorParent, 0, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_CtorParentDef = new wxCheckBox(this, ID_CHECKBOX9, _("Def. value"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX9"));
    m_CtorParentDef->SetValue(false);
    FlexGridSizer3->Add(m_CtorParentDef, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_CtorId = new wxCheckBox(this, ID_CHECKBOX6, _("Id"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX6"));
    m_CtorId->SetValue(true);
    FlexGridSizer3->Add(m_CtorId, 0, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_CtorIdDef = new wxCheckBox(this, ID_CHECKBOX10, _("Def. value"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX10"));
    m_CtorIdDef->SetValue(true);
    FlexGridSizer3->Add(m_CtorIdDef, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_CtorPos = new wxCheckBox(this, ID_CHECKBOX7, _("Position"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX7"));
    m_CtorPos->SetValue(false);
    FlexGridSizer3->Add(m_CtorPos, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_CtorPosDef = new wxCheckBox(this, ID_CHECKBOX11, _("Def. value"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX11"));
    m_CtorPosDef->SetValue(true);
    m_CtorPosDef->Disable();
    FlexGridSizer3->Add(m_CtorPosDef, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_CtorSize = new wxCheckBox(this, ID_CHECKBOX8, _("Size"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX8"));
    m_CtorSize->SetValue(false);
    FlexGridSizer3->Add(m_CtorSize, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_CtorSizeDef = new wxCheckBox(this, ID_CHECKBOX12, _("Def. value"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX12"));
    m_CtorSizeDef->SetValue(true);
    m_CtorSizeDef->Disable();
    FlexGridSizer3->Add(m_CtorSizeDef, 1, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    FlexGridSizer2->Add(FlexGridSizer3, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StaticText6 = new wxStaticText(this, wxID_ANY, _("Custom arguments:"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer2->Add(StaticText6, 1, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_CtorCustom = new wxTextCtrl(this, ID_TEXTCTRL7, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL7"));
    FlexGridSizer2->Add(m_CtorCustom, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_AdvancedOptionsSizer->Add(FlexGridSizer2, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_UseFwdDecl = new wxCheckBox(this, ID_CHECKBOX14, _("Use forward declarations"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX14"));
    m_UseFwdDecl->SetValue(false);
    m_AdvancedOptionsSizer->Add(m_UseFwdDecl, 0, wxLEFT|wxRIGHT|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_UseI18n = new wxCheckBox(this, ID_CHECKBOX15, _("Use internationalize"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX15"));
    m_UseI18n->SetValue(true);
    m_AdvancedOptionsSizer->Add(m_UseI18n, 0, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
    m_AddWxs = new wxCheckBox(this, ID_CHECKBOX13, _("Add wxs file to project"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX13"));
    m_AddWxs->SetValue(true);
    m_AdvancedOptionsSizer->Add(m_AddWxs, 0, wxBOTTOM|wxLEFT|wxRIGHT|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_RootSizer->Add(m_AdvancedOptionsSizer, 0, wxLEFT|wxRIGHT|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    m_RootSizer->Add(300,5,0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    StdDialogButtonSizer1 = new wxStdDialogButtonSizer();
    StdDialogButtonSizer1->AddButton(new wxButton(this, wxID_OK, wxEmptyString));
    StdDialogButtonSizer1->AddButton(new wxButton(this, wxID_CANCEL, wxEmptyString));
    StdDialogButtonSizer1->Realize();
    m_RootSizer->Add(StdDialogButtonSizer1, 0, wxBOTTOM|wxLEFT|wxRIGHT|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    SetSizer(m_RootSizer);
    m_RootSizer->Fit(this);
    m_RootSizer->SetSizeHints(this);
    Center();

    Connect(ID_TEXTCTRL1,wxEVT_COMMAND_TEXT_UPDATED,(wxObjectEventFunction)&wxsNewWindowDlg::OnClassChanged);
    Connect(ID_TEXTCTRL2,wxEVT_COMMAND_TEXT_UPDATED,(wxObjectEventFunction)&wxsNewWindowDlg::OnHeaderChanged);
    Connect(ID_TEXTCTRL3,wxEVT_COMMAND_TEXT_UPDATED,(wxObjectEventFunction)&wxsNewWindowDlg::OnSourceChanged);
    Connect(ID_CHECKBOX1,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnUseXrcChange);
    Connect(ID_TEXTCTRL4,wxEVT_COMMAND_TEXT_UPDATED,(wxObjectEventFunction)&wxsNewWindowDlg::OnXrcChanged);
    Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnAdvOpsClick);
    Connect(ID_CHECKBOX2,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnUsePCHClick);
    Connect(ID_CHECKBOX4,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnUseInitFuncClick);
    Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnScopeIdsClick);
    Connect(ID_BUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnScopeMembersClick);
    Connect(ID_BUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnScopeHandlersClick);
    Connect(ID_CHECKBOX5,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnCtorParentClick);
    Connect(ID_CHECKBOX9,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnCtorParentDefClick);
    Connect(ID_CHECKBOX6,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnCtorIdClick);
    Connect(ID_CHECKBOX10,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnCtorIdDefClick);
    Connect(ID_CHECKBOX7,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnCtorPosClick);
    Connect(ID_CHECKBOX11,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnCtorPosDefClick);
    Connect(ID_CHECKBOX8,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnCtorSizeClick);
    Connect(ID_CHECKBOX12,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsNewWindowDlg::OnCtorSizeDefClick);
    //*)

    ConfigManager* Cfg = Manager::Get()->GetConfigManager(_T("wxsmith"));

    m_BlockText = true;
    m_SourceDirectory = Cfg->Read(_T("/newresource/sourcedirectory"),_T(""));

    wxString StrippedName = ResType.Mid(2);
    wxString ResName = wxString::Format(_("New%s"),StrippedName.c_str());
    m_Class->SetValue(ResName);
    m_Source->SetValue(m_SourceDirectory + ResName+_T(".cpp"));
    m_Header->SetValue(m_SourceDirectory + ResName+_T(".h"));
    m_Xrc   ->SetValue(m_SourceDirectory + ResName+_T(".xrc"));
    m_Xrc->Disable();
    SetTitle(wxString::Format(_("New %s resource"),ResType.c_str()));
    DetectPchFile();
    m_BaseClass->SetValue(ResType);
    wxCommandEvent event;
    OnAdvOpsClick(event);
    Center();
    m_AppManaged =
        m_Project->GetGUI() &&
        m_Project->GetGUI()->GetName()==_T("wxWidgets") &&
        m_Project->GetGUI()->CheckIfApplicationManaged();
    m_XRCAutoload->SetValue(m_AppManaged);

    m_UseInitFunc->SetValue(Cfg->ReadBool(_T("/newresource/useinitfunc"),m_UseInitFunc->GetValue()));
    m_InitFunc->Enable(m_UseInitFunc->GetValue());
    m_InitFunc->SetValue(Cfg->Read(_T("/newresource/initfunc"),m_InitFunc->GetValue()));
    m_CtorParent->SetValue(Cfg->ReadBool(_T("/newresource/ctorparent"),m_CtorParent->GetValue()));
    m_CtorParentDef->Enable(m_CtorParent->GetValue());
    m_CtorParentDef->SetValue(Cfg->ReadBool(_T("/newresource/ctorparentdef"),m_CtorParentDef->GetValue()));
    m_CtorId->SetValue(Cfg->ReadBool(_T("/newresource/ctorid"),m_CtorId->GetValue()));
    m_CtorIdDef->Enable(m_CtorId->GetValue());
    m_CtorIdDef->SetValue(Cfg->ReadBool(_T("/newresource/ctorid"),m_CtorIdDef->GetValue()));
    m_CtorPos->SetValue(Cfg->ReadBool(_T("/newresource/ctorpos"),m_CtorPos->GetValue()));
    m_CtorPosDef->Enable(m_CtorPos->GetValue());
    m_CtorPosDef->SetValue(Cfg->ReadBool(_T("/newresource/ctorpos"),m_CtorPosDef->GetValue()));
    m_CtorSize->SetValue(Cfg->ReadBool(_T("/newresource/ctorsize"),m_CtorSize->GetValue()));
    m_CtorSizeDef->Enable(m_CtorSize->GetValue());
    m_CtorSizeDef->SetValue(Cfg->ReadBool(_T("/newresource/ctorsize"),m_CtorSizeDef->GetValue()));
    m_UseXrc->SetValue(Cfg->ReadBool(_T("/newresource/usexrc"),m_UseXrc->GetValue()));
    m_Xrc->Enable(m_UseXrc->GetValue());
    m_XRCAutoload->SetValue(Cfg->ReadBool(_T("/newresource/xrcautoloag"),m_XRCAutoload->GetValue()));
    m_AddWxs->SetValue(Cfg->ReadBool(_T("/newresource/addwxs"),m_AddWxs->GetValue()));
    m_ScopeIdsVal = (wxsItemRes::NewResourceParams::Scope)Cfg->ReadInt(_T("/newresource/scopeids"),(int)wxsItemRes::NewResourceParams::Protected);
    m_ScopeMembersVal = (wxsItemRes::NewResourceParams::Scope)Cfg->ReadInt(_T("/newresource/scopemembers"),(int)wxsItemRes::NewResourceParams::Public);
    m_ScopeHandlersVal = (wxsItemRes::NewResourceParams::Scope)Cfg->ReadInt(_T("/newresource/scopehandlers"),(int)wxsItemRes::NewResourceParams::Private);
    m_UseFwdDecl->SetValue(Cfg->ReadBool(_T("/newresource/usefwddecl"),m_UseFwdDecl->GetValue()));
    m_UseI18n->SetValue(Cfg->ReadBool(_T("/newresource/usei18n"),m_UseI18n->GetValue()));
    m_PchGuard->SetValue(Cfg->Read(_T("/newresource/pchguard"),m_PchGuard->GetValue()));
    UpdateScopeButtons();
    OnUseXrcChange(event);

    m_BlockText = false;

}
示例#24
0
bool CLocalListView::DisplayDir(wxString dirname)
{
	CancelLabelEdit();

	wxString focused;
	std::list<wxString> selectedNames;
	bool ensureVisible = false;
	if (m_dir != dirname)
	{
		ResetSearchPrefix();

		if (IsComparing())
			ExitComparisonMode();

		ClearSelection();
		focused = m_pState->GetPreviouslyVisitedLocalSubdir();
		ensureVisible = !focused.IsEmpty();
		if (focused.IsEmpty())
			focused = _T("..");

		if (GetItemCount())
			EnsureVisible(0);
		m_dir = dirname;
	}
	else
	{
		// Remember which items were selected
		selectedNames = RememberSelectedItems(focused);
	}

	if (m_pFilelistStatusBar)
		m_pFilelistStatusBar->UnselectAll();

	const int oldItemCount = m_indexMapping.size();

	m_fileData.clear();
	m_indexMapping.clear();

	m_hasParent = CLocalPath(dirname).HasLogicalParent();

	if (m_hasParent)
	{
		CLocalFileData data;
		data.flags = normal;
		data.dir = true;
		data.icon = -2;
		data.name = _T("..");
#ifdef __WXMSW__
		data.label = _T("..");
#endif
		data.size = -1;
		m_fileData.push_back(data);
		m_indexMapping.push_back(0);
	}

#ifdef __WXMSW__
	if (dirname == _T("\\"))
	{
		DisplayDrives();
	}
	else if (dirname.Left(2) == _T("\\\\"))
	{
		int pos = dirname.Mid(2).Find('\\');
		if (pos != -1 && pos + 3 != (int)dirname.Len())
			goto regular_dir;

		// UNC path without shares
		DisplayShares(dirname);
	}
	else
#endif
	{
#ifdef __WXMSW__
regular_dir:
#endif
		CFilterManager filter;
		CLocalFileSystem local_filesystem;

		if (!local_filesystem.BeginFindFiles(dirname, false))
		{
			SetItemCount(1);
			return false;
		}

		wxLongLong totalSize;
		int unknown_sizes = 0;
		int totalFileCount = 0;
		int totalDirCount = 0;
		int hidden = 0;

		int num = m_fileData.size();
		CLocalFileData data;
		data.flags = normal;
		data.icon = -2;
		bool wasLink;
		while (local_filesystem.GetNextFile(data.name, wasLink, data.dir, &data.size, &data.lastModified, &data.attributes))
		{
			if (data.name.IsEmpty())
			{
				wxGetApp().DisplayEncodingWarning();
				continue;
			}
#ifdef __WXMSW__
			data.label = data.name;
#endif

			m_fileData.push_back(data);
			if (!filter.FilenameFiltered(data.name, dirname, data.dir, data.size, true, data.attributes, data.lastModified))
			{
				if (data.dir)
					totalDirCount++;
				else
				{
					if (data.size != -1)
						totalSize += data.size;
					else
						unknown_sizes++;
					totalFileCount++;
				}
				m_indexMapping.push_back(num);
			}
			else
				hidden++;
			num++;
		}

		if (m_pFilelistStatusBar)
			m_pFilelistStatusBar->SetDirectoryContents(totalFileCount, totalDirCount, totalSize, unknown_sizes, hidden);
	}

	if (m_dropTarget != -1)
	{
		CLocalFileData* data = GetData(m_dropTarget);
		if (!data || !data->dir)
		{
			SetItemState(m_dropTarget, 0, wxLIST_STATE_DROPHILITED);
			m_dropTarget = -1;
		}
	}

	const int count = m_indexMapping.size();
	if (oldItemCount != count)
		SetItemCount(count);

	SortList(-1, -1, false);

	if (IsComparing())
	{
		m_originalIndexMapping.clear();
		RefreshComparison();
	}

	ReselectItems(selectedNames, focused, ensureVisible);

	RefreshListOnly();

	return true;
}
示例#25
0
bool CSiteManager::AddBookmark(wxString sitePath, const wxString& name, const wxString &local_dir, const CServerPath &remote_dir, bool sync)
{
	if (local_dir.empty() && remote_dir.IsEmpty())
		return false;

	if (sitePath[0] != '0')
		return false;

	sitePath = sitePath.Mid(1);

	// We have to synchronize access to sitemanager.xml so that multiple processed don't write
	// to the same file or one is reading while the other one writes.
	CInterProcessMutex mutex(MUTEX_SITEMANAGER);

	CXmlFile file;
	TiXmlElement* pDocument = file.Load(_T("sitemanager"));

	if (!pDocument)
	{
		wxString msg = file.GetError() + _T("\n") + _("The bookmark could not be added.");
		wxMessageBox(msg, _("Error loading xml file"), wxICON_ERROR);

		return false;
	}

	TiXmlElement* pElement = pDocument->FirstChildElement("Servers");
	if (!pElement)
		return false;

	std::list<wxString> segments;
	if (!UnescapeSitePath(sitePath, segments))
	{
		wxMessageBox(_("Site path is malformed."), _("Invalid site path"));
		return 0;
	}

	TiXmlElement* pChild = GetElementByPath(pElement, segments);
	if (!pChild || strcmp(pChild->Value(), "Server"))
	{
		wxMessageBox(_("Site does not exist."), _("Invalid site path"));
		return 0;
	}

	// Bookmarks
	TiXmlElement *pInsertBefore = 0;
	TiXmlElement* pBookmark;
	for (pBookmark = pChild->FirstChildElement("Bookmark"); pBookmark; pBookmark = pBookmark->NextSiblingElement("Bookmark"))
	{
		TiXmlHandle handle(pBookmark);

		wxString old_name = GetTextElement_Trimmed(pBookmark, "Name");
		if (old_name.empty())
			continue;

		if (name == old_name)
		{
			wxMessageBox(_("Name of bookmark already exists."), _("New bookmark"), wxICON_EXCLAMATION);
			return false;
		}
		if (name < old_name && !pInsertBefore)
			pInsertBefore = pBookmark;
	}

	if (pInsertBefore)
		pBookmark = pChild->InsertBeforeChild(pInsertBefore, TiXmlElement("Bookmark"))->ToElement();
	else
		pBookmark = pChild->LinkEndChild(new TiXmlElement("Bookmark"))->ToElement();
	AddTextElement(pBookmark, "Name", name);
	if (!local_dir.empty())
		AddTextElement(pBookmark, "LocalDir", local_dir);
	if (!remote_dir.IsEmpty())
		AddTextElement(pBookmark, "RemoteDir", remote_dir.GetSafePath());
	if (sync)
		AddTextElementRaw(pBookmark, "SyncBrowsing", "1");

	wxString error;
	if (!file.Save(&error))
	{
		if (COptions::Get()->GetOptionVal(OPTION_DEFAULT_KIOSKMODE) == 2)
			return true;

		wxString msg = wxString::Format(_("Could not write \"%s\", the selected sites could not be exported: %s"), file.GetFileName().GetFullPath().c_str(), error.c_str());
		wxMessageBox(msg, _("Error writing xml file"), wxICON_ERROR);
	}

	return true;
}
示例#26
0
void pgForeignTable::iSetOptions(const wxString &tmpoptions)
{
	wxString tmp;
	wxString option;
	wxString value;
	wxString currentChar;
	bool wrappedInQuotes, antislash;

	options = wxEmptyString;

	if (tmpoptions == wxEmptyString)
		return;

	// parse the options string
	// we start at 1 and stop at length-1 to get rid of the { and } of the array
	for (unsigned int index = 1 ; index < tmpoptions.Length() - 1 ; index++)
	{
		// get current char
		currentChar = tmpoptions.Mid(index, 1);

		// if there is a double quote at the beginning of an option,
		// the whole option=value will be wrapped in quotes
		if (currentChar == wxT("\"") && tmp.IsEmpty())
			wrappedInQuotes = true;
		else if (currentChar == wxT("\\") && wrappedInQuotes)
			antislash = true;
		else
		{
			if ((currentChar == wxT(",") && !wrappedInQuotes && !tmp.IsEmpty())
			        || (currentChar == wxT("\"") && wrappedInQuotes && !antislash && !tmp.IsEmpty()))
			{
				// new options

				if (currentChar == wxT("\"") && wrappedInQuotes && !antislash && !tmp.IsEmpty())
				{
					// In this specific case, the next character is the comma,
					// but we don't want to start the next option with the comma
					// so we skip it right now
					index++;
				}

				// we need to grab option and value from tmp string
				option = tmp.BeforeFirst('=');
				value = tmp.AfterFirst('=');

				// put them in the array
				optionsArray.Add(option);
				optionsArray.Add(value);

				// build the options string
				if (options.Length() > 0)
					options += wxT(", ");
				options += option + wxT(" '") + value + wxT("'");

				// reinit tmp
				tmp = wxEmptyString;
				wrappedInQuotes = false;
			}
			else
				tmp += currentChar;
			antislash = false;
		}
	}

	// last options

	if (!tmp.IsEmpty())
	{
		// we need to grab option and value from tmp string
		option = tmp.BeforeFirst('=');
		value = tmp.AfterFirst('=');

		// put them in the array
		optionsArray.Add(option);
		optionsArray.Add(value);

		// build the options string
		if (options.Length() > 0)
			options += wxT(", ");
		options += option + wxT(" '") + value + wxT("'");
	}
}
示例#27
0
MPQArchive::MPQArchive(wxString filename) : ok(false)
{
	wxLogMessage(wxT("Opening %s %s"), filename.Mid(gamePath.Len()).c_str(), isPartialMPQ(filename) ? "(Partial)" : "");
	g_modelViewer->SetStatusText(wxT("Initiating "+filename+wxT(" Archive")));
#ifndef _MINGW
	if (!SFileOpenArchive(filename.fn_str(), 0, MPQ_OPEN_FORCE_MPQ_V1|MPQ_OPEN_READ_ONLY, &mpq_a )) {
#else
	if (!SFileOpenArchive(filename.char_str(), 0, MPQ_OPEN_FORCE_MPQ_V1|MPQ_OPEN_READ_ONLY, &mpq_a )) {
#endif
		int nError = GetLastError();
		wxLogMessage(wxT("Error opening archive %s, error #: 0x%X"), filename.Mid(gamePath.Len()).c_str(), nError);
		return;
	}

	
	// do patch, but skip cache\ directory
	if (!(filename.BeforeLast(SLASH).Lower().Contains(wxT("cache")) && 
		filename.AfterLast(SLASH).Lower().StartsWith(wxT("patch"))) &&
		!isPartialMPQ(filename)) { // skip the PTCH files atrchives
		// do patch
		for(ssize_t j=mpqArchives.GetCount()-1; j>=0; j--) {
			if (!mpqArchives[j].AfterLast(SLASH).StartsWith(wxT("wow-update-")))
				continue;
			if (mpqArchives[j].AfterLast(SLASH).Len() == strlen("wow-update-xxxxx.mpq")) {
#ifndef _MINGW
				SFileOpenPatchArchive(mpq_a, mpqArchives[j].fn_str(), "base", 0);
				SFileOpenPatchArchive(mpq_a, mpqArchives[j].fn_str(), langName.fn_str(), 0);
#else
				SFileOpenPatchArchive(mpq_a, mpqArchives[j].char_str(), "base", 0);
				SFileOpenPatchArchive(mpq_a, mpqArchives[j].char_str(), langName.char_str(), 0);
#endif
				// too many for ptr client, just comment it
				// wxLogMessage(wxT("Appending base & %s patch %s"), langName.c_str(), mpqArchives[j].Mid(gamePath.Len()).c_str());
			} else if (mpqArchives[j].BeforeLast(SLASH) == filename.BeforeLast(SLASH)) { // same directory only
#ifndef _MINGW
				SFileOpenPatchArchive(mpq_a, mpqArchives[j].fn_str(), "", 0);
#else
				SFileOpenPatchArchive(mpq_a, mpqArchives[j].char_str(), "", 0);
#endif
				// wxLogMessage(wxT("Appending patch %s"), mpqArchives[j].Mid(gamePath.Len()).c_str());
			}
		}
	}

	ok = true;
	gOpenArchives.push_back( make_pair( filename, &mpq_a ) );
}

MPQArchive::~MPQArchive()
{
	/*
	for(ArchiveSet::iterator i=gOpenArchives.begin(); i!=gOpenArchives.end();++i)
	{
		mpq_archive &mpq_a = **i;
		
		free(mpq_a.header);
	}
	*/
	//gOpenArchives.erase(gOpenArchives.begin(), gOpenArchives.end());
}

bool MPQArchive::isPartialMPQ(wxString filename)
{
	if (filename.AfterLast(SLASH).StartsWith(wxT("wow-update-")))
		return true;
	return false;
}

void MPQArchive::close()
{
	if (ok == false)
		return;
	SFileCloseArchive(mpq_a);
	for(ArchiveSet::iterator it=gOpenArchives.begin(); it!=gOpenArchives.end();++it)
	{
		HANDLE &mpq_b = *it->second;
		if (&mpq_b == &mpq_a) {
			gOpenArchives.erase(it);
			//delete (*it);
			return;
		}
	}
	
}

bool MPQFile::isPartialMPQ(wxString filename)
{
	if (filename.AfterLast(SLASH).StartsWith(wxT("wow-update-")))
		return true;
	return false;
}

void
MPQFile::openFile(wxString filename)
{
	eof = false;
	buffer = 0;
	pointer = 0;
	size = 0;
	if( useLocalFiles ) {
		wxString fn1 = wxGetCwd()+SLASH+wxT("Import")+SLASH;
		wxString fn2 = fn1;
		wxString fn3 = gamePath;
		fn1.Append(filename);
		fn2.Append(filename.AfterLast(SLASH));
		fn3.Append(filename);

		wxString fns[] = { fn1, fn2, fn3 };
		for(size_t i=0; i<WXSIZEOF(fns); i++) {
			wxString fn = fns[i];
			if (wxFile::Exists(fn)) {
				// success
				wxFile file;
				// if successfully opened
				if (file.Open(fn, wxFile::read)) {
					size = file.Length();
					if (size > 0) {
						buffer = new unsigned char[size];
						// if successfully read data
						if (file.Read(buffer, size) > 0) {
							eof = false;
							file.Close();
							return;
						} else {
							wxDELETEA(buffer);
							eof = true;
							size = 0;
						}
					}
					file.Close();
				}
			}
		}
	}

	// zhCN alternate file mode
	if (bAlternate && !filename.Lower().StartsWith(wxT("alternate"))) {
		wxString alterName = wxT("alternate")+SLASH+filename;

		for(ArchiveSet::iterator i=gOpenArchives.begin(); i!=gOpenArchives.end(); ++i)
		{
			HANDLE &mpq_a = *i->second;

			HANDLE fh;
#ifndef _MINGW
			if( !SFileOpenFileEx( mpq_a, alterName.fn_str(), SFILE_OPEN_PATCHED_FILE, &fh ) )
#else
			if( !SFileOpenFileEx( mpq_a, alterName.char_str(), SFILE_OPEN_PATCHED_FILE, &fh ) )
#endif
				continue;

			// Found!
			DWORD filesize = SFileGetFileSize( fh );
			size = filesize;

			// HACK: in patch.mpq some files don't want to open and give 1 for filesize
			if (size<=1) {
				eof = true;
				buffer = 0;
				return;
			}

			buffer = new unsigned char[size];
			SFileReadFile( fh, buffer, (DWORD)size );
			SFileCloseFile( fh );

			return;
		}
	}

	for(ArchiveSet::iterator i=gOpenArchives.begin(); i!=gOpenArchives.end(); ++i)
	{
		HANDLE &mpq_a = *i->second;

		HANDLE fh;
#ifndef _MINGW
		if( !SFileOpenFileEx( mpq_a, filename.fn_str(), SFILE_OPEN_PATCHED_FILE, &fh ) )
#else
		if( !SFileOpenFileEx( mpq_a, filename.char_str(), SFILE_OPEN_PATCHED_FILE, &fh ) )
#endif
			continue;

		// Found!
		DWORD filesize = SFileGetFileSize( fh );
		size = filesize;

		// HACK: in patch.mpq some files don't want to open and give 1 for filesize
		if (size<=1) {
			eof = true;
			buffer = 0;
			return;
		}

		buffer = new unsigned char[size];
		SFileReadFile( fh, buffer, (DWORD)size );
		SFileCloseFile( fh );

		return;
	}

	eof = true;
	buffer = 0;
}
示例#28
0
文件: misc.cpp 项目: swflb/pgadmin3
void DisplayExternalHelp(const wxString &helpTopic, const wxString &docPath, wxHelpControllerBase *helpCtl, const bool init)
{
	// Build the page name
	wxString page;
	int hashPos = helpTopic.Find('#');
	if (hashPos < 0)
		page = helpTopic + wxT(".html");
	else
		page = helpTopic.Left(hashPos) + wxT(".html") + helpTopic.Mid(hashPos);

	// If the docPath ends in .pdf, then open the file in the browser. No
	// bookmarks though :-(
	if (docPath.Lower().EndsWith(wxT(".pdf")))
	{
		wxLaunchDefaultBrowser(docPath);
		return;
	}

	// If the docPath doesn't end in .chm, .zip or .hhp, then we must be using
	// plain HTML files, so just fire off the browser and be done with it.
	if (!docPath.Lower().EndsWith(wxT(".hhp")) &&
#if defined (__WXMSW__) || wxUSE_LIBMSPACK
	        !docPath.Lower().EndsWith(wxT(".chm")) &&
#endif
	        !docPath.Lower().EndsWith(wxT(".zip")))
	{
		wxLaunchDefaultBrowser(docPath + page);
		return;
	}

	// We must be using HTML Help, so init the appropriate help controller
	// Note the path that we init for - if it changes, we need to init a
	// new controller in case it's no longer the same type
	if (init || !helpCtl)
	{
		// Get shot of the old help controller if there is one.
		if (helpCtl)
			delete helpCtl;

#ifdef __WXMSW__
		// For Windows builds we us the MS HTML Help viewer for .chm files
		if (docPath.Lower().EndsWith(wxT(".chm")) && wxFile::Exists(docPath))
		{
			helpCtl = new wxCHMHelpController();
			helpCtl->Initialize(docPath);
		}
		else
#endif
#if wxUSE_LIBMSPACK
			// If we can use a .chm file...
			if ((docPath.Lower().EndsWith(wxT(".chm")) && wxFile::Exists(docPath)) ||
			        (docPath.Lower().EndsWith(wxT(".hhp")) && wxFile::Exists(docPath)) ||
			        (docPath.Lower().EndsWith(wxT(".zip")) && wxFile::Exists(docPath)))
#else
			// Otherwise...
			if ((docPath.Lower().EndsWith(wxT(".hhp")) && wxFile::Exists(docPath)) ||
			        (docPath.Lower().EndsWith(wxT(".zip")) && wxFile::Exists(docPath)))
#endif
			{
				helpCtl = new wxHtmlHelpController();
				helpCtl->Initialize(docPath);
			}
	}

	// Display the page using the help controller
	// If it's foobar'ed, use the browser.
	if (helpCtl)
	{
		if (helpTopic == wxT("index.html"))
			helpCtl->DisplayContents();
		else
			helpCtl->DisplaySection(page);
	}
	else
	{
		wxLogError(_("The help source (\"%s\") could not be opened. Please check the help configuration options."), docPath.c_str());
	}
}
示例#29
0
void CAPRSWriter::writeData(const wxString& callsign, const CAMBEData& data)
{
	if (data.isEnd())
		return;

	wxString band = callsign.Mid(LONG_CALLSIGN_LENGTH - 1U);

	CAPRSEntry* entry = m_array[band];
	if (entry == NULL) {
		wxLogError(wxT("Cannot find the band %s in the APRS array"), band.c_str());
		return;
	}

	CAPRSCollector* collector = entry->getCollector();

	if (data.isSync()) {
		collector->sync();
		return;
	}

	unsigned char buffer[300U];
	data.getData(buffer, DV_FRAME_MAX_LENGTH_BYTES);

	bool complete = collector->writeData(buffer + VOICE_FRAME_LENGTH_BYTES);
	if (!complete)
		return;

	if (!m_enabled) {
		collector->reset();
		return;
	}

	// Check the transmission timer
	bool ok = entry->isOK();
	if (!ok) {
		collector->reset();
		return;
	}

	unsigned int length = collector->getData(buffer, 300U);
	wxString text((char*)buffer, wxConvLocal, length);

	int n = text.Find(wxT(':'));
	if (n == wxNOT_FOUND) {
		collector->reset();
		return;
	}

	wxString header = text.Left(n);
	wxString body   = text.Mid(n + 1U);

	// If we already have a q-construct, don't send it on
	n = header.Find(wxT('q'));
	if (n != wxNOT_FOUND)
		return;

	// Remove the trailing \r
	n = body.Find(wxT('\r'));
	if (n != wxNOT_FOUND)
		body = body.Left(n);

	wxString output;
	output.Printf(wxT("%s,qAR,%s-%s:%s"), header.c_str(), entry->getCallsign().c_str(), entry->getBand().c_str(), body.c_str());

	char ascii[300U];
	::memset(ascii, 0x00, 300U);
	for (unsigned int i = 0U; i < output.Len(); i++)
		ascii[i] = output.GetChar(i);

	m_thread->write(ascii);

	collector->reset();
}
示例#30
0
文件: ex.cpp 项目: Emmavw/wxExtension
bool wxExEx::Command(const wxString& command)
{
  if (command.empty() || !command.StartsWith(":"))
  {
    return false;
  }
  
  bool result = true;

  if (command == ":")
  {
    m_Frame->GetExCommand(this, command);
    return true;
  }
  else if (command == ":$")
  {
    m_STC->DocumentEnd();
  }
  else if (command == ":close")
  {
    wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, wxID_CLOSE);
    wxPostEvent(wxTheApp->GetTopWindow(), event);
  }
  else if (command == ":d")
  {
    return Delete(1);
  }
  else if (command.StartsWith(":e"))
  {
    wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, wxID_OPEN);
    
    if (command.Contains(" "))
    {
      event.SetString(command.AfterFirst(' '));
    }
    
    wxPostEvent(wxTheApp->GetTopWindow(), event);
  }
  else if (command.StartsWith(":g"))
  {
    result = CommandGlobal(command.AfterFirst('g'));
  }
  else if (command == ":n")
  {
    wxExSTC* stc = m_Frame->ExecExCommand(ID_EDIT_NEXT);
    
    if (stc != NULL)
    {
      if (m_Macros.IsPlayback())
      {
        m_STC = stc;
      }
    }
    else
    {
      result = false;
    }
  }
  else if (command == ":prev")
  {
    wxExSTC* stc = m_Frame->ExecExCommand(ID_EDIT_PREVIOUS);
    
    if (stc != NULL)
    {
      if (m_Macros.IsPlayback())
      {
        m_STC = stc;
      }
    }
    else
    {
      result = false;
    }
  }
  else if (command == ":q")
  {
    wxCloseEvent event(wxEVT_CLOSE_WINDOW);
    wxPostEvent(wxTheApp->GetTopWindow(), event);
  }
  else if (command == ":q!")
  {
    wxCloseEvent event(wxEVT_CLOSE_WINDOW);
    event.SetCanVeto(false); 
    wxPostEvent(wxTheApp->GetTopWindow(), event);
  }
  else if (command.StartsWith(":r"))
  {
    wxString arg(command.AfterFirst(' '));
    arg.Trim(false); // from left
    
    if (arg.StartsWith("!"))
    {
      if (m_Process == NULL)
      {
        m_Process = new wxExProcess;
      }
    
      m_Process->Execute(arg.AfterFirst('!'), wxEXEC_SYNC);
      m_Process->HideDialog();
      
      m_STC->AddText(m_Process->GetOutput());
    }
    else
    {
      wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_EDIT_READ);
      event.SetString(arg);
      wxPostEvent(wxTheApp->GetTopWindow(), event);
    }
  }
  // e.g. set ts=4
  else if (command.StartsWith(":set "))
  {
    result = CommandSet(command.Mid(5));
  }
  else if (command.StartsWith(":w"))
  {
    if (command.Contains(" "))
    {
      wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, wxID_SAVEAS);
      event.SetString(command.AfterFirst(' '));
      wxPostEvent(wxTheApp->GetTopWindow(), event);
    }
    else
    {
      wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, wxID_SAVE);
      wxPostEvent(wxTheApp->GetTopWindow(), event);
    }
  }
  else if (command == ":x")
  {
    wxPostEvent(wxTheApp->GetTopWindow(), 
      wxCommandEvent(wxEVT_COMMAND_MENU_SELECTED, wxID_SAVE));
      
    wxPostEvent(wxTheApp->GetTopWindow(), 
      wxCloseEvent(wxEVT_CLOSE_WINDOW));
  }
  else if (command == ":y")
  {
    Yank(1);
  }
  else if (command.Last() == '=')
  {
    const int no = ToLineNumber(command.AfterFirst(':').BeforeLast('='));
    
    if (no == 0)
    {
      return false;
    }
    
    m_Frame->ShowExMessage(wxString::Format("%d", no));
    return true;
  }
  else if (command.StartsWith(":!"))
  {
    if (m_Process == NULL)
    {
      m_Process = new wxExProcess;
    }
    
    m_Process->Execute(command.AfterFirst('!'));
  }
  else if (command.AfterFirst(':').IsNumber())
  {
    m_STC->GotoLineAndSelect(atoi(command.AfterFirst(':').c_str()));
  }
  else
  {
    result = CommandRange(command.AfterFirst(':'));
  }

  if (result)
  {  
    SetLastCommand(command);
    MacroRecord(command);
  }
  else
  {
    wxBell();
  }
  
  return result;
}