Example #1
0
bool CSSHTunnelThread::IsHostKeyVerified(const wxString &newHostKey)
{
	bool bIsVerified = false;
	wxString cachedHostKey = settings->Read(wxT("HostKeys/") + m_tunnelhost, wxEmptyString);

	// If cached host key is empty then ask user to accept or reject
	if (cachedHostKey == wxEmptyString)
	{
		// Prompt User to accept or reject
		wxString msg = wxString::Format(wxT("Host key received for the SSH server \"%s\" is \n\n%s\n\nWould you like to accept it and continue with the connection?"), m_tunnelhost.c_str(), newHostKey.c_str());
		int answer = wxMessageBox(msg, wxT("Host key verification"), wxYES_NO | wxNO_DEFAULT);
		if (answer == wxYES)
		{
			// Write the host key with respect to tunnel host
			settings->Write(wxT("HostKeys/") + m_tunnelhost, newHostKey);
			bIsVerified = true;
		}
	}
	else
	{
		// Compare the cached host key with the new key
		if (cachedHostKey.compare(newHostKey) == 0)
			bIsVerified = true;
		else
		{
			// Prompt user to accept or reject the new host key received for the tunnel host
			wxString msg = wxString::Format(wxT("The host key received from the server \"%s\" is\n\n%s\n\nbut the stored key is\n\n%s\n\nThis may indicate that this is not the same server that was previously used.\n\nDo you wish to accept and store the new key, and continue with the connection?"), m_tunnelhost.c_str(), newHostKey.c_str(), cachedHostKey.c_str());
			int answer = wxMessageBox(msg, wxT("Host key verification - WARNING"), wxYES_NO | wxNO_DEFAULT);
			if (answer == wxYES)
			{
				// Write the host key with respect to tunnel host
				settings->Write(wxT("HostKeys/") + m_tunnelhost, newHostKey);
				bIsVerified = true;
			}
		}
	}

	return bIsVerified;
}
Example #2
0
void wxStaticText::DoSetLabel(const wxString& str)
{
    SetWindowText(GetHwnd(), str.c_str());
}
Example #3
0
// ----------------------------------------------------------------------------
void MMSapEvents::OnMiddleMouseDown(wxMouseEvent& event, cbStyledTextCtrl* ed)
// ----------------------------------------------------------------------------
{
    // If selected text, paste selected text at current cursor position
    // If selected text, and user middle-clicks inside selection, copy to clipboard
    // If no selected text, paste clipboard data at cursor position

    int pos = ed->PositionFromPoint(wxPoint(event.GetX(), event.GetY()));

    if(pos == wxSCI_INVALID_POSITION)
        return;

    int start = ed->GetSelectionStart();
    int end = ed->GetSelectionEnd();

    const wxString selectedText = ed->GetSelectedText();

    // If no current selection, or shift key is down, use paste from the clipboard
    bool shiftKeyState = ::wxGetKeyState(WXK_SHIFT);

    if (  shiftKeyState || selectedText.IsEmpty() )
    {
        PasteFromClipboard( event, ed, shiftKeyState );
        return;
    }

    //if user middle-clicked inside the selection, copy to clipboard
    if ( (pos >= start) && (pos <= end) )
    {
        #if defined(__WXGTK__)
            gtk_clipboard_set_text(
                gtk_clipboard_get(GDK_SELECTION_PRIMARY),
                selectedText.mb_str(wxConvUTF8),
                selectedText.Length() );
        #else //__WXMSW__
                if (wxTheClipboard->Open())
                {
                    wxTheClipboard->AddData(new wxTextDataObject(selectedText));
                    wxTheClipboard->Close();
                }
        #endif
        return;
    }//if

    if(pos < ed->GetCurrentPos())
    {
        start += selectedText.length();
        end += selectedText.length();
    }

    #if defined(LOGGING)
    //LOGIT( _T("pos,start,end[%d][%d][%d]"), pos, start, end);
    #endif

    // paste selected text at current cursor position
    ed->InsertText(pos, selectedText);
    //-SetSelection(start, end);
    ed->GotoPos(pos);
    ed->SetSelectionVoid(pos, pos+selectedText.length());
    #if defined(LOGGING)
    LOGIT( _T("OnMiddleMouseDown[%s]"), selectedText.c_str());
    #endif

} // end of OnGPM
Example #4
0
static wxNativeFont wxLoadQueryFont(int pointSize,
                                    int family,
                                    int style,
                                    int weight,
                                    bool WXUNUSED(underlined),
                                    const wxString& facename,
                                    const wxString& xregistry,
                                    const wxString& xencoding,
                                    wxString* xFontName)
{
    wxString xfamily;
    switch (family)
    {
        case wxDECORATIVE: xfamily = wxT("lucida"); break;
        case wxROMAN:      xfamily = wxT("times");  break;
        case wxMODERN:     xfamily = wxT("courier"); break;
        case wxSWISS:      xfamily = wxT("helvetica"); break;
        case wxTELETYPE:   xfamily = wxT("lucidatypewriter"); break;
        case wxSCRIPT:     xfamily = wxT("utopia"); break;
        default:           xfamily = wxT("*");
    }
#if wxUSE_NANOX
    int xweight;
    switch (weight)
    {
         case wxBOLD:
             {
                 xweight = MWLF_WEIGHT_BOLD;
                 break;
             }
        case wxLIGHT:
             {
                 xweight = MWLF_WEIGHT_LIGHT;
                 break;
             }
         case wxNORMAL:
             {
                 xweight = MWLF_WEIGHT_NORMAL;
                 break;
             }

     default:
             {
                 xweight = MWLF_WEIGHT_DEFAULT;
                 break;
             }
    }
    GR_SCREEN_INFO screenInfo;
    GrGetScreenInfo(& screenInfo);

    int yPixelsPerCM = screenInfo.ydpcm;

    // A point is 1/72 of an inch.
    // An inch is 2.541 cm.
    // So pixelHeight = (pointSize / 72) (inches) * 2.541 (for cm) * yPixelsPerCM (for pixels)
    // In fact pointSize is 10 * the normal point size so
    // divide by 10.

    int pixelHeight = (int) ( (((float)pointSize) / 720.0) * 2.541 * (float) yPixelsPerCM) ;

    // An alternative: assume that the screen is 72 dpi.
    //int pixelHeight = (int) (((float)pointSize / 720.0) * 72.0) ;
    //int pixelHeight = (int) ((float)pointSize / 10.0) ;

    GR_LOGFONT logFont;
    logFont.lfHeight = pixelHeight;
    logFont.lfWidth = 0;
    logFont.lfEscapement = 0;
    logFont.lfOrientation = 0;
    logFont.lfWeight = xweight;
    logFont.lfItalic = (style == wxNORMAL ? 0 : 1) ;
    logFont.lfUnderline = 0;
    logFont.lfStrikeOut = 0;
    logFont.lfCharSet = MWLF_CHARSET_DEFAULT; // TODO: select appropriate one
    logFont.lfOutPrecision = MWLF_TYPE_DEFAULT;
    logFont.lfClipPrecision = 0; // Not used
    logFont.lfRoman = (family == wxROMAN ? 1 : 0) ;
    logFont.lfSerif = (family == wxSWISS ? 0 : 1) ;
    logFont.lfSansSerif = !logFont.lfSerif ;
    logFont.lfModern = (family == wxMODERN ? 1 : 0) ;
    logFont.lfProportional = (family == wxTELETYPE ? 0 : 1) ;
    logFont.lfOblique = 0;
    logFont.lfSmallCaps = 0;
    logFont.lfPitch = 0; // 0 = default
    strcpy(logFont.lfFaceName, facename.c_str());

    XFontStruct* fontInfo = (XFontStruct*) malloc(sizeof(XFontStruct));
    fontInfo->fid = GrCreateFont((GR_CHAR*) facename.c_str(), pixelHeight, & logFont);
    GrGetFontInfo(fontInfo->fid, & fontInfo->info);
    return (wxNativeFont) fontInfo;

#else
    wxString fontSpec;
    if (!facename.empty())
    {
        fontSpec.Printf(wxT("-*-%s-*-*-normal-*-*-*-*-*-*-*-*-*"),
                        facename.c_str());

        if ( wxTestFontSpec(fontSpec) )
        {
            xfamily = facename;
        }
        //else: no such family, use default one instead
    }

    wxString xstyle;
    switch (style)
    {
        case wxSLANT:
            fontSpec.Printf(wxT("-*-%s-*-o-*-*-*-*-*-*-*-*-*-*"),
                    xfamily.c_str());
            if ( wxTestFontSpec(fontSpec) )
            {
                xstyle = wxT("o");
                break;
            }
            // fall through - try wxITALIC now

        case wxITALIC:
            fontSpec.Printf(wxT("-*-%s-*-i-*-*-*-*-*-*-*-*-*-*"),
                    xfamily.c_str());
            if ( wxTestFontSpec(fontSpec) )
            {
                xstyle = wxT("i");
            }
            else if ( style == wxITALIC ) // and not wxSLANT
            {
                // try wxSLANT
                fontSpec.Printf(wxT("-*-%s-*-o-*-*-*-*-*-*-*-*-*-*"),
                        xfamily.c_str());
                if ( wxTestFontSpec(fontSpec) )
                {
                    xstyle = wxT("o");
                }
                else
                {
                    // no italic, no slant - leave default
                    xstyle = wxT("*");
                }
            }
            break;

        default:
            wxFAIL_MSG(wxT("unknown font style"));
            // fall back to normal

        case wxNORMAL:
            xstyle = wxT("r");
            break;
    }

    wxString xweight;
    switch (weight)
    {
         case wxBOLD:
             {
                  fontSpec.Printf(wxT("-*-%s-bold-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("bold");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-heavy-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("heavy");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-extrabold-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("extrabold");
                      break;
                  }
                  fontSpec.Printf(wxT("-*-%s-demibold-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("demibold");
                      break;
                  }
                  fontSpec.Printf(wxT("-*-%s-black-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("black");
                      break;
                  }
                  fontSpec.Printf(wxT("-*-%s-ultrablack-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("ultrablack");
                      break;
                  }
              }
              break;
        case wxLIGHT:
             {
                  fontSpec.Printf(wxT("-*-%s-light-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("light");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-thin-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("thin");
                       break;
                  }
             }
             break;
         case wxNORMAL:
             {
                  fontSpec.Printf(wxT("-*-%s-medium-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("medium");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-normal-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("normal");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-regular-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("regular");
                      break;
                  }
                  xweight = wxT("*");
              }
              break;
        default:           xweight = wxT("*"); break;
    }

    // if pointSize is -1, don't specify any
    wxString sizeSpec;
    if ( pointSize == -1 )
    {
        sizeSpec = wxT('*');
    }
    else
    {
        sizeSpec.Printf(wxT("%d"), pointSize);
    }

    // construct the X font spec from our data
    fontSpec.Printf(wxT("-*-%s-%s-%s-normal-*-*-%s-*-*-*-*-%s-%s"),
                    xfamily.c_str(), xweight.c_str(), xstyle.c_str(),
                    sizeSpec.c_str(), xregistry.c_str(), xencoding.c_str());

    if( xFontName )
        *xFontName = fontSpec;

    return wxLoadFont(fontSpec);
#endif
    // wxUSE_NANOX
}
int
wxFontMapperBase::NonInteractiveCharsetToEncoding(const wxString& charset)
{
    wxFontEncoding encoding = wxFONTENCODING_SYSTEM;

    // we're going to modify it, make a copy
    wxString cs = charset;

#if wxUSE_CONFIG && wxUSE_FILECONFIG
    // first try the user-defined settings
    wxFontMapperPathChanger path(this, FONTMAPPER_CHARSET_PATH);
    if ( path.IsOk() )
    {
        wxConfigBase *config = GetConfig();

        // do we have an encoding for this charset?
        long value = config->Read(charset, -1l);
        if ( value != -1 )
        {
            if ( value == wxFONTENCODING_UNKNOWN )
            {
                // don't try to find it, in particular don't ask the user
                return value;
            }

            if ( value >= 0 && value <= wxFONTENCODING_MAX )
            {
                encoding = (wxFontEncoding)value;
            }
            else
            {
                wxLogDebug(wxT("corrupted config data: invalid encoding %ld for charset '%s' ignored"),
                           value, charset.c_str());
            }
        }

        if ( encoding == wxFONTENCODING_SYSTEM )
        {
            // may be we have an alias?
            config->SetPath(FONTMAPPER_CHARSET_ALIAS_PATH);

            wxString alias = config->Read(charset);
            if ( !alias.empty() )
            {
                // yes, we do - use it instead
                cs = alias;
            }
        }
    }
#endif // wxUSE_CONFIG

    // if didn't find it there, try to recognize it ourselves
    if ( encoding == wxFONTENCODING_SYSTEM )
    {
        // trim any spaces
        cs.Trim(true);
        cs.Trim(false);

        // discard the optional quotes
        if ( !cs.empty() )
        {
            if ( cs[0u] == wxT('"') && cs.Last() == wxT('"') )
            {
                cs = wxString(cs.c_str(), cs.length() - 1);
            }
        }

        for ( size_t i = 0; i < WXSIZEOF(gs_encodingNames); ++i )
        {
            for ( const wxChar* const* encName = gs_encodingNames[i]; *encName; ++encName )
            {
                if ( cs.CmpNoCase(*encName) == 0 )
                    return gs_encodings[i];
            }
        }

        cs.MakeUpper();

        if ( cs.Left(3) == wxT("ISO") )
        {
            // the dash is optional (or, to be exact, it is not, but
            // several broken programs "forget" it)
            const wxChar *p = cs.c_str() + 3;
            if ( *p == wxT('-') )
                p++;

            unsigned int value;
            if ( wxSscanf(p, wxT("8859-%u"), &value) == 1 )
            {
                // make it 0 based and check that it is strictly positive in
                // the process (no such thing as iso8859-0 encoding)
                if ( (value-- > 0) &&
                     (value < wxFONTENCODING_ISO8859_MAX -
                              wxFONTENCODING_ISO8859_1) )
                {
                    // it's a valid ISO8859 encoding
                    value += wxFONTENCODING_ISO8859_1;
                    encoding = (wxFontEncoding)value;
                }
            }
        }
        else if ( cs.Left(4) == wxT("8859") )
        {
            const wxChar *p = cs.c_str();

            unsigned int value;
            if ( wxSscanf(p, wxT("8859-%u"), &value) == 1 )
            {
                // make it 0 based and check that it is strictly positive in
                // the process (no such thing as iso8859-0 encoding)
                if ( (value-- > 0) &&
                     (value < wxFONTENCODING_ISO8859_MAX -
                              wxFONTENCODING_ISO8859_1) )
                {
                    // it's a valid ISO8859 encoding
                    value += wxFONTENCODING_ISO8859_1;
                    encoding = (wxFontEncoding)value;
                }
            }
        }
        else // check for Windows charsets
        {
            size_t len;
            if ( cs.Left(7) == wxT("WINDOWS") )
            {
                len = 7;
            }
            else if ( cs.Left(2) == wxT("CP") )
            {
                len = 2;
            }
            else // not a Windows encoding
            {
                len = 0;
            }

            if ( len )
            {
                const wxChar *p = cs.c_str() + len;
                if ( *p == wxT('-') )
                    p++;

                unsigned int value;
                if ( wxSscanf(p, wxT("%u"), &value) == 1 )
                {
                    if ( value >= 1250 )
                    {
                        value -= 1250;
                        if ( value < wxFONTENCODING_CP12_MAX -
                                     wxFONTENCODING_CP1250 )
                        {
                            // a valid Windows code page
                            value += wxFONTENCODING_CP1250;
                            encoding = (wxFontEncoding)value;
                        }
                    }

                    switch ( value )
                    {
                        case 866:
                            encoding = wxFONTENCODING_CP866;
                            break;

                        case 874:
                            encoding = wxFONTENCODING_CP874;
                            break;

                        case 932:
                            encoding = wxFONTENCODING_CP932;
                            break;

                        case 936:
                            encoding = wxFONTENCODING_CP936;
                            break;

                        case 949:
                            encoding = wxFONTENCODING_CP949;
                            break;

                        case 950:
                            encoding = wxFONTENCODING_CP950;
                            break;
                    }
                }
            }
        }
        //else: unknown
    }

    return encoding;
}
bool wxMacPageMarginsDialog::CheckValue(wxTextCtrl* textCtrl, int *value, int minValue, const wxString& name)
  {
  long lvalue;
  if (!textCtrl->GetValue().ToLong(&lvalue))
    {
    wxMessageBox(wxString::Format(wxT("Sorry, \"%s\" is not a valid numerical value for the %s"), textCtrl->GetValue().c_str(), name.c_str()), wxT("Page Margin Error"));
    return false;
    }
  if (lvalue < minValue)
    {
    wxMessageBox(wxString::Format(wxT("Sorry, \"%s\" is not a valid value for the %s, which must be >= %d"), textCtrl->GetValue().c_str(), name.c_str(), minValue), wxT("Page Margin Error"));
    textCtrl->SetValue(wxString::Format(wxT("%d"), minValue));
    textCtrl->SetSelection(-1, -1);
    textCtrl->SetFocus();
    return false;
    }
  *value = int(lvalue);
  return true;
  }
Example #7
0
void cRawParser::ParseMatrix(const cXmlNode& node, MATRIX& m, const wxString& nodes) {
    m = matrixGetUnity();

    bool missrow[4] = {true, true, true, true};
    string temp;
    cXmlNode child(node.children());
    while(child) {
        if (child("row1")) {
            missrow[0] = false;
            temp = child.content();
            if (!parseMatrixRow(temp, m._11, m._12, m._13, m._14))
                throw MakeNodeException<RCT3InvalidValueException>(nodes+_(" tag, row1: invalid content: ")+temp, child);
        } else if (child("row2")) {
            missrow[1] = false;
            temp = child.content();
            if (!parseMatrixRow(temp, m._21, m._22, m._23, m._24))
                throw MakeNodeException<RCT3InvalidValueException>(nodes+_(" tag, row2: invalid content: ")+temp, child);
        } else if (child("row3")) {
            missrow[2] = false;
            temp = child.content();
            if (!parseMatrixRow(temp, m._31, m._32, m._33, m._34))
                throw MakeNodeException<RCT3InvalidValueException>(nodes+_(" tag, row3: invalid content: ")+temp, child);
        } else if (child("row4")) {
            missrow[3] = false;
            temp = child.content();
            if (!parseMatrixRow(temp, m._41, m._42, m._43, m._44))
                throw MakeNodeException<RCT3InvalidValueException>(nodes+_(" tag, row4: invalid content: ")+temp, child);
        } else if (child.is(XML_ELEMENT_NODE)) {
            throw MakeNodeException<RCT3Exception>(wxString::Format(_("Unknown tag '%s' in %s"), child.wxname().c_str(), nodes.c_str()), child);
        }
        child.go_next();
    }
    if (missrow[0] || missrow[1] || missrow[2] || missrow[3])
        throw MakeNodeException<RCT3Exception>(wxString::Format(_("Missing matrix row in %s"), nodes.c_str()), node);
}
wxString wxsCoderContext::GetUniqueName(const wxString& Prefix)
{
    wxString& MapEntry = m_Extra[_T("__Counter_of_") + Prefix];
    MapEntry.Append(_T('*'));
    return wxString::Format(_T("%s_%d"),Prefix.c_str(),(int)MapEntry.Length());
}
Example #9
0
bool GpxDocument::LoadFile(const wxString &filename)
{
      SeedRandom();
      wxRegEx re; //We try to fix popularily broken GPX files. Unencoded '&' is an illegal character in XML, but seems higly popular amongst users (and perhaps even vendors not aware of what XML is...)
      //The same as above is true for '<' but it would be harder to solve - it's illegal just inside a value, not when it starts a tag
      int re_compile_flags = wxRE_ICASE;
#ifdef wxHAS_REGEX_ADVANCED
      re_compile_flags |= wxRE_ADVANCED;
#endif
      bool b = re.Compile(wxT("&(?!amp;|lt;|gt;|apos;|quot;|#[0-9]{1,};|#x[0-f]{1,};)"), re_compile_flags); //Should find all the non-XML entites to be encoded as text
      wxFFile file(filename);
      wxString s;
      if(file.IsOpened()) {
            file.ReadAll(&s, wxConvUTF8);

            //Fallback for not-well formed (non-UTF8) GPX files
            //the "garbage" characters are lost, but the important part of the information should survive...
            if (s == wxEmptyString)
            {
                  file.Seek(0);
                  file.ReadAll(&s, wxConvISO8859_1);
                  wxLogMessage(wxString::Format(wxT("File %s seems not to be well-formed UTF-8 XML, used fallback ASCII format conversion - some text information might have not been imported."), filename.c_str()));
            }

            file.Close();
      }
      if(b)
      {
            //CDATA handling makes this task way too complex for regular expressions to handle,
            // so we do nothing and just let the possible damage happen...
            if (!s.Contains(wxT("![CDATA[")))
            {
                  int cnt = re.ReplaceAll(&s, wxT("&amp;"));
                  if (cnt > 0)
                        wxLogMessage(wxString::Format(wxT("File %s seems broken, %i occurences of '&' were replaced with '&amp;' to try to fix it."), filename.c_str(), cnt));
            }
      }
      wxFFile gpxfile;
      wxString gpxfilename = wxFileName::CreateTempFileName(wxT("gpx"), &gpxfile);
      gpxfile.Write(s);
      gpxfile.Close();
      bool res = TiXmlDocument::LoadFile((const char*)gpxfilename.mb_str());

	  if( ! res ) {
		  wxString msg = _T("Failed to load ");
		  msg << filename;
		  msg << _T(": ");
		  msg << wxString( TiXmlDocument::ErrorDesc(), wxConvUTF8 );
 		  wxLogMessage( msg );
	  }
      ::wxRemoveFile(gpxfilename);
      return res;
}
Example #10
0
void baz(const wxString& s)
{
    printf("baz: %s\n", (const char*)s.c_str());
}
///////////////////////////////
// Transform framerate in tags
void AssTransformFramerateFilter::TransformTimeTags (wxString name,int n,AssOverrideParameter *curParam,void *curData) {
	// Setup
	LineData *lineData = (LineData*) curData;
	AssDialogue *curDiag = lineData->line;;
	bool start = true;
	bool karaoke = false;
	int mult = 1;
	int value;
	switch (curParam->classification) {
		case PARCLASS_RELATIVE_TIME_START:
			start = true;
			mult = 1;
			break;
		case PARCLASS_RELATIVE_TIME_END:
			start = false;
			mult = 1;
			break;
		case PARCLASS_KARAOKE:
			karaoke = true;
			start = true;
			mult = 10;
			break;
		default:
			return;
	}

	// Parameter value
	int parVal = curParam->AsInt() * mult;

	// Karaoke preprocess
	int curKarPos = 0;
	if (karaoke) {
		if (name == _T("\\k")) {
			curKarPos = lineData->k;
			lineData->k += parVal/10;
		}
		else if (name == _T("\\K") || name == _T("\\kf")) {
			curKarPos = lineData->kf;
			lineData->kf += parVal/10;
		}
		else if (name == _T("\\ko")) {
			curKarPos = lineData->ko;
			lineData->ko += parVal/10;
		}
		else throw wxString::Format(_T("Unknown karaoke tag! '%s'"), name.c_str());
		curKarPos *= 10;
		parVal += curKarPos;
	}

	// Start time
	if (start) {
		int newStart = instance.Input->GetTimeAtFrame(instance.Output->GetFrameAtTime(curDiag->Start.GetMS()));
		int absTime = curDiag->Start.GetMS() + parVal;
		value = instance.Input->GetTimeAtFrame(instance.Output->GetFrameAtTime(absTime)) - newStart;
	}

	// End time
	else {
		int newEnd = instance.Input->GetTimeAtFrame(instance.Output->GetFrameAtTime(curDiag->End.GetMS()));
		int absTime = curDiag->End.GetMS() - parVal;
		value = newEnd - instance.Input->GetTimeAtFrame(instance.Output->GetFrameAtTime(absTime));
	}

	// Karaoke postprocess
	if (karaoke) {
		int post = instance.Input->GetTimeAtFrame(instance.Output->GetFrameAtTime(curDiag->Start.GetMS() + curKarPos));
		int start = instance.Input->GetTimeAtFrame(instance.Output->GetFrameAtTime(curDiag->Start.GetMS()));
		curKarPos = post-start;
		value -= curKarPos;
	}

	curParam->SetInt(value/mult);
}
Example #12
0
void wxSheetCellFloatRendererRefData::SetParameters(const wxString& params)
{
    if ( params.IsEmpty() )
    {
        // reset to defaults
        SetWidth(-1);
        SetPrecision(-1);
    }
    else
    {
        wxString tmp( params.BeforeFirst(_T(',')) );
        if ( !tmp.IsEmpty() )
        {
            long width;
            if ( tmp.ToLong(&width) )
                SetWidth((int)width);
            else
                wxLogDebug(_T("Invalid wxSheetCellFloatRenderer width parameter string '%s ignored"), params.c_str());
        }
        tmp = params.AfterFirst(_T(','));
        if ( !tmp.IsEmpty() )
        {
            long precision;
            if ( tmp.ToLong(&precision) )
                SetPrecision((int)precision);
            else
                wxLogDebug(_T("Invalid wxSheetCellFloatRenderer precision parameter string '%s ignored"), params.c_str());
        }
    }
}
Example #13
0
void GutterCtrl::DrawGutter(wxDC& dc) {
	//if (!m_editorCtrl) return; // We can be called before editorCtrl is valid
	Lines& lines = m_editorCtrl.m_lines;

	const wxSize size = GetClientSize();
	m_mdc.Clear();

	const unsigned int bg_xpos = m_gutterLeft ? size.x-1 : 0;
	const unsigned int edge_xpos = m_gutterLeft ? size.x-2 : 1;

	// Draw the edge
	m_mdc.SetPen(m_theme.backgroundColor);
	m_mdc.DrawLine(bg_xpos, 0, bg_xpos, size.y);
	m_mdc.SetPen(m_edgecolor);
	m_mdc.DrawLine(edge_xpos, 0, edge_xpos, size.y);

	// Draw the line numbers
	m_mdc.SetTextForeground(m_numbercolor);
	wxString number;
	const int scrollPos = m_editorCtrl.scrollPos;

	const unsigned int firstline = lines.GetLineFromYPos(scrollPos);
	const unsigned int linecount = lines.GetLineCount();

	// Prepare for foldings
	const vector<EditorCtrl::cxFold>& folds = m_editorCtrl.GetFolds();
	vector<EditorCtrl::cxFold>::const_iterator nextFold = folds.begin();
	const unsigned int line_middle = lines.GetLineHeight() / 2;
	vector<const EditorCtrl::cxFold*> foldStack;
	if (m_showFolds) {
		m_editorCtrl.UpdateFolds();

#ifdef __WXDEBUG__
		bool debug = false;
		if (debug) {
			for (vector<EditorCtrl::cxFold>::const_iterator f = folds.begin(); f != folds.end(); ++f) {
				const wxString indent(wxT('.'), f->indent);
				wxLogDebug(wxT("%d: %s%d"), f->line_id, indent.c_str(), f->type);
			}
		}
#endif

		for (nextFold = folds.begin(); nextFold != folds.end() && nextFold->line_id < firstline; ++nextFold) {
			if (nextFold->type == EditorCtrl::cxFOLD_END) {
				// check if end marker matches any starter on the stack
				for (vector<const EditorCtrl::cxFold*>::reverse_iterator p = foldStack.rbegin(); p != foldStack.rend(); ++p) {
					if ((*p)->indent == nextFold->indent) {
						foldStack.erase(p.base()-1, foldStack.end()); // pop
						break;
					}
				}
			}
			else {
				foldStack.push_back(&*nextFold);
			}
		}
	}

	// Prepare for bookmarks
	const vector<cxBookmark>& bookmarks = m_editorCtrl.GetBookmarks();
	vector<cxBookmark>::const_iterator nextBookmark = bookmarks.begin();
	while(nextBookmark != bookmarks.end() && nextBookmark->line_id < firstline) ++nextBookmark;

	// Draw each line
	for (unsigned int i = firstline; i < linecount; ++i) {
		number.Printf(wxT("%*u"), m_max_digits, i+1);
		const int ypos = lines.GetYPosFromLine(i) - scrollPos;
		if (ypos > size.y) break;

		// Highlight selections
		if (m_currentSel != -1 &&
			((i >= m_sel_startline && i <= m_sel_endline) ||
			 (i >= m_sel_endline && i <= m_sel_startline))) {

			const int ypos2 = lines.GetBottomYPosFromLine(i) - scrollPos;
			m_mdc.SetPen(m_hlightcolor);
			m_mdc.SetBrush(wxBrush(m_hlightcolor, wxSOLID));
			m_mdc.DrawRectangle(0, ypos, size.x-2, ypos2-ypos);
		}

		// Draw bookmark
		if (m_showBookmarks && nextBookmark != bookmarks.end() && nextBookmark->line_id == i) {
			//m_mdc.DrawText(wxT("\u066D"), 3, ypos);
			m_mdc.DrawBitmap(m_bmBookmark, 2, ypos + line_middle - 5);
			++nextBookmark;
		}

		// Draw the line number
		m_mdc.DrawText(number, m_numberX, ypos);

		// Draw fold markers
		if (m_showFolds) {
			bool drawFoldLine = (!foldStack.empty());

			if (nextFold != folds.end() && nextFold->line_id == i) {
				if (nextFold->type == EditorCtrl::cxFOLD_START) {
					const int ypos2 = lines.GetBottomYPosFromLine(i) - scrollPos;
					const unsigned int box_y = ypos + line_middle - 5;
					m_mdc.DrawBitmap(m_bmFoldOpen, m_foldStartX, box_y);

					if (&*nextFold == m_currentFold) m_mdc.SetPen(wxPen(m_edgecolor, 2));
					else m_mdc.SetPen(m_edgecolor);
					m_mdc.DrawLine(m_foldStartX+4, box_y+9, m_foldStartX+4, ypos2);

					foldStack.push_back(&*nextFold);
					drawFoldLine = false;
					++nextFold;
				}
				else if (nextFold->type == EditorCtrl::cxFOLD_START_FOLDED) {
					const unsigned int box_y = ypos + line_middle - 5;
					m_mdc.DrawBitmap(m_bmFoldClosed, m_foldStartX, box_y);
					drawFoldLine = false;

					// Advance to end of fold
					i += nextFold->count;
					while (nextFold != folds.end() && nextFold->line_id <= i) ++nextFold;
				}
				else if (nextFold->type == EditorCtrl::cxFOLD_END) {
					if (!foldStack.empty()) {
						// check if end marker matches any starter on the stack (ignore unmatched)
						for (vector<const EditorCtrl::cxFold*>::reverse_iterator f = foldStack.rbegin(); f != foldStack.rend(); ++f) {
							if (nextFold->indent == (*f)->indent) {
								vector<const EditorCtrl::cxFold*>::iterator fb = (++f).base();

								// Check if we should highlight fold line
								if (*fb == m_currentFold) m_mdc.SetPen(wxPen(m_edgecolor, 2));
								else m_mdc.SetPen(m_edgecolor);

								// If we are closing other folds, we want to leave a gap
								const unsigned int ytop = (fb < foldStack.end()-1) ? ypos + 2 : ypos;

								// Draw end marker
								const unsigned int middle_y = ypos + line_middle+1;
								m_mdc.DrawLine(m_foldStartX+4, ytop, m_foldStartX+4, middle_y);
								m_mdc.DrawLine(m_foldStartX+4, middle_y, m_foldStartX+9, middle_y);

								foldStack.erase(fb, foldStack.end()); // pop
								drawFoldLine = false;
								break;
							}
						}
					}
					++nextFold;
				}

			}

			if (drawFoldLine) {
				const int ypos2 = lines.GetBottomYPosFromLine(i) - scrollPos;

				// Check if we should highlight fold line
				if (!foldStack.empty() && foldStack.back() == m_currentFold) {
					m_mdc.SetPen(wxPen(m_edgecolor, 2));
				}
				else m_mdc.SetPen(m_edgecolor);

				m_mdc.DrawLine(m_foldStartX+4, ypos, m_foldStartX+4, ypos2);
			}
		}
	}

	// Copy MemoryDC to Display
#ifdef __WXMSW__
	::BitBlt(GetHdcOf(dc), 0, 0,(int)size.x, (int)size.y, GetHdcOf(m_mdc), 0, 0, SRCCOPY);
#else
	dc.Blit(0, 0, size.x, size.y, &m_mdc, 0, 0);
#endif
}
Example #14
0
void wxsCoder::FlushFile(const wxString& FileName)
{
    int Index = CodeChangesFiles.Index(FileName);
    if ( Index == wxNOT_FOUND ) return;

    CodeChange* Changes = CodeChanges[Index];
    if ( !Changes ) return;

    // Searching for file in opened file list
	EditorManager* EM = Manager::Get()->GetEditorManager();
	assert ( EM != 0 );
    cbEditor* Editor = EM->GetBuiltinEditor(FileName);

    if ( Editor )
    {
        wxString EOL;
        while ( Changes )
        {
            CodeChange* Next = Changes->Next;
            ApplyChangesEditor(Editor,Changes->Header,Changes->End,Changes->Code,Changes->CodeHasHeader,Changes->CodeHasEnd,EOL);
            delete Changes;
            Changes = Next;
        }
    }
    else
    {
        // Reading file content
        wxString EOL;
        bool HasChanged = false;

        //wxStopWatch SW;
        EncodingDetector Detector(FileName);
        if ( !Detector.IsOK() )
        {
            #if wxCHECK_VERSION(2, 9, 0)
            Manager::Get()->GetLogManager()->Log(F(_("wxSmith: Couldn't open and properly read file '%s'"),FileName.wx_str()));
            #else
            Manager::Get()->GetLogManager()->Log(F(_("wxSmith: Couldn't open and properly read file '%s'"),FileName.c_str()));
            #endif
            return;
        }
        //Manager::Get()->GetLogManager()->DebugLog(F(_T("File read time: %d ms"),SW.Time()));

        wxString Content = Detector.GetWxStr();
        while ( Changes )
        {
            CodeChange* Next = Changes->Next;
            ApplyChangesString(Content,Changes->Header,Changes->End,Changes->Code,Changes->CodeHasHeader,Changes->CodeHasEnd,HasChanged,EOL);
            delete Changes;
            Changes = Next;
        }

        if ( HasChanged )
        {
            // Storing the result
            //wxStopWatch SW;
            if ( !cbSaveToFile(FileName,Content,Detector.GetFontEncoding(),Detector.GetBOMSizeInBytes()>0) )
            {
                #if wxCHECK_VERSION(2, 9, 0)
                Manager::Get()->GetLogManager()->Log(F(_("wxSmith: Couldn't write data to file '%s'"),FileName.wx_str()));
                #else
                Manager::Get()->GetLogManager()->Log(F(_("wxSmith: Couldn't write data to file '%s'"),FileName.c_str()));
                #endif
            }
            else
            {
                CodeBlocksEvent event(cbEVT_PROJECT_FILE_CHANGED);
                event.SetString(FileName);
                Manager::Get()->GetPluginManager()->NotifyPlugins(event);
            }
            //Manager::Get()->GetLogManager()->DebugLog(F(_T("File write time: %d ms"),SW.Time()));
        }
    }

    CodeChanges[Index] = 0;
}
Example #15
0
void SearchThread::DoSearchLineRE(const wxString &line, const int lineNum, const int lineOffset, const wxString &fileName, const SearchData *data, TextStatesPtr statesPtr)
{
    wxRegEx &re = GetRegex(data->GetFindString(), data->IsMatchCase());
    size_t col = 0;
    int iCorrectedCol = 0;
    int iCorrectedLen = 0;
    wxString modLine = line;
    if ( re.IsValid() ) {
        while ( re.Matches(modLine)) {
            size_t start, len;
            re.GetMatch(&start, &len);
            col += start;

            // Notify our match
            // correct search Pos and Length owing to non plain ASCII multibyte characters
            iCorrectedCol = clUTF8Length(line.c_str(), col);
            iCorrectedLen = clUTF8Length(line.c_str(), col+len) - iCorrectedCol;
            SearchResult result;
            result.SetPosition(lineOffset + col);
            result.SetColumnInChars((int)col);
            result.SetColumn(iCorrectedCol);
            result.SetLineNumber(lineNum);
            result.SetPattern(line);
            result.SetFileName(fileName);
            result.SetLenInChars((int)len);
            result.SetLen(iCorrectedLen);
            result.SetFlags(data->m_flags);
            result.SetFindWhat(data->GetFindString());

            // Make sure our match is not on a comment
            int  position(wxNOT_FOUND);
            bool canAdd(true);

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

            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);
            }

            col += len;

            // adjust the line
            if (line.Length() - col <= 0)
                break;
            modLine = modLine.Right(line.Length() - col);
        }
    }
}
Example #16
0
void wxGridCellPathEditor::SetParameters(const wxString& params)
{
    if ( !params )
    {
        // reset to default
        m_maxChars = 0;
    }
    else
    {
        long tmp;
        if ( !params.ToLong(&tmp) )
        {
            wxLogDebug(_T("Invalid wxGridCellPathEditor parameter string '%s' ignored"), params.c_str());
        }
        else
        {
            m_maxChars = (size_t)tmp;
        }
    }
}
Example #17
0
void SearchThread::DoSearchLine(const wxString &line, const int lineNum, const int lineOffset, const wxString &fileName, const SearchData *data, TextStatesPtr statesPtr)
{
    wxString findString = data->GetFindString();
    wxString modLine = line;

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

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

            // 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, findString) ) {

                        break;
                    } else {
                        col += (int) findString.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 + findString.Length() <= modLine.Length()) {
                    wxChar nextCh = modLine.GetChar(pos+findString.Length());
                    if (m_wordCharsMap.find(nextCh) != m_wordCharsMap.end()) {
                        if( !AdjustLine(modLine, pos, findString) ) {

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

            // Notify our match
            // correct search Pos and Length owing to non plain ASCII multibyte characters
            iCorrectedCol = clUTF8Length(line.c_str(), col);
            iCorrectedLen = clUTF8Length(findString.c_str(), findString.Length());
            SearchResult result;
            result.SetPosition(lineOffset + col);
            result.SetColumnInChars(col);
            result.SetColumn(iCorrectedCol);
            result.SetLineNumber(lineNum);
            result.SetPattern(line);
            result.SetFileName(fileName);
            result.SetLenInChars((int)findString.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, findString) ) {
                break;
            }
            col += (int)findString.Length();
        }
    }
}
Example #18
0
////////////////////////////////////////////////////////////////////////////////////////////
/// \return     a wxString which will contain the error message for any error occuring, 
///             otherwise a null string is returned
/// \param      tablePathName   -> the path to the consistent changes (.cct) file to be loaded
/// \remarks
/// Called from: The App's OnToolsDefineCC() menu event handler.
/// The loadTableFromFile() function calls ccModule->CCLoadTable() and 
/// ccModule->CCSetUTF8Encoding() to make the consistent changes facilities available to the
/// application.
////////////////////////////////////////////////////////////////////////////////////////////
wxString CConsistentChanger::loadTableFromFile(wxString tablePathName) // caller supplies a CString, so LPCTSTR needed here
{
	// The wx version of loadTableFromFile returns any error as a formatted error string to the caller.
	//---- LOAD THE CC TABLE INTO THE BUFFER
	// wx version: we can't use MFC specific functions; so we'll just try to open the file for reading
	// and consider it an error if f.Open() returns false.
	wxFile f;
	if (!f.Open(tablePathName,wxFile::read))
	{
		ccErrorStr = ccErrorStr.Format(_("The CC-Table \"%s\" could not be found or opened.\n"), tablePathName.c_str());
		return ccErrorStr;	
	}
	else
	{
		f.Close();
	}

	// BEW 15Oct07, a long path will crash the CCLoadTable() call, so I've built a function to copy the table
	// data to a temporary "_tbl_.cct" file at the CSIDL_PERSONAL folder, which is the My Documents folder or
	// the Documents folder in Vista, and I'll have subsequent code below access that instead, and removing the
	// temporary file when done. The effect of this is that the CC32.DLL never accesses a cct file buried so
	// deep in the folder hierachy that the DLL code fails due to its small internal buffer for the path
	wxString pathToPersonalFolder = CopyTableToPersonalFolder(tablePathName);
	wxString lpPath = pathToPersonalFolder; // use this one below, not tablePathName

	// we don't expect the table file copy to the personal folder to fail, but check for it just in case and if it
	// did (the returned pathInRoot wxString will be empty) then tell the user and abort the load operation
	if (pathToPersonalFolder.IsEmpty())
	{
		// for some reason the CopyTableToPersonalFolder() function failed, a hard coded English message will suffice
		wxString aPath = tablePathName;
		wxString s;
		s = s.Format(_T("Relocating the CC table file in loadTableFromFile failed, so cc processing is disabled; original table's path was: %s"),aPath.c_str());
		wxMessageBox(s,_T(""), wxICON_EXCLAMATION | wxOK);
		return s ; // MFC note: we really need to return BOOL -- add this change later
	}

	int iResult2;
	int iResult;

#ifdef _UNICODE

	// whm: one method of conversion is to use the .mb_str() method of wxString as illustrated in the
	// two commented out lines below:
	//wxCharBuffer tempBuff = lpPath.mb_str(wxConvUTF8);
	//CBString psz(tempBuff);
	// whm: an easier method of conversion is just to use the wxString constructor with wxConvUTF8 conversion parameter
	// whm 8Jun12 modified. The lpPath is already a wxString, so it doesn't need any further conversion with wxConvUTF8
	iResult = ccModule->CCLoadTable(lpPath);

	// make the environment enabled for UTF-8 support
	iResult2 = ccModule->CCSetUTF8Encoding(TRUE);

#else // ANSI

	iResult = ccModule->CCLoadTable(lpPath);

	// make the environment disabled for UTF-8 support
	iResult2 = ccModule->CCSetUTF8Encoding(FALSE);

#endif

	// get rid of the temporary file _tbt_.cct in the data folder
	if (!::wxRemoveFile(lpPath))
	{
		wxString aPath = tablePathName;
		wxString s;
		s = s.Format(_T("CopyTableToPersonalFolder() failed to remove the temporary file for path %s (so remove it manually using Win Explorer)"),aPath.c_str());
		wxMessageBox(s,_T(""), wxICON_EXCLAMATION | wxOK);
	}

	if(iResult)
	{
		// Instead of throwing Exceptions, the wx version of loadTableFromFile() returns the error result
		// returned by the CC function.
		ccErrorStr = ccErrorStr.Format(_("CC couldn't load the table: %s.  Got error code: %d.  Check the syntax of the table."),
							tablePathName.c_str(), iResult);
		return ccErrorStr; //throw ccErrorStr;
	}

	if(iResult2)
	{
		ccErrorStr = ccErrorStr.Format(_("CC environment did not accept CCSetUTR8Encoding() call: Got error code: %d."), 
							 iResult2);
		return ccErrorStr; //throw ccErrorStr;
	}

	// if we get here all was successful and ccErrorStr should still be empty
	return ccErrorStr;
}
Example #19
0
unsigned long cRawParser::HandleUnsignedContent(const wxString& content, const cXmlNode& node, const wxString& nodes, const wxString& attribute) {
    wxString t(content);
    MakeVariable(t);
    unsigned long i;
    if (t.IsEmpty()) {
		if (attribute.IsEmpty())
			throw MakeNodeException<RCT3Exception>(wxString::Format(_("Tag '%s' misses content"), nodes.c_str()), node);
		else
			throw MakeNodeException<RCT3Exception>(wxString::Format(_("Tag '%s' misses attribute '%s'"), nodes.c_str(), attribute.c_str()), node);
	}

    if (t.StartsWith('b')) {
        try {
            bitset<32> bits(string(t.utf8_str()), 1);
            i = bits.to_ulong();
        } catch (exception& e) {
			if (attribute.IsEmpty())
				throw MakeNodeException<RCT3Exception>(wxString::Format(_("Tag '%s': invalid binary content '%s'"), nodes.c_str(), t.c_str()), node);
			else
				throw MakeNodeException<RCT3Exception>(wxString::Format(_("Tag '%s', '%s': invalid binary content '%s'"), nodes.c_str(), attribute.c_str(), t.c_str()), node);
        }
    } else if (t.StartsWith('h') || t.StartsWith("0x")) {
        wxString hex;
        if (!t.StartsWith('h', &hex))
            t.StartsWith("0x", &hex);
        if (!parseHexULong(hex, i)) {
			if (attribute.IsEmpty())
				throw MakeNodeException<RCT3Exception>(wxString::Format(_("Tag '%s': invalid hex content '%s'"), nodes.c_str(), t.c_str()), node);
			else
				throw MakeNodeException<RCT3Exception>(wxString::Format(_("Tag '%s', '%s': invalid hex content '%s'"), nodes.c_str(), attribute.c_str(), t.c_str()), node);
		}
    } else if (t == "true") {
        i = 1;
    } else if (t == "false") {
        i = 0;
    } else if (!t.ToULong(&i)) {
		if (attribute.IsEmpty())
			throw MakeNodeException<RCT3Exception>(wxString::Format(_("Tag '%s': invalid value '%s'"), nodes.c_str(), t.c_str()), node);
		else
			throw MakeNodeException<RCT3Exception>(wxString::Format(_("Tag '%s', '%s': invalid value '%s'"), nodes.c_str(), attribute.c_str(), t.c_str()), node);
	}
    return i;
}
Example #20
0
wxString wxLuaFreezeApp::LoadScript(const wxString& filename, bool only_check)
{
    // lots of debugging to make sure that everything is ok
    wxFile f;

    if (!f.Open(filename, wxFile::read))
    {
        OutputPrint(wxString::Format(wxT("Unable to open this executable file '%s' in read-only mode.\n"), filename.c_str()));
        return wxEmptyString;
    }

    // end of file is : "<wxLuaFreeze:%010d>", script_len
    #define END_TAG_LEN 24

    if (f.Seek(-END_TAG_LEN, wxFromEnd) == wxInvalidOffset)
    {
        f.Close();
        OutputPrint(wxString::Format(wxT("Unable to seek to last %d bytes at end of '%s'.\n"), END_TAG_LEN, filename.c_str()));
        return wxEmptyString;
    }

    // do some sanity checking before reading the script length

    char tag_buf[END_TAG_LEN+2] = {0};
    memset(tag_buf, 0, sizeof(char)*(END_TAG_LEN+2));
    long script_len = 0;

    if (f.Read((void*)tag_buf, END_TAG_LEN) == wxInvalidOffset)
    {
        f.Close();
        OutputPrint(wxString::Format(wxT("Unable to read wxLuaFreeze tag info at end of '%s'.\n"), filename.c_str()));
        return wxEmptyString;
    }

    if (sscanf(tag_buf, "<wxLuaFreeze:%ld>", &script_len) != 1)
    {
        f.Close();

        // they only wanted to know if the script exists, assume it's valid
        if (only_check)
            return LOADSCRIPT_MISSING;

        OutputPrint(wxString::Format(wxT("Expecting '<wxLuaFreeze:[script length]>' at end of '%s'.\n")
                                     wxT("Did you forget to run wxluafreeze.lua to attach your script?\n"), filename.c_str()));
        return wxEmptyString;
    }
    else if (f.Seek(-END_TAG_LEN - script_len, wxFromEnd) == wxInvalidOffset)
    {
        f.Close();
        OutputPrint(wxString::Format(wxT("Unable to seek to beginning of wxLua script at end of '%s'.\n"), filename.c_str()));
        return wxEmptyString;
    }

    // size should be valid from Seek statement
    char *script = (char*)malloc(script_len+2);
    if (script)
    {
        memset(script, 0, sizeof(script_len+2));
        f.Read(script, script_len);
        script[script_len] = 0;
    }

    f.Close();

    // we finally have our script!
    wxString scriptStr(lua2wx(script));
    free(script);

    return scriptStr;
}
Example #21
0
c3DLoaderOrientation cRawParser::ParseOrientation(const cXmlNode& node, const wxString& nodes, c3DLoaderOrientation defori) {
    c3DLoaderOrientation ori = defori;
    wxString hand = node.wxgetPropVal("handedness");
    wxString up = node.wxgetPropVal("up");
    if (hand.IsEmpty()) {
        if (!up.IsEmpty()) {
            throw MakeNodeException<RCT3Exception>(wxString::Format(_("Hand attribute missing in %s"), up.c_str(), nodes.c_str()), node);
        }
        // Fall through to default
    } else if (hand == wxT("left")) {
        if (up.IsEmpty()) {
            throw MakeNodeException<RCT3Exception>(wxString::Format(_("Up attribute missing in %s"), up.c_str(), nodes.c_str()), node);
        } else if (up == wxT("x")) {
            ori = ORIENTATION_LEFT_XUP;
        } else if (up == wxT("y")) {
            ori = ORIENTATION_LEFT_YUP;
        } else if (up == wxT("z")) {
            ori = ORIENTATION_LEFT_ZUP;
        } else {
            throw MakeNodeException<RCT3Exception>(wxString::Format(_("Unknown value '%s' for up attribute in %s"), up.c_str(), nodes.c_str()), node);
        }
    } else if (hand == wxT("right")) {
        if (up.IsEmpty()) {
            throw MakeNodeException<RCT3Exception>(wxString::Format(_("Up attribute missing in %s"), up.c_str(), nodes.c_str()), node);
        } else if (up == wxT("x")) {
            ori = ORIENTATION_RIGHT_XUP;
        } else if (up == wxT("y")) {
            ori = ORIENTATION_RIGHT_YUP;
        } else if (up == wxT("z")) {
            ori = ORIENTATION_RIGHT_ZUP;
        } else {
            throw MakeNodeException<RCT3Exception>(wxString::Format(_("Unknown value '%s' for up attribute in %s"), up.c_str(), nodes.c_str()), node);
        }
    } else {
        throw MakeNodeException<RCT3Exception>(wxString::Format(_("Unknown value '%s' for handedness attribute in %s"), up.c_str(), nodes.c_str()), node);
    }
    return ori;
}
Example #22
0
bool wxLuaFreezeApp::OnInit()
{
#ifdef __WXGTK__
    // this call is very important since otherwise scripts using the decimal
    // point '.' could not work with those locales which use a different symbol
    // (e.g. the comma) for the decimal point...
    // It doesn't work to put os.setlocale('c', 'numeric') in the Lua file that
    // you want to use decimal points in. That's because the file has been lexed
    // and compiler before the locale has changed, so the lexer - the part that
    // recognizes numbers - will use the old locale.
    setlocale(LC_NUMERIC, "C");
#endif

    // load all image handlers for the wxLua script to make things easy
    wxInitAllImageHandlers();

    // Initialize the wxLua bindings we want to use.
    // See notes for WXLUA_DECLARE_BIND_ALL above.
    WXLUA_IMPLEMENT_BIND_ALL

    // Find the full path this this executable
    wxFileName appFile = wxFindAppFullName(argv[0], wxGetCwd(), wxEmptyString);

    if (appFile.FileExists() == false)
    {
        m_fileName = argv[0]; // the filename of 'this' program
        //OutputPrint(wxString::Format(wxT("Unable to find the path for '%s'\n"), argv[0]));
    }
    else
        m_fileName = appFile.GetFullPath();


    // When this function returns wxApp:MainLoop() will be called by wxWidgets
    // and so we want the Lua code wx.wxGetApp:MainLoop() to not
    // prematurely start it.
    wxLuaState::sm_wxAppMainLoop_will_run = true;

    m_wxlState = wxLuaState(this, wxID_ANY);
    if (!m_wxlState.Ok())
        return false;

    // if no script attached try to run the program on the command line
    if (LoadScript(m_fileName, true) == LOADSCRIPT_MISSING)
    {
        if (argc > 1)
        {
            wxlua_pushargs(m_wxlState.GetLuaState(), argv, argc, 1);
            // just run it, lua gives a nice error message on failure
            m_wxlState.RunFile(argv[1]);
        }
        else
        {
            OutputPrint(wxString::Format(wxT("Expecting '<wxLuaFreeze:[script length]>' at end of '%s'.\n")
                                         wxT("Did you forget to run wxluafreeze.lua to attach your script?\n")
                                         wxT("You may also run wxLua programs by specifying them on the command line."),
                                         m_fileName.c_str()));
        }
    }
    else
    {
        // now load our script to run that should have been appended to this file
        //  by wxluafreeze.lua
        wxString script = LoadScript(m_fileName);
        if (!script.IsEmpty())
        {
            wxlua_pushargs(m_wxlState.GetLuaState(), argv, argc, 0);
            m_wxlState.RunString(script);
        }
    }

    // no matter what - try to see any toplevel windows exist, if not then
    // there's no way to exit so assume that the program is all done
    wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
    if (node)
        return true;

    return false;
}
Example #23
0
static inline
wxString FormatAsHex(const wxString& value, wxRegKey::ValueType type)
{
    return FormatAsHex(value.c_str(), value.length() + 1, type);
}
Example #24
0
wxString wxExpandEnvVars(const wxString& str)
{
  wxString strResult;
  strResult.Alloc(str.length());

  size_t m;
  for ( size_t n = 0; n < str.length(); n++ ) {
    switch ( str[n].GetValue() ) {
#ifdef  __WXMSW__
      case wxT('%'):
#endif  //WINDOWS
      case wxT('$'):
        {
          Bracket bracket;
          #ifdef  __WXMSW__
            if ( str[n] == wxT('%') )
              bracket = Bracket_Windows;
            else
          #endif  //WINDOWS
          if ( n == str.length() - 1 ) {
            bracket = Bracket_None;
          }
          else {
            switch ( str[n + 1].GetValue() ) {
              case wxT('('):
                bracket = Bracket_Normal;
                n++;                   // skip the bracket
                break;

              case wxT('{'):
                bracket = Bracket_Curly;
                n++;                   // skip the bracket
                break;

              default:
                bracket = Bracket_None;
            }
          }

          m = n + 1;

          while ( m < str.length() && (wxIsalnum(str[m]) || str[m] == wxT('_')) )
            m++;

          wxString strVarName(str.c_str() + n + 1, m - n - 1);

#ifdef __WXWINCE__
          const bool expanded = false;
#else
          // NB: use wxGetEnv instead of wxGetenv as otherwise variables
          //     set through wxSetEnv may not be read correctly!
          bool expanded = false;
          wxString tmp;
          if (wxGetEnv(strVarName, &tmp))
          {
              strResult += tmp;
              expanded = true;
          }
          else
#endif
          {
            // variable doesn't exist => don't change anything
            #ifdef  __WXMSW__
              if ( bracket != Bracket_Windows )
            #endif
                if ( bracket != Bracket_None )
                  strResult << str[n - 1];
            strResult << str[n] << strVarName;
          }

          // check the closing bracket
          if ( bracket != Bracket_None ) {
            if ( m == str.length() || str[m] != (wxChar)bracket ) {
              // under MSW it's common to have '%' characters in the registry
              // and it's annoying to have warnings about them each time, so
              // ignroe them silently if they are not used for env vars
              //
              // under Unix, OTOH, this warning could be useful for the user to
              // understand why isn't the variable expanded as intended
              #ifndef __WXMSW__
                wxLogWarning(_("Environment variables expansion failed: missing '%c' at position %u in '%s'."),
                             (char)bracket, (unsigned int) (m + 1), str.c_str());
              #endif // __WXMSW__
            }
            else {
              // skip closing bracket unless the variables wasn't expanded
              if ( !expanded )
                strResult << (wxChar)bracket;
              m++;
            }
          }

          n = m - 1;  // skip variable name
        }
        break;

      case wxT('\\'):
        // backslash can be used to suppress special meaning of % and $
        if ( n != str.length() - 1 &&
                (str[n + 1] == wxT('%') || str[n + 1] == wxT('$')) ) {
          strResult += str[++n];

          break;
        }
        //else: fall through

      default:
        strResult += str[n];
    }
  }

  return strResult;
}
Example #25
0
bool wxFileDialogBase::Create(wxWindow *parent,
                              const wxString& message,
                              const wxString& defaultDir,
                              const wxString& defaultFile,
                              const wxString& wildCard,
                              long style,
                              const wxPoint& WXUNUSED(pos),
                              const wxSize& WXUNUSED(sz),
                              const wxString& WXUNUSED(name))
{
    m_message = message;
    m_dir = defaultDir;
    m_fileName = defaultFile;
    m_wildCard = wildCard;

    m_parent = parent;
    m_windowStyle = style;
    m_filterIndex = 0;

    if (!HasFdFlag(wxFD_OPEN) && !HasFdFlag(wxFD_SAVE))
        m_windowStyle |= wxFD_OPEN;     // wxFD_OPEN is the default

    // check that the styles are not contradictory
    wxASSERT_MSG( !(HasFdFlag(wxFD_SAVE) && HasFdFlag(wxFD_OPEN)),
                  _T("can't specify both wxFD_SAVE and wxFD_OPEN at once") );

    wxASSERT_MSG( !HasFdFlag(wxFD_SAVE) ||
                    (!HasFdFlag(wxFD_MULTIPLE) && !HasFdFlag(wxFD_FILE_MUST_EXIST)),
                   _T("wxFD_MULTIPLE or wxFD_FILE_MUST_EXIST can't be used with wxFD_SAVE" ) );

    wxASSERT_MSG( !HasFdFlag(wxFD_OPEN) || !HasFdFlag(wxFD_OVERWRITE_PROMPT),
                  _T("wxFD_OVERWRITE_PROMPT can't be used with wxFD_OPEN") );

    if ( wildCard.empty() || wildCard == wxFileSelectorDefaultWildcardStr )
    {
        m_wildCard = wxString::Format(_("All files (%s)|%s"),
                                      wxFileSelectorDefaultWildcardStr,
                                      wxFileSelectorDefaultWildcardStr);
    }
    else // have wild card
    {
        // convert m_wildCard from "*.bar" to "bar files (*.bar)|*.bar"
        if ( m_wildCard.Find(wxT('|')) == wxNOT_FOUND )
        {
            wxString::size_type nDot = m_wildCard.find(_T("*."));
            if ( nDot != wxString::npos )
                nDot++;
            else
                nDot = 0;

            m_wildCard = wxString::Format
                         (
                            _("%s files (%s)|%s"),
                            wildCard.c_str() + nDot,
                            wildCard.c_str(),
                            wildCard.c_str()
                         );
        }
    }

    return true;
}
Example #26
0
// Read a XDG *.desktop file of type 'Application'
void wxMimeTypesManagerImpl::LoadXDGApp(const wxString& filename)
{
    wxLogTrace(TRACE_MIME, wxT("loading XDG file %s"), filename.c_str());

    wxMimeTextFile file(filename);
    if ( !file.Open() )
        return;

    // Here, only type 'Application' should be considered.
    int nIndex = file.pIndexOf( "Type=" );
    if (nIndex != wxNOT_FOUND && file.GetCmd(nIndex) != "application")
        return;

    // The hidden entry specifies a file to be ignored.
    nIndex = file.pIndexOf( "Hidden=" );
    if (nIndex != wxNOT_FOUND && file.GetCmd(nIndex) == "true")
        return;

    // Semicolon separated list of mime types handled by the application.
    nIndex = file.pIndexOf( wxT("MimeType=") );
    if (nIndex == wxNOT_FOUND)
        return;
    wxString mimetypes = file.GetCmd (nIndex);

    // Name of the application
    wxString nameapp;
    nIndex = wxNOT_FOUND;
#if wxUSE_INTL // try "Name[locale name]" first
    wxLocale *locale = wxGetLocale();
    if ( locale )
        nIndex = file.pIndexOf(wxT("Name[")+locale->GetName()+wxT("]="));
#endif // wxUSE_INTL
    if(nIndex == wxNOT_FOUND)
        nIndex = file.pIndexOf( wxT("Name=") );
    if(nIndex != wxNOT_FOUND)
        nameapp = file.GetCmd(nIndex);

    // Icon of the application.
    wxString nameicon, namemini;
    nIndex = wxNOT_FOUND;
#if wxUSE_INTL // try "Icon[locale name]" first
    if ( locale )
        nIndex = file.pIndexOf(wxT("Icon[")+locale->GetName()+wxT("]="));
#endif // wxUSE_INTL
    if(nIndex == wxNOT_FOUND)
        nIndex = file.pIndexOf( wxT("Icon=") );
    if(nIndex != wxNOT_FOUND) {
        nameicon = wxString(wxT("--icon ")) + file.GetCmd(nIndex);
        namemini = wxString(wxT("--miniicon ")) + file.GetCmd(nIndex);
    }

    // Replace some of the field code in the 'Exec' entry.
    // TODO: deal with %d, %D, %n, %N, %k and %v (but last one is deprecated)
    nIndex = file.pIndexOf( wxT("Exec=") );
    if (nIndex == wxNOT_FOUND)
        return;
    wxString sCmd = file.GetCmd(nIndex);
    // we expect %f; others including  %F and %U and %u are possible
    sCmd.Replace(wxT("%F"), wxT("%f"));
    sCmd.Replace(wxT("%U"), wxT("%f"));
    sCmd.Replace(wxT("%u"), wxT("%f"));
    if (0 == sCmd.Replace ( wxT("%f"), wxT("%s") ))
        sCmd = sCmd + wxT(" %s");
    sCmd.Replace(wxT("%c"), nameapp);
    sCmd.Replace(wxT("%i"), nameicon);
    sCmd.Replace(wxT("%m"), namemini);

    wxStringTokenizer tokenizer(mimetypes, wxT(";"));
    while(tokenizer.HasMoreTokens()) {
        wxString mimetype = tokenizer.GetNextToken().Lower();
        nIndex = m_aTypes.Index(mimetype);
        if(nIndex != wxNOT_FOUND) { // is this a known MIME type?
            wxMimeTypeCommands* entry = m_aEntries[nIndex];
            entry->AddOrReplaceVerb(wxT("open"), sCmd);
        }
    }
}
Example #27
0
// -------------------------------------------------------------------------------- //
int guLibUpdateThread::ScanDirectory( wxString dirname, bool includedir )
{
  wxDir         Dir;
  wxString      FileName;
  wxString      LowerFileName;
  bool          FoundCover = false;
  wxString      FirstAudioFile;

  if( !dirname.EndsWith( wxT( "/" ) ) )
    dirname += wxT( "/" );

  //guLogMessage( wxT( "Scanning dir (%i) '%s'" ), includedir, dirname.c_str() );
  Dir.Open( dirname );

  if( !TestDestroy() && Dir.IsOpened() )
  {
    if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
    {
      do {
        if( FileName[ 0 ] == '.' )
          continue;

        if ( !m_ScanSymlinks && IsFileSymbolicLink( dirname + FileName ) )
            continue;

        int FileDate = GetFileLastChangeTime( dirname + FileName );
        if( Dir.Exists( dirname + FileName ) )
        {
          //guLogMessage( wxT( "Scanning dir '%s' : FileDate: %u  -> %u\n%u Tracks found" ), ( dirname + FileName ).c_str(), m_LastUpdate, FileDate, m_TrackFiles.Count() );
          ScanDirectory( dirname + FileName, includedir || ( FileDate > m_LastUpdate ) );

          wxCommandEvent event( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
          event.SetInt( m_GaugeId );
          event.SetExtraLong( m_TrackFiles.Count() );
          wxPostEvent( m_MainFrame, event );
        }
        else
        {
          //guLogMessage( wxT( "%s (%i): FileDate: %u  -> %u" ), ( dirname + FileName ).c_str(), includedir, m_LastUpdate, FileDate );
          if( includedir || ( FileDate > m_LastUpdate ) )
          {
            LowerFileName = FileName.Lower();

            if( guIsValidAudioFile( LowerFileName ) )
            {
              if( !m_Db->FindDeletedFile( dirname + FileName, false ) )
              {
                m_TrackFiles.Add( dirname + FileName );
                if( m_ScanEmbeddedCovers && FirstAudioFile.IsEmpty() )
                    FirstAudioFile = dirname + FileName;
              }
            }
            else if( guIsValidImageFile( LowerFileName ) )
            {
              if( SearchCoverWords( LowerFileName, m_CoverSearchWords ) )
              {
                //guLogMessage( wxT( "Adding image '%s'" ), wxString( dirname + FileName ).c_str() );
                m_ImageFiles.Add( dirname + FileName );
                FoundCover = true;
              }
            }
            else if( m_ScanAddPlayLists && guPlaylistFile::IsValidPlayList( LowerFileName ) )
            {
              m_PlayListFiles.Add( dirname + FileName );
            }
            else if( guCuePlaylistFile::IsValidFile( LowerFileName ) )
            {
              //
              m_CueFiles.Add( dirname + FileName );
            }
            //else
            //{
            //    guLogMessage( wxT( "Unknown file: '%s'"), ( dirname + FileName ).c_str() );
            //}
          }
        }
      } while( !TestDestroy() && Dir.GetNext( &FileName ) );

      if( m_ScanEmbeddedCovers && !FoundCover && !FirstAudioFile.IsEmpty() )
      {
        m_ImageFiles.Add( FirstAudioFile );
      }
    }
  }
  else
  {
      guLogMessage( wxT( "Could not open the dir '%s'" ), dirname.c_str() );
  }
  return 1;
}
Example #28
0
bool wxTextCtrl::Create(
  wxWindow*                         pParent
, wxWindowID                        vId
, const wxString&                   rsValue
, const wxPoint&                    rPos
, const wxSize&                     rSize
, long                              lStyle
, const wxValidator&                rValidator
, const wxString&                   rsName
)
{
    //
    // Base initialization
    //
    if ( !CreateBase( pParent
                     ,vId
                     ,rPos
                     ,rSize
                     ,lStyle
                     ,rValidator
                     ,rsName
                    ))
        return false;

    wxPoint                         vPos = rPos; // The OS/2 position
    SWP                             vSwp;

    if (pParent )
    {
        pParent->AddChild(this);
    }

    m_windowStyle = lStyle;
    m_bIsMLE = false;
    m_bSkipUpdate = false;

    long                            lSstyle = WS_VISIBLE | WS_TABSTOP;

    //
    // Single and multiline edit fields are two different controls in PM
    //
    if ( m_windowStyle & wxTE_MULTILINE )
    {
        lSstyle |= MLS_BORDER | MLS_WORDWRAP;
        m_bIsMLE = true;

        if ((m_windowStyle & wxTE_NO_VSCROLL) == 0)
            lSstyle |= MLS_VSCROLL;
        if (m_windowStyle & wxHSCROLL)
            lSstyle |= MLS_HSCROLL;
        if (m_windowStyle & wxTE_READONLY)
            lSstyle |= MLS_READONLY;
    }
    else
    {
        lSstyle |= ES_LEFT | ES_AUTOSCROLL | ES_MARGIN;

        if (m_windowStyle & wxHSCROLL)
            lSstyle |=  ES_AUTOSCROLL;
        if (m_windowStyle & wxTE_READONLY)
            lSstyle |= ES_READONLY;
        if (m_windowStyle & wxTE_PASSWORD) // hidden input
            lSstyle |= ES_UNREADABLE;
    }

    if (m_bIsMLE)
    {
        m_hWnd = (WXHWND)::WinCreateWindow( (HWND)GetHwndOf(pParent) // Parent window handle
                                           ,WC_MLE                   // Window class
                                           ,(PSZ)rsValue.c_str()     // Initial Text
                                           ,(ULONG)lSstyle           // Style flags
                                           ,(LONG)0                  // X pos of origin
                                           ,(LONG)0                  // Y pos of origin
                                           ,(LONG)0                  // field width
                                           ,(LONG)0                  // field height
                                           ,(HWND)GetHwndOf(pParent) // owner window handle (same as parent
                                           ,HWND_TOP                 // initial z position
                                           ,(ULONG)vId               // Window identifier
                                           ,NULL                     // no control data
                                           ,NULL                     // no Presentation parameters
                                          );
    }
    else
    {
        m_hWnd = (WXHWND)::WinCreateWindow( (HWND)GetHwndOf(pParent) // Parent window handle
                                           ,WC_ENTRYFIELD            // Window class
                                           ,(PSZ)rsValue.c_str()     // Initial Text
                                           ,(ULONG)lSstyle           // Style flags
                                           ,(LONG)0                  // X pos of origin
                                           ,(LONG)0                  // Y pos of origin
                                           ,(LONG)0                  // field width
                                           ,(LONG)0                  // field height
                                           ,(HWND)GetHwndOf(pParent) // owner window handle (same as parent
                                           ,HWND_TOP                 // initial z position
                                           ,(ULONG)vId               // Window identifier
                                           ,NULL                     // no control data
                                           ,NULL                     // no Presentation parameters
                                          );
    }

    if (m_hWnd == 0)
    {
        return false;
    }

    SubclassWin(GetHWND());

    //
    // Set font, position, size and initial value
    //
    wxFont*                          pTextFont = new wxFont( 8
                                                            ,wxMODERN
                                                            ,wxNORMAL
                                                            ,wxNORMAL
                                                           );
    SetFont(*pTextFont);
    if (!rsValue.empty())
    {
        SetValue(rsValue);
    }
    SetupColours();
    //
    // If X and/or Y are not zero the difference is the compensation value
    // for margins for OS/2 controls.
    //
    ::WinQueryWindowPos(m_hWnd, &vSwp);
    SetXComp(vSwp.x);
    SetYComp(vSwp.y);
    SetSize( vPos.x - GetXComp()
            ,vPos.y - GetYComp()
            ,rSize.x
            ,rSize.y
           );
    delete pTextFont;
    return true;
} // end of wxTextCtrl::Create
Example #29
0
FileIO::FileIO(const wxString name, FileIOMode mode)
: mName(name),
  mMode(mode),
  mFtp(NULL),
  mInputStream(NULL),
  mOutputStream(NULL),
  mOpen(false)
{
   wxString scheme;

   mUri.Create(mName);
   scheme = mUri.GetScheme();

   if (scheme == wxT("ftp")) {
      wxString user = mUri.GetUser();
      wxString pass = mUri.GetPassword();;

      mFtp = new wxFTP();
      mFtp->SetDefaultTimeout(60);

      if (!user.IsEmpty()) {
         mFtp->SetUser(user);
      }

      if (!pass.IsEmpty()) {
         mFtp->SetPassword(pass);
      }

      if (!mFtp->Connect(mUri.GetServer())) {
         wxPrintf(wxT("Couldn't connect to server\n"));

         delete mFtp;
         mFtp = NULL;

         return;
      }

      mFtp->SetBinary();
      mFtp->SetPassive(true);

      if (mMode == FileIO::Input) {
         mInputStream = mFtp->GetInputStream(mUri.GetPath());
         if (mInputStream == NULL) {
            wxPrintf(wxT("Couldn't get input stream: %s\n"), mUri.GetPath().c_str());
   
            delete mFtp;
            mFtp = NULL;
   
            return;
         }
      }
      else {
         mOutputStream = mFtp->GetOutputStream(mUri.GetPath());
         if (mOutputStream == NULL) {
            wxPrintf(wxT("Couldn't get output stream: %s\n"), mUri.GetPath().c_str());
   
            delete mFtp;
            mFtp = NULL;
   
            return;
         }
      }

      mOpen = true;
   }
   else {
      if (mMode == FileIO::Input) {
         mInputStream = new wxFFileInputStream(mName);
         if (mInputStream == NULL) {
            wxPrintf(wxT("Couldn't get input stream: %s\n"), name.c_str());
            return;
         }
      }
      else {
         mOutputStream = new wxFFileOutputStream(mName);
         if (mOutputStream == NULL) {
            wxPrintf(wxT("Couldn't get output stream: %s\n"), name.c_str());
            return;
         }
      }

      mOpen = true;
   }
}
Example #30
0
void ChatPanel::OutputError(const wxString& message)
{
	OutputLine(wxString::Format(_(" Error: %s"), message.c_str()), sett().GetChatColorError());
}