Example #1
0
std::vector<wxString> CRgbaquad::Split(const wxString & s, char seperator)
{
	std::vector<wxString> output;

	std::string::size_type prev_pos = 0, pos = 0;

	while ((pos = s.find(seperator, pos)) != std::string::npos)
	{
		wxString substring(s.substr(prev_pos, pos - prev_pos));

		output.push_back(substring);

		prev_pos = ++pos;
	}

	output.push_back(s.substr(prev_pos, pos - prev_pos)); // Last word

	return output;
}
Example #2
0
FileNameParser::Type FileNameParser::getFileType(const wxString& filename)
{
	if (filename.empty()) return e_unknown;

	int pos = filename.rfind('.');
	if (pos == -1) return e_unknown;

	std::string extension = filename.substr(pos);
	if (extension == ".txt")
	{
		const wxString txtName = filename.substr(0, filename.find_last_of('.'));
		if (txtName.find('_') == -1) return e_unknown;

		const wxString txtExtension = txtName.substr(txtName.find_last_of('_') + 1);

		if (txtExtension == TAG_POLYLINE) return e_polyline;
		else if (txtExtension == TAG_CIRCLE) return e_circle;
		else if (txtExtension == TAG_POLYGON) return e_polygon;
		else if (txtExtension == TAG_MESH) return e_mesh;
		else if (txtExtension == TAG_COMBINATION) return e_combination;
		else return e_unknown;
	}
	else if (extension == ".json")
	{
		const wxString jsonName = filename.substr(0, filename.find_last_of('.'));
		if (jsonName.find('_') == -1) return e_unknown;

		const wxString jsonExtension = jsonName.substr(jsonName.find_last_of('_') + 1);

		if (jsonExtension == TAG_SHAPE) return e_shape;
		else if (jsonExtension == TAG_COMPLEX) return e_complex;
		else if (jsonExtension == TAG_ANIM) return e_anim;
		else if (jsonExtension == TAG_PATCH) return e_9patch;
		else if (jsonExtension == TAG_FONTBLANK) return e_fontblank;
		else return e_unknown;
	}
	else
	{
		StringTools::toLower(extension);
		if (extension == ".jpg" || extension == ".png" || extension == ".bmp") return e_image;
		else return e_unknown;
	}
}
unsigned int HexToInt(wxString theLine, int start,int size)
{
    long rv=0;
    wxString ss=theLine.substr(start,size);
    bool valid=ss.ToLong(&rv,16);
//    bool valid=theLine.substr(start,size).ToLong(&rv,16);
    if (valid)
        return rv;
    else
        return -1;
}
Example #4
0
File: Env.cpp Project: boulerne/e
void cxEnv::SetToCurrent() {
#ifdef __WXMSW__
	LPWCH envStr = ::GetEnvironmentStrings();
	if (!envStr) return;
	const wxChar* env = envStr;

	while (*env != wxT('\0')) {
		const wxString envStr(env);
		if (envStr.StartsWith(wxT("=C:"))) { // special case that holds cwd for C:
			const wxString value = envStr.substr(4);
			m_env[wxT("=C:")] = value;
		}
		else {
			const int equalNdx = envStr.Find(wxT('='));
			if (equalNdx != -1) {
				// NOTE: cygwin uses all env keys in uppercase, so we
				// convert here. But if used native we might want to avoid this
				wxString key = envStr.substr(0, equalNdx);
				key.MakeUpper();
				const wxString value = envStr.substr(equalNdx+1);
				m_env[key] = value;
			}
		}

		env += envStr.size()+1;
	}

	::FreeEnvironmentStrings(envStr);
#else
	char **env = environ;
	while(*env != NULL)
	{
		const wxString envStr(*env, wxConvUTF8);
		const int equalNdx = envStr.Find(wxT('='));
		if (equalNdx != -1) {
			m_env[envStr.substr(0, equalNdx)] = envStr.substr(equalNdx+1);
		}
		env++;
	}
#endif //__WXMSW__
}
Example #5
0
bool SpritesPanelImpl::DragSymbolTarget::
OnDropText(wxCoord x, wxCoord y, const wxString& data)
{
	wxString sType = data.substr(0, data.find(","));
	wxString sIndex = data.substr(data.find(",") + 1);

	long index;
	sIndex.ToLong(&index);

	ISymbol* symbol = m_panelImpl->m_libraryPanel->getSymbol(index);
	if (symbol)
	{
		Vector pos = m_panelImpl->m_editPanel->transPosScreenToProject(x, y);
		ISprite* sprite = SpriteFactory::create(symbol);
		sprite->translate(pos);
		m_panelImpl->insertSprite(sprite);
		sprite->release();
	}

	return true;
}
Example #6
0
wxString CygwinPathToWin(const wxString& path) { // static
	if (path.empty()) {
		wxASSERT(false);
		return wxEmptyString;
	}
	wxString newpath;

	if (path.StartsWith(wxT("/cygdrive/"))) {

		// Get drive letter
		const wxChar drive = wxToupper(path[10]);
		if (drive < wxT('A') || drive > wxT('Z')) {
			wxASSERT(false);
			return wxEmptyString;
		}

		// Build new path
		newpath += drive;
		newpath += wxT(':');
		if (path.size() > 11) newpath += path.substr(11);
		else newpath += wxT('\\');
	}
	else if (path.StartsWith(wxT("/usr/bin/"))) {
		newpath = GetCygwinDir() + wxT("\\bin\\");
		newpath += path.substr(9);
	}
	else if (path.GetChar(0) == wxT('/')) {
		newpath = GetCygwinDir();
		newpath += path;
	}
	else return path; // no conversion

	// Convert path seperators
	for (unsigned int i = 0; i < newpath.size(); ++i) {
		if (newpath[i] == wxT('/')) newpath[i] = wxT('\\');
	}

	return newpath;
}
Example #7
0
void SearchTreeNode::Dump(BasicSearchTree* tree, nSearchTreeNode node_id, const wxString& prefix, wxString& result)
{
    wxString suffix(_T(""));
    suffix << _T("- \"") << SerializeString(GetLabel(tree)) << _T("\" (") << U2S(node_id) << _T(")");
    if (prefix.length() && prefix[prefix.length()-1]=='|')
        result << prefix.substr(0,prefix.length()-1) << _T('+') << suffix << _T('\n');
    else if (prefix.length() && prefix[prefix.length()-1]==' ')
        result << prefix.substr(0,prefix.length()-1) << _T('\\') << suffix << _T('\n');
    else
        result << prefix << suffix << _T('\n');
    wxString newprefix(prefix);
    newprefix.append(suffix.length() - 2, _T(' '));
    newprefix << _T("|");
    SearchTreeLinkMap::iterator i;
    unsigned int cnt = 0;
    for (i = m_Children.begin(); i!= m_Children.end(); i++)
    {
        if (cnt == m_Children.size() - 1)
            newprefix[newprefix.length() - 1] = _T(' ');
        tree->GetNode(i->second,false)->Dump(tree,i->second,newprefix,result);
        cnt++;
    }
}
Example #8
0
bool SearchTreeNode::S2I(const wxString& s,int& i)
{
    bool is_ok = true;
    i = 0;
    unsigned int u = 0;
    if (!s.IsEmpty())
    {
        if (s[0]==_T('-'))
        {
            if (!S2U(s.substr(1),u))
                is_ok = false;
            else
                i = 0 - u;
        }
        else
        {
            if (!S2U(s.substr(1),u))
                is_ok = false;
            else
                i = u;
        }
    }
    return is_ok;
}
Example #9
0
	wxString ChooseFile(wxString currentexe, wxString title,
			wxString filenamepattern) {
		wxString defaultpath = wxEmptyString;
		wxString selectedfile;
		if (currentexe.length()) {
			size_t pos = currentexe.rfind(wxT("/"));
			if (pos != wxString::npos)
				defaultpath = currentexe.substr(0, pos);
		}
		wxFileDialog* OpenDialog = new wxFileDialog(this, title, defaultpath,
				wxEmptyString, filenamepattern, wxFD_OPEN, wxDefaultPosition);
		if (OpenDialog->ShowModal() == wxID_OK)
			selectedfile = OpenDialog->GetPath();
		OpenDialog->Destroy();
		return selectedfile;
	}
Example #10
0
//-----------------------------------------------------------------------
bool EditorDocument::OnOpenDocument( const wxString& filename )
{
    if ( filename.empty() || !wxDocument::OnOpenDocument( filename ) )
        return false;

	if (m_imagePath.empty())
	{
		m_imagePath = filename.substr(0, filename.find_last_of('\\')+1);
	}
	

    wxString relFilename( getDefaultResourceGroupRelativePath( filename ) );

    // create handler object
    ImagesetHandler handler( this );

    // This could take some time, enter 'busy' state
    wxWindowDisabler wd; wxBusyCursor bc;

    // do parse (which uses handler to create actual data)
    try
    {
        System::getSingleton().getXMLParser()->parseXMLFile(
            handler,
            CEGUIHelper::ToCEGUIString( relFilename ),
            "Imageset.xsd",
            "" );
    }
    catch ( ... )
    {
        Logger::getSingleton().logEvent( "EditorDocument::onOpenDocument - loading of Imageset from file '" +
                                          CEGUIHelper::ToCEGUIString( filename ) + "' failed.", Errors );
        throw;
    }

    // Since we have overwritten this method, we must notify the views ourselves!
    UpdateAllViews();

    SetFilename( filename, true );
    SetTitle( filename );

    Modify( false );

    return true;
}
Example #11
0
void HtmlDialog::OnMSHTMLBeforeNavigate2X(wxActiveXEvent& event) {
 	const wxString url = event[wxT("Url")];
	if (url == wxT("about:blank"))
		return;

	if (url.StartsWith(wxT("cocoadialog://"))) {
		wxString output = URLDecode(url.substr(14));

		// Remove trailing '/' (added by ie)
		if (output.EndsWith(wxT("/"))) output.RemoveLast();

		printf("%s", output.mb_str(wxConvUTF8));
		if (!m_optionDict.HasOption(wxT("no-newline"))) printf("\n");

		// Don't try to open it in browser
		event[wxT("Cancel")] = true;

		Close();
	}
}
Example #12
0
const wxString wxExGetEndOfText(
    const wxString& text,
    size_t max_chars)
{
    wxString text_out(text);

    if (text_out.length() > max_chars)
    {
        if (4 + text_out.length() - max_chars < text_out.length())
        {
            text_out = "..." + text_out.substr(4 + text_out.length() - max_chars);
        }
        else
        {
            text_out = text.substr(text.length() - max_chars);
        }
    }

    return text_out;
}
Example #13
0
void TempDir::RemoveDir(wxString& path)
{
    wxCHECK_RET(!m_tmp.empty() && path.substr(0, m_tmp.length()) == m_tmp,
                wxT("remove '") + path + wxT("' fails safety check"));

    const wxChar *files[] = {
        wxT("text/empty"),
        wxT("text/small"),
        wxT("bin/bin1000"),
        wxT("bin/bin4095"),
        wxT("bin/bin4096"),
        wxT("bin/bin4097"),
        wxT("bin/bin16384"),
        wxT("zero/zero5"),
        wxT("zero/zero1024"),
        wxT("zero/zero32768"),
        wxT("zero/zero16385"),
        wxT("zero/newname"),
        wxT("newfile"),
    };

    const wxChar *dirs[] = {
        wxT("text/"), wxT("bin/"), wxT("zero/"), wxT("empty/")
    };

    wxString tmp = m_tmp + wxFileName::GetPathSeparator();
    size_t i;

    for (i = 0; i < WXSIZEOF(files); i++)
        wxRemoveFile(tmp + wxFileName(files[i], wxPATH_UNIX).GetFullPath());

    for (i = 0; i < WXSIZEOF(dirs); i++)
        wxRmdir(tmp + wxFileName(dirs[i], wxPATH_UNIX).GetFullPath());

    if (!wxRmdir(m_tmp))
    {
        wxLogSysError(wxT("can't remove temporary dir '%s'"), m_tmp.c_str());
    }
}
Example #14
0
//
// This code assumes that we've already checked for special cases
// involving a cygdrive prefix of '/' and a path that isn't a drive path.
//
// The given path is assumed to already start with cygdrive prefix
//
wxString eDocumentPath::convert_cygdrive_path_to_windows(const wxString& path) {
	const size_t n = eDocumentPath::s_cygdrivePrefix.Len(); // Cygdrive prefix length

	// Get drive letter
	const wxChar drive = wxToupper(path[n] + 1);
	if (drive < wxT('A') || wxT('Z') < drive) {
		// Invalid drive letter; can't do anything with this.
		wxASSERT(false);
		return wxEmptyString;
	}

	wxString newpath;
	newpath += drive;
	newpath += wxT(':');

	// Add stuff after the cygdrive+drive letter to the new path, else just add a slash.
	if (path.size() > n+2) 	newpath += path.substr(n+2);
	else newpath += wxT('\\');

	newpath.Replace(wxT("/"), wxT("\\"));
	return newpath;
}
inline int DetectRepeatingSymbols(wxString const &str, int pos)
{
    int newPos = -1, currPos = pos;
    while (1)
    {
        if (currPos + 4 >= static_cast<int>(str.length()))
            break;
        if (str[currPos + 1] != wxT(','))
            break;
        if (str[currPos + 3] == wxT('\''))
        {
            const wxString &s = str.substr(currPos + 3, str.length() - (currPos + 3));
            if (regexRepeatedChars.Matches(s))
            {
                size_t start, length;
                regexRepeatedChars.GetMatch(&start, &length, 0);
                newPos = currPos + 3 + length;
                if ((newPos + 4 < static_cast<int>(str.length()))
                    && str[newPos] == wxT(',') && str[newPos + 2] == wxT('"'))
                {
                    newPos += 3;
                    while (newPos < static_cast<int>(str.length()) && str[newPos] != wxT('"'))
                        ++newPos;
                    if (newPos + 1 < static_cast<int>(str.length()) && str[newPos] == wxT('"'))
                        ++newPos;
                }
                currPos = newPos;
            }
            else
                break;
        }
        else
            break;

        // move the current position to point at the '"' character
        currPos--;
    }
    return newPos;
}
int FindSequenceDialog::subsearch ( const wxString &s , const wxString &sub , int start )
    {
    int a , b ;
    if ( s.length() < sub.length() ) return -1 ;
    for ( a = start ; a < s.length() - sub.length() + 1 ; a++ )
        {
        for ( b = 0 ; b < sub.length() ; b++ )
           {
           if ( sub[b] == '*' )
              {
              if ( subsearch ( s , sub.substr ( b+1 ) , a ) == -1 ) break ;
              b = sub.length()-1 ;
              }
           else
              {
              if ( !doesMatch ( sub[b] , s[a+b] ) ) break ;
              last = a+b ;
              }
           }
        if ( b == sub.length() ) return a ;
        }
    return -1 ;
    }
Example #17
0
int wxExGetLineNumber(const wxString& text)
{
    // Get text after :.
    const size_t pos_char = text.rfind(":");

    if (pos_char == wxString::npos)
    {
        return 0;
    }

    const wxString linenumber = text.substr(pos_char + 1);

    long line;

    if (linenumber.ToLong(&line))
    {
        return line;
    }
    else
    {
        return 0;
    }
}
Example #18
0
void CCodeParser::ParseCInclude(wxString code)
{
    int userIncludeEnd;
    m_userInclude = wxT("");

    //find the begining of the user include
    int userIncludeStart = code.Find(wxT("//// end generated include"));
    if (userIncludeStart != wxNOT_FOUND)
    {
        userIncludeStart = code.find(wxT('\n'), userIncludeStart);
        if (userIncludeStart != wxNOT_FOUND)
        {
            //find the end of the user include
            userIncludeEnd = code.find(wxT("\n/** Implementing "), userIncludeStart);

            if (userIncludeEnd != wxNOT_FOUND)
            {
                userIncludeStart++;
                m_userInclude = code.substr(userIncludeStart, userIncludeEnd - userIncludeStart);
            }
        }
    }
}
Example #19
0
const wxString wxExLink::FindPath(const wxString& text) const
{
  if (
    text.empty() ||
    // wxPathList cannot handle links over several lines.
    wxExGetNumberOfLines(text) > 1)
  {
    return wxEmptyString;
  }

  // Better first try to find "...", then <...>, as in next example.
  // <A HREF="http://www.scintilla.org">scintilla</A> component.

  // So, first get text between " signs.
  size_t pos_char1 = text.find("\"");
  size_t pos_char2 = text.rfind("\"");

  // If that did not succeed, then get text between < and >.
  if (pos_char1 == wxString::npos || 
      pos_char2 == wxString::npos || 
      pos_char2 <= pos_char1)
  {
    pos_char1 = text.find("<");
    pos_char2 = text.rfind(">");
  }

  // If that did not succeed, then get text between : and : (in .po files).
  if (m_STC->GetLexer().GetScintillaLexer() == "po" && 
      (pos_char1 == wxString::npos || 
       pos_char2 == wxString::npos || 
       pos_char2 <= pos_char1))
  {
    pos_char1 = text.find(": ");
    pos_char2 = text.rfind(":");
  }

  // If that did not succeed, then get text between ' and '.
  if (pos_char1 == wxString::npos ||
      pos_char2 == wxString::npos || 
      pos_char2 <= pos_char1)
  {
    pos_char1 = text.find("'");
    pos_char2 = text.rfind("'");
  }
  
  wxString out;

  // If we did not find anything.
  if (pos_char1 == wxString::npos || 
      pos_char2 == wxString::npos || 
      pos_char2 <= pos_char1)
  {
    wxRegEx regex("(.*):[0-9]+");
    
    if (regex.Matches(text))
    {
      size_t start, len;

      if (regex.GetMatch(&start, &len, 1))
      {
        out = text.substr(start, len);
      }
      else
      {
        out = text;
      }
    }
    else
    {
      out = text;
    }
  }
  else
  {
    // Okay, get everything inbetween.
    out = text.substr(pos_char1 + 1, pos_char2 - pos_char1 - 1);
  }

  // And make sure we skip white space.
  out.Trim(true);
  out.Trim(false);
  
  return out;
}
Example #20
0
wxString eDocumentPath::CygwinPathToWin(const wxString& path) { 
	if (path.empty()) {
		wxASSERT(false);
		return wxEmptyString;
	}

	wxString newpath;

	// Map cygdrive paths to standard Windows drive-letter.
	if (s_cygdrivePrefix == wxT("/")) {
		const size_t path_len = path.Len();

		// path looks like: /q or /q/ or /q/stuff
		if (path_len == 2 || ((path_len >= 3) && (path[2] == wxT('/'))))
			return convert_cygdrive_path_to_windows(path);

		// If we got here, then don't convert the path, and let the StartsWith cases
		// in the other top-level ifs happen.
	}
	else {
		if (path.StartsWith(s_cygdrivePrefix))
			return convert_cygdrive_path_to_windows(path);
	}

	// For /usr/bin and /usr/lib, techincally we should be mapping anything that
	// appears in the registry under cygwin mounts.
	//
	// Cygwin 1.7 will be changing this behavior, though, and storing mount information
	// in fstab.
	//
	// For now, keep hard coding these mounts and worry about playing will with existing
	// installations (that e didn't do) in the future.
	
	// Map /usr/bin/ paths to Cygwin bin folder
	if (path.StartsWith(wxT("/usr/bin/"))) {
		newpath = s_cygPath + wxT("\\bin\\") + path.substr(9);
		newpath.Replace(wxT("/"), wxT("\\"));
		return newpath;
	}
	
	// Map /usr/lib paths to Cygwin lib folder
	if (path.StartsWith(wxT("/usr/lib/"))) {
		newpath = s_cygPath + wxT("\\lib\\") + path.substr(9);
		newpath.Replace(wxT("/"), wxT("\\"));
		return newpath;
	}
	
	// Check for UNC paths
	if (path.StartsWith(wxT("//"))) {
		newpath = path;
		newpath.Replace(wxT("/"), wxT("\\"));
		return newpath;
	}
	
	// Cygwin paths that aren't cygdrive paths get mapped to cygwin's native install folder
	if (path.GetChar(0) == wxT('/')) {
		newpath = s_cygPath + path;
		newpath.Replace(wxT("/"), wxT("\\"));
		return newpath;
	}
	
	// If we got here, then don't convert the path.
	return path;
}
 wxString ExtractString(wxString const &s) const
 {
     assert(end <= static_cast<int>(s.length()));
     return s.substr(start, end - start);
 }
Example #22
0
// Try the test for a single flavour of expression
//
void RegExTestCase::doTest(int flavor)
{
    wxRegEx re(m_pattern, m_compileFlags | flavor);

    // 'e' - test that the pattern fails to compile
    if (m_mode == 'e') {
        failIf(re.IsValid(), wxT("compile succeeded (should fail)"));
        return;
    }
    failIf(!re.IsValid(), wxT("compile failed"));

    bool matches = re.Matches(m_data, m_matchFlags);

    // 'f' or 'p' - test that the pattern does not match
    if (m_mode == 'f' || m_mode == 'p') {
        failIf(matches, wxT("match succeeded (should fail)"));
        return;
    }

    // otherwise 'm' or 'i' - test the pattern does match
    failIf(!matches, wxT("match failed"));

    if (m_compileFlags & wxRE_NOSUB)
        return;

    // check wxRegEx has correctly counted the number of subexpressions
    wxString msg;
    msg << wxT("GetMatchCount() == ") << re.GetMatchCount()
        << wxT(", expected ") << m_expected.size();
    failIf(m_expected.size() != re.GetMatchCount(), msg);

    for (size_t i = 0; i < m_expected.size(); i++) {
        wxString result;
        size_t start, len;

        msg.clear();
        msg << wxT("wxRegEx::GetMatch failed for match ") << i;
        failIf(!re.GetMatch(&start, &len, i), msg);

        // m - check the match returns the strings given
        if (m_mode == 'm')
        {
            if (start < INT_MAX)
                result = m_data.substr(start, len);
            else
                result = wxT("");
        }

        // i - check the match returns the offsets given
        else if (m_mode == 'i')
        {
            if (start > INT_MAX)
                result = wxT("-1 -1");
            else if (start + len > 0)
                result << start << wxT(" ") << start + len - 1;
            else
                result << start << wxT(" -1");
        }

        msg.clear();
        msg << wxT("match(") << i << wxT(") == ") << quote(result)
            << wxT(", expected == ") << quote(m_expected[i]);
        failIf(result != m_expected[i], msg);
    }
}
Example #23
0
wxString eSettings::StripSlashes(const wxString& path) { // static
	if (path.empty() || path == wxT('/')) return wxEmptyString;
	const size_t start = (path[0] == wxT('/')) ? 1 : 0;
	const size_t end = (path.Last() ==  wxT('/')) ? path.size()-1 : path.size();
	return path.substr(start, end-start);
}
Example #24
0
Frame::Frame()
  : wxExFrameWithHistory(nullptr, wxID_ANY, wxTheApp->GetAppDisplayName())
  , m_Results(new wxExGrid(this))
  , m_Query(new wxExSTC(this))
  , m_Shell(new wxExShell(this, "", ";", true, 50))
{
  SetIcon(wxICON(app));

  wxExMenu* menuFile = new wxExMenu;
  menuFile->Append(wxID_NEW);
  menuFile->Append(wxID_OPEN);
  GetFileHistory().UseMenu(ID_RECENTFILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu* menuDatabase = new wxExMenu;
  menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
  menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));

  wxExMenu* menuQuery = new wxExMenu;
  menuQuery->Append(wxID_EXECUTE);
  menuQuery->Append(wxID_STOP);

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(wxID_PREFERENCES);

  wxExMenu* menuView = new wxExMenu();
  AppendPanes(menuView);
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
  menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
  menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));

  wxMenu* menuHelp = new wxMenu();
  menuHelp->Append(wxID_ABOUT);

  wxMenuBar *menubar = new wxMenuBar;
  menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuDatabase, _("&Connection"));
  menubar->Append(menuQuery, _("&Query"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
  SetMenuBar(menubar);

  m_Results->CreateGrid(0, 0);
  m_Results->EnableEditing(false); // this is a read-only grid

  m_Shell->SetFocus();

#if wxUSE_STATUSBAR
  SetupStatusBar(std::vector<wxExStatusBarPane>{
    wxExStatusBarPane(),
    wxExStatusBarPane("PaneInfo", 100, _("Lines"))});
#endif

  GetToolBar()->AddControls(false); // no realize yet
  GetToolBar()->AddTool(wxID_EXECUTE, 
    wxEmptyString,
    wxArtProvider::GetBitmap(
      wxART_GO_FORWARD, wxART_TOOLBAR, GetToolBar()->GetToolBitmapSize()),
    wxGetStockLabel(wxID_EXECUTE, wxSTOCK_NOFLAGS));
  GetToolBar()->Realize();

  GetManager().AddPane(m_Shell,
    wxAuiPaneInfo().
      Name("CONSOLE").
      CenterPane());

  GetManager().AddPane(m_Results,
    wxAuiPaneInfo().
      Name("RESULTS").
      Caption(_("Results")).
      CloseButton(true).
      Bottom().
      MaximizeButton(true));

  GetManager().AddPane(m_Query,
    wxAuiPaneInfo().
      Name("QUERY").
      Caption(_("Query")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Statistics.Show(this),
    wxAuiPaneInfo().Left().
      Hide().
      MaximizeButton(true).
      Caption(_("Statistics")).
      Name("STATISTICS"));

  GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
  GetManager().GetPane("QUERY").Show(false);

  GetManager().Update();
  
  Bind(wxEVT_CLOSE_WINDOW, [=](wxCloseEvent& event) {
    if (wxExFileDialog(this,
      &m_Query->GetFile()).ShowModalIfChanged()  != wxID_CANCEL)
    {
      wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());
      event.Skip();
    }});
    
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    wxAboutDialogInfo info;
    info.SetIcon(GetIcon());
    info.SetDescription(_("This program offers a general ODBC query."));
    info.SetVersion(wxExGetVersionInfo().GetVersionOnlyString());
    info.SetCopyright(wxExGetVersionInfo().GetCopyright());
    info.AddDeveloper(wxExOTL::VersionInfo().GetVersionString());
    wxAboutBox(info);
    }, wxID_ABOUT);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    m_Stopped = false;
    if (m_Query->GetText().empty()) return;
    if (m_Results->IsShown())
    {
      m_Results->ClearGrid();
    }
    // Skip sql comments.
    std::regex re("--.*$");
    wxString output = std::regex_replace(m_Query->GetText().ToStdString(), re, "", std::regex_constants::format_sed);
    // Queries are seperated by ; character.
    wxStringTokenizer tkz(output, ";");
    int no_queries = 0;
    m_Running = true;
    const auto start = std::chrono::system_clock::now();
    // Run all queries.
    while (tkz.HasMoreTokens() && !m_Stopped)
    {
      wxString query = tkz.GetNextToken();
      query.Trim(true);
      query.Trim(false);
      if (!query.empty())
      {
        try
        {
          RunQuery(query, no_queries == 0);
          no_queries++;
        }
        catch (otl_exception& p)
        {
          m_Statistics.Inc(_("Number of query errors"));
          m_Shell->AppendText(
            _("\nerror: ") +  wxString(wxExQuoted(p.msg)) + 
            _(" in: ") + wxString(wxExQuoted(query)));
        }
      }
    }
    const auto end = std::chrono::system_clock::now();
    const auto elapsed = end - start;
    const auto milli = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
    m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
      no_queries,
      (float)milli.count() / (float)1000).ToStdString());
    m_Running = false;}, wxID_EXECUTE);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    Close(true);}, wxID_EXIT);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    m_Query->GetFile().FileNew(wxExFileName());
    m_Query->SetFocus();
    ShowPane("QUERY");}, wxID_NEW);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    wxExOpenFilesDialog(
      this, 
      wxFD_OPEN | wxFD_CHANGE_DIR, 
      "sql files (*.sql)|*.sql|" + 
      _("All Files") + wxString::Format(" (%s)|%s",
        wxFileSelectorDefaultWildcardStr,
        wxFileSelectorDefaultWildcardStr),
      true);}, wxID_OPEN);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    m_Query->GetFile().FileSave();}, wxID_SAVE);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    wxExFileDialog dlg(
      this, 
      &m_Query->GetFile(), 
      wxGetStockLabel(wxID_SAVEAS), 
      wxFileSelectorDefaultWildcardStr, 
      wxFD_SAVE);
    if (dlg.ShowModal() == wxID_OK)
    {
       m_Query->GetFile().FileSave(dlg.GetPath().ToStdString());
    }}, wxID_SAVEAS);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    m_Running = false;
    m_Stopped = true;}, wxID_STOP);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    if (m_otl.Logoff())
    {
      m_Shell->SetPrompt(">");
    }}, ID_DATABASE_CLOSE);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    if (m_otl.Logon(this))
    {
      m_Shell->SetPrompt(m_otl.Datasource().ToStdString() + ">");
    }}, ID_DATABASE_OPEN);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    if (m_otl.IsConnected())
    {
      try
      {
        const wxString input(event.GetString());
        if (!input.empty())
        {
          const wxString query = input.substr(
            0,
            input.length() - 1);

          m_Stopped = false;
          RunQuery(query, true);
        }
      }
      catch (otl_exception& p)
      {
        if (m_Results->IsShown())
        {
          m_Results->EndBatch();
        }
        m_Shell->AppendText(_("\nerror: ") + wxString(wxExQuoted(p.msg)));
      }
    }
    else
    {
      m_Shell->AppendText(_("\nnot connected"));
    }
    m_Shell->Prompt();}, ID_SHELL_COMMAND);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    m_Stopped = true;
    m_Shell->Prompt("cancelled");}, ID_SHELL_COMMAND_STOP);

  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    TogglePane("QUERY");}, ID_VIEW_QUERY);
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    TogglePane("RESULTS");}, ID_VIEW_RESULTS);
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    TogglePane("STATISTICS");}, ID_VIEW_STATISTICS);
  
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    event.Enable(m_Query->GetModify());}, wxID_SAVE);
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    event.Enable(m_Query->GetLength() > 0);}, wxID_SAVEAS);
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    event.Enable(m_Running);}, wxID_STOP);
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    event.Enable(m_otl.IsConnected());}, ID_DATABASE_CLOSE);
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    event.Enable(!m_otl.IsConnected());}, ID_DATABASE_OPEN);
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    // If we have a query, you can hide it, but still run it.
    event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());}, wxID_EXECUTE);
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    event.Enable(!GetFileHistory().GetHistoryFile().empty());}, ID_RECENTFILE_MENU);
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    event.Check(GetManager().GetPane("QUERY").IsShown());}, ID_VIEW_QUERY);
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    event.Check(GetManager().GetPane("RESULTS").IsShown());}, ID_VIEW_RESULTS);
  Bind(wxEVT_UPDATE_UI, [=](wxUpdateUIEvent& event) {
    event.Check(GetManager().GetPane("STATISTICS").IsShown());}, ID_VIEW_STATISTICS);
  
  // Do automatic connect.
  if (!m_otl.Datasource().empty() && m_otl.Logon())
  {
    m_Shell->SetPrompt(m_otl.Datasource().ToStdString() + ">");
  }
  else
  {
    m_Shell->SetPrompt(">");
  }
}
Example #25
0
rc_ide2Frame::rc_ide2Frame(wxWindow* parent,wxWindowID id)
{
    rc_initKeywords();
    wxFont rc_font(12,wxFONTFAMILY_DEFAULT,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL);
    rc_path =  wxStandardPaths::Get().GetExecutablePath();
    rc_path = rc_path.substr(0, rc_path.find_last_of(_("\\"))) +_("\\");
    //(*Initialize(rc_ide2Frame)
    wxMenuItem* MenuItem2;
    wxMenuItem* MenuItem1;
    wxMenu* Menu1;
    wxBoxSizer* BoxSizer1;
    wxMenuBar* MenuBar1;
    wxMenu* Menu2;

    Create(parent, id, _("RC Basic"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE, _T("id"));
    SetClientSize(wxSize(640,480));
    SetMinSize(wxSize(640,480));
    SetExtraStyle( GetExtraStyle() | wxFRAME_EX_METAL );
    {
    	wxIcon FrameIcon;
    	FrameIcon.CopyFromBitmap(wxBitmap(wxImage(_T("img\\rcbasic.ico"))));
    	SetIcon(FrameIcon);
    }
    BoxSizer1 = new wxBoxSizer(wxHORIZONTAL);
    AuiNotebook1 = new wxAuiNotebook(this, ID_AUINOTEBOOK1, wxDefaultPosition, wxDefaultSize, wxAUI_NB_DEFAULT_STYLE);
    BoxSizer1->Add(AuiNotebook1, 1, wxALL|wxEXPAND, 1);
    SetSizer(BoxSizer1);
    MenuBar1 = new wxMenuBar();
    Menu1 = new wxMenu();
    MenuItem6 = new wxMenuItem(Menu1, newID, _("New"), wxEmptyString, wxITEM_NORMAL);
    Menu1->Append(MenuItem6);
    MenuItem5 = new wxMenuItem(Menu1, openID, _("Open"), wxEmptyString, wxITEM_NORMAL);
    Menu1->Append(MenuItem5);
    MenuItem4 = new wxMenuItem(Menu1, saveID, _("Save"), wxEmptyString, wxITEM_NORMAL);
    Menu1->Append(MenuItem4);
    MenuItem3 = new wxMenuItem(Menu1, saveAsID, _("Save As"), wxEmptyString, wxITEM_NORMAL);
    Menu1->Append(MenuItem3);
    MenuItem1 = new wxMenuItem(Menu1, idMenuQuit, _("Quit\tAlt-F4"), _("Quit the application"), wxITEM_NORMAL);
    Menu1->Append(MenuItem1);
    MenuBar1->Append(Menu1, _("&File"));
    Menu3 = new wxMenu();
    MenuItem7 = new wxMenuItem(Menu3, undoID, _("Undo"), wxEmptyString, wxITEM_NORMAL);
    Menu3->Append(MenuItem7);
    MenuItem8 = new wxMenuItem(Menu3, redoID, _("Redo"), wxEmptyString, wxITEM_NORMAL);
    Menu3->Append(MenuItem8);
    Menu3->AppendSeparator();
    MenuItem9 = new wxMenuItem(Menu3, cutID, _("Cut"), wxEmptyString, wxITEM_NORMAL);
    Menu3->Append(MenuItem9);
    MenuItem10 = new wxMenuItem(Menu3, copyID, _("Copy"), wxEmptyString, wxITEM_NORMAL);
    Menu3->Append(MenuItem10);
    MenuItem11 = new wxMenuItem(Menu3, pasteID, _("Paste"), wxEmptyString, wxITEM_NORMAL);
    Menu3->Append(MenuItem11);
    MenuItem12 = new wxMenuItem(Menu3, deleteID, _("Delete"), wxEmptyString, wxITEM_NORMAL);
    Menu3->Append(MenuItem12);
    MenuBar1->Append(Menu3, _("Edit"));
    Menu4 = new wxMenu();
    MenuItem13 = new wxMenuItem(Menu4, compileID, _("Compile"), wxEmptyString, wxITEM_NORMAL);
    Menu4->Append(MenuItem13);
    MenuItem14 = new wxMenuItem(Menu4, runID, _("Run"), wxEmptyString, wxITEM_NORMAL);
    Menu4->Append(MenuItem14);
    MenuBar1->Append(Menu4, _("Build"));
    Menu2 = new wxMenu();
    MenuItem2 = new wxMenuItem(Menu2, idMenuAbout, _("About\tF1"), _("Show info about this application"), wxITEM_NORMAL);
    Menu2->Append(MenuItem2);
    MenuItem15 = new wxMenuItem(Menu2, referenceID, _("Reference"), wxEmptyString, wxITEM_NORMAL);
    Menu2->Append(MenuItem15);
    MenuBar1->Append(Menu2, _("Help"));
    SetMenuBar(MenuBar1);
    StatusBar1 = new wxStatusBar(this, ID_STATUSBAR1, 0, _T("ID_STATUSBAR1"));
    int __wxStatusBarWidths_1[1] = { -1 };
    int __wxStatusBarStyles_1[1] = { wxSB_NORMAL };
    StatusBar1->SetFieldsCount(1,__wxStatusBarWidths_1);
    StatusBar1->SetStatusStyles(1,__wxStatusBarStyles_1);
    SetStatusBar(StatusBar1);
    ToolBar1 = new wxToolBar(this, ID_TOOLBAR1, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL|wxNO_BORDER, _T("ID_TOOLBAR1"));
    ToolBarItem1 = ToolBar1->AddTool(toolNewID, _("New File"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_NEW")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, _("New File"));
    ToolBarItem2 = ToolBar1->AddTool(toolOpenID, _("Open File"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_FILE_OPEN")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, _("Open File"));
    ToolBarItem3 = ToolBar1->AddTool(toolSaveID, _("Save File"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_FILE_SAVE")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);
    ToolBarItem4 = ToolBar1->AddTool(toolSaveAsID, _("Save File As"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_FILE_SAVE_AS")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, _("Save File As"));
    ToolBar1->AddSeparator();
    ToolBarItem5 = ToolBar1->AddTool(toolRunID, _("Run Program"), wxBitmap(wxImage(_T("img\\player_play.png"))), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, _("Run Program"));
    ToolBarItem6 = ToolBar1->AddTool(toolStopID, _("Stop Program"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_ERROR")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, _("Stops Program"));
    ToolBar1->Realize();
    SetToolBar(ToolBar1);
    SetSizer(BoxSizer1);
    Layout();
    Center();

    Connect(newID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnNewPage);
    Connect(openID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnPageOpen);
    Connect(saveID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::onSavePage);
    Connect(saveAsID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnSavePageAs);
    Connect(idMenuQuit,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnQuit);
    Connect(undoID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnUndo);
    Connect(redoID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnRedo);
    Connect(cutID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnCut);
    Connect(copyID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnCopy);
    Connect(pasteID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnPaste);
    Connect(deleteID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnDelete);
    Connect(compileID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnCompile);
    Connect(runID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnRun);
    Connect(idMenuAbout,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnAbout);
    Connect(referenceID,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&rc_ide2Frame::OnReference);
    Connect(toolNewID,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&rc_ide2Frame::OnNewPage);
    Connect(toolOpenID,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&rc_ide2Frame::OnPageOpen);
    Connect(toolSaveID,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&rc_ide2Frame::onSavePage);
    Connect(toolSaveAsID,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&rc_ide2Frame::OnSavePageAs);
    Connect(toolRunID,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&rc_ide2Frame::OnRun);
    Connect(toolStopID,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&rc_ide2Frame::OnStop);
    //*)
}
Example #26
0
wxString get_name(const wxString& pathname) {
	return pathname.substr(pathname.find_last_of('/') + 1);
}
Example #27
0
wxString get_path(const wxString& pathname) {
	return pathname.substr(0, pathname.find_last_of('/'));
}
Example #28
0
wxString get_parent(const wxString& dir) {
	return dir.substr(0, dir.find_last_of('/'));
}
Example #29
0
wxString wxFilterClassFactoryBase::PopExtension(const wxString& location) const
{
    return location.substr(0, FindExtension(location));
}
void ArchiveTestCase<ClassFactoryT>::VerifyDir(wxString& path,
                                               size_t rootlen /*=0*/)
{
    wxDir dir;
    path += wxFileName::GetPathSeparator();
    int pos = path.length();
    wxString name;

    if (!rootlen)
        rootlen = pos;

    if (dir.Open(path) && dir.GetFirst(&name)) {
        do {
            path.replace(pos, wxString::npos, name);
            name = m_factory->GetInternalName(
                    path.substr(rootlen, wxString::npos));

            bool isDir = wxDirExists(path);
            if (isDir)
                name += _T("/");

            // provide some context for the error message so that we know which
            // iteration of the loop we were on
            string error_entry((_T(" '") + name + _T("'")).mb_str());
            string error_context(" failed for entry" + error_entry);

            TestEntries::iterator it = m_testEntries.find(name);
            CPPUNIT_ASSERT_MESSAGE(
                "archive contains an entry that shouldn't be there"
                    + error_entry,
                it != m_testEntries.end());

            const TestEntry& testEntry = *it->second;

#ifndef __WXMSW__
            CPPUNIT_ASSERT_MESSAGE("timestamp check" + error_context,
                                   testEntry.GetDateTime() ==
                                   wxFileName(path).GetModificationTime());
#endif
            if (!isDir) {
                wxFFileInputStream in(path);
                CPPUNIT_ASSERT_MESSAGE(
                    "entry not found in archive" + error_entry, in.Ok());

                size_t size = (size_t)in.GetLength();
                wxCharBuffer buf(size);
                CPPUNIT_ASSERT_MESSAGE("Read" + error_context,
                    in.Read(buf.data(), size).LastRead() == size);
                CPPUNIT_ASSERT_MESSAGE("size check" + error_context,
                    testEntry.GetSize() == size);
                CPPUNIT_ASSERT_MESSAGE("data compare" + error_context,
                    memcmp(buf.data(), testEntry.GetData(), size) == 0);
            }
            else {
                VerifyDir(path, rootlen);
            }

            delete it->second;
            m_testEntries.erase(it);
        }
        while (dir.GetNext(&name));
    }
}