コード例 #1
0
ファイル: Path.cpp プロジェクト: dreamerc/amule
/** Returns true if the two paths are equal. */
bool IsSameAs(const wxString& a, const wxString& b)
{
	// Cache the current directory
	const wxString cwd = wxGetCwd();

	// We normalize everything, except env. variables, which
	// can cause problems when the string is not encodable
	// using wxConvLibc which wxWidgets uses for the purpose.
	const int flags = (wxPATH_NORM_ALL | wxPATH_NORM_CASE) & ~wxPATH_NORM_ENV_VARS;

	// Let wxFileName handle the tricky stuff involved in actually
	// comparing two paths ... Currently, a path ending with a path-
	// seperator will be unequal to the same path without a path-
	// seperator, which is probably for the best, but can could
	// lead to some unexpected behavior.
	wxFileName fn1(a);
	wxFileName fn2(b);
	
	fn1.Normalize(flags, cwd);
	fn2.Normalize(flags, cwd);

	return (fn1.GetFullPath() == fn2.GetFullPath());
}
コード例 #2
0
void WinEDA_MainFrame::Load_Prj_Config(void)
/*******************************************/
{
FILE * in_file;

	in_file = fopen(m_PrjFileName, "rt");
	if ( in_file == 0 )
		{
		wxString msg = _("Project File <") + m_PrjFileName + _("> not found");
		DisplayError(this, msg);
		return;
		}
	fclose(in_file);

	wxSetWorkingDirectory(wxPathOnly(m_PrjFileName) );
	SetTitle(Main_Title + " " + m_PrjFileName);
	ReCreateMenuBar();
	m_LeftWin->ReCreateTreePrj();

	wxString msg = _("\nWorking dir: ") + wxGetCwd();
	msg << _("\nProject: ") << m_PrjFileName << "\n";
	PrintMsg(msg);
}
コード例 #3
0
ファイル: util.cpp プロジェクト: hugofvw/wxExtension
void wxExOpenFiles(
    wxExFrame* frame,
    const wxArrayString& files,
    long file_flags,
    int dir_flags)
{
    // std::vector gives compile error.
    for (
#ifdef wxExUSE_CPP0X
        auto it = files.begin();
#else
        wxArrayString::const_iterator it = files.begin();
#endif
        it != files.end();
        it++)
    {
        wxString file = *it; // cannot be const because of file = later on

        if (file.Contains("*") || file.Contains("?"))
        {
            wxExDirOpenFile dir(frame, wxGetCwd(), file, file_flags, dir_flags);
            dir.FindFiles();
        }
        else
        {
            int line = 0;

            if (!wxFileName(file).FileExists() && file.Contains(":"))
            {
                line = atoi(file.AfterFirst(':').c_str());
                file = file.BeforeFirst(':');
            }

            frame->OpenFile(file, line, wxEmptyString, file_flags);
        }
    }
}
コード例 #4
0
ファイル: unpkg.cpp プロジェクト: MissValeska/rpcs3
int Unpack(wxFile& pkg_f, std::string src, std::string dst)
{
	PKGHeader* m_header = (PKGHeader*) malloc (sizeof(PKGHeader));

	wxFile dec_pkg_f;
	std::string decryptedFile = wxGetCwd() + "/dev_hdd1/" + src + ".dec";

	dec_pkg_f.Create(decryptedFile, true);
	
	if (Decrypt(pkg_f, dec_pkg_f, m_header) < 0)
		return -1;
	
	dec_pkg_f.Close();

	wxFile n_dec_pkg_f(decryptedFile, wxFile::read);

	std::vector<PKGEntry> m_entries;
	m_entries.resize(m_header->file_count);

	PKGEntry *m_entries_ptr = &m_entries[0];
	if (!LoadEntries(n_dec_pkg_f, m_header, m_entries_ptr))
		return -1;

	wxProgressDialog pdlg("PKG Decrypter / Installer", "Please wait, unpacking...", m_entries.size(), 0, wxPD_AUTO_HIDE | wxPD_APP_MODAL);

	for (const PKGEntry& entry : m_entries)
	{
		UnpackEntry(n_dec_pkg_f, entry, dst + src + "/");
		pdlg.Update(pdlg.GetValue() + 1);
	}
	pdlg.Update(m_entries.size());

	n_dec_pkg_f.Close();
	wxRemoveFile(decryptedFile);

	return 0;
}
コード例 #5
0
ファイル: utildlgs.cpp プロジェクト: erwin47/alh
void CShowDescriptionListDlg::SaveAs()
{
    int            err, i;
    CBaseObject  * pObj;
    CStr           S(128);

    wxString CurrentDir = wxGetCwd();
    wxFileDialog dialog(GetParent(),
                        wxT("Save current text"),
                        wxT(""),
                        wxT(""),
                        wxT(SZ_ALL_FILES),
                        wxFD_SAVE |  wxFD_OVERWRITE_PROMPT );
    err = dialog.ShowModal();
    wxSetWorkingDirectory(CurrentDir);

    if (wxID_OK == err)
    {
        CFileWriter F;
        if (F.Open(dialog.GetPath().mb_str()))
        {
            for (i=0; i<m_pItems->Count(); i++)
            {
                pObj = (CBaseObject*)m_pItems->At(i);
                S    = pObj->Description;
                S.TrimRight(TRIM_ALL);
                S << EOL_FILE;
                F.WriteBuf(S.GetData(), S.GetLength());
            }
            F.Close();
        }
        else
            wxMessageBox(wxT("Can not open file"));

    }

}
コード例 #6
0
ファイル: pgm_base.cpp プロジェクト: chgans/kicad
void PGM_BASE::saveCommonSettings()
{
    // m_common_settings is not initialized until fairly late in the
    // process startup: initPgm(), so test before using:
    if( m_common_settings )
    {
        wxString cur_dir = wxGetCwd();

        m_common_settings->Write( workingDirKey, cur_dir );
        m_common_settings->Write( showEnvVarWarningDialog, m_show_env_var_dialog );

        // Save the local environment variables.
        m_common_settings->SetPath( pathEnvVariables );

        for( ENV_VAR_MAP_ITER it = m_local_env_vars.begin(); it != m_local_env_vars.end(); ++it )
        {
            wxLogTrace( traceEnvVars, wxT( "Saving environment varaiable config entry %s as %s" ),
                        GetChars( it->first ),  GetChars( it->second.GetValue() ) );
            m_common_settings->Write( it->first, it->second.GetValue() );
        }

        m_common_settings->SetPath( wxT( ".." ) );
    }
}
コード例 #7
0
ファイル: CscopePlugin.cpp プロジェクト: jenslody/codeblocks
void CscopePlugin::DoCscopeCommand(const wxString &cmd, const wxString &endMsg)
{
    ClearOutputWindow();
	MakeOutputPaneVisible();
	m_CscouptOutput.clear();

    cbProject * prj = Manager::Get()->GetProjectManager()->GetActiveProject();
    wxString path;
    if ( prj )
        path = prj->GetBasePath();

    Manager::Get()->GetLogManager()->Log(cmd);
    m_EndMsg = endMsg;

    if ( m_pProcess ) return;


    wxString curDir = wxGetCwd();
	wxSetWorkingDirectory(path);
    //set environment variables for cscope
	wxSetEnv(_T("TMPDIR"), _T("."));

    m_view->GetWindow()->SetMessage(_T("Executing cscope..."), 10);

	m_pProcess = new CscopeProcess(this);
    if ( !wxExecute(cmd, wxEXEC_ASYNC|wxEXEC_MAKE_GROUP_LEADER, m_pProcess) )
    {
        delete m_pProcess;
        m_pProcess = NULL;
        m_view->GetWindow()->SetMessage(_T("Error while calling cscope occurred!"), 0);
    }

    //set environment variables back
    Manager::Get()->GetLogManager()->Log(_T("cscope process started"));
    wxSetWorkingDirectory(curDir);
}
コード例 #8
0
void MyFrame::OnPDF(wxCommandEvent& WXUNUSED(event))
{
  wxFileName fileName;
  fileName.SetPath(wxGetCwd());
  fileName.SetFullName(wxT("default.pdf"));
  wxPrintData printData;
  printData.SetOrientation(wxPORTRAIT);
  printData.SetPaperId(wxPAPER_A4);
  printData.SetFilename(fileName.GetFullPath());
  {
    wxPdfDC dc(printData);
    bool ok = dc.StartDoc(_("Printing ..."));
    if (ok)
    {
      dc.StartPage();
      Draw(dc);
      dc.EndPage();
      dc.EndDoc();
    }
  }
#if defined(__WXMSW__)
  ShellExecute(NULL, _T("open"), fileName.GetFullPath(), _T(""), _T(""), 0);
#endif
}
コード例 #9
0
ファイル: LayerDlg.cpp プロジェクト: kamalsirsa/vtp
//Helper
bool SaveAbstractLayer(vtAbstractLayer *alay, bool bAskFilename)
{
	vtFeatureSet *fset = alay->GetFeatureSet();
	vtString fname = fset->GetFilename();

	if (bAskFilename)
	{
		// save current directory
		wxString path = wxGetCwd();

		wxString default_file(StartOfFilename(fname), wxConvUTF8);
		wxString default_dir(ExtractPath(fname, false), wxConvUTF8);

		EnableContinuousRendering(false);
		wxFileDialog saveFile(NULL, _("Save Abstract Data"), default_dir,
			default_file, FSTRING_SHP, wxFD_SAVE);
		bool bResult = (saveFile.ShowModal() == wxID_OK);
		EnableContinuousRendering(true);
		if (!bResult)
		{
			wxSetWorkingDirectory(path);	// restore
			return false;
		}
		wxString str = saveFile.GetPath();
		fname = str.mb_str(wxConvUTF8);
		fset->SetFilename(fname);
	}
	bool success = fset->SaveToSHP(fname);

	if (success)
		alay->SetModified(false);
	else
		wxMessageBox(_("Couldn't save layer."));

	return success;
}
コード例 #10
0
    void MainFrame::loadPopulation(wxCommandEvent& WXUNUSED(event))
    {
        if (experimentRun.isStarted())
            {}
        else
        {
            wxFileDialog loadParametersDialog(
                this,
                _T("Choose a Population File"),
                wxGetCwd(),
                _T(""),
                _T("*.xml;*.gz"),
                wxOPEN|wxFILE_MUST_EXIST
            );

            int retVal = loadParametersDialog.ShowModal();

            if (retVal==wxID_OK)
            {
                cout_ << "Loading population file: " << WXSTRING_TO_STRING(loadParametersDialog.GetPath()) << endl;

                populationFileName = WXSTRING_TO_STRING(loadParametersDialog.GetFilename());

                experimentRun.setupExperimentInProgress(
                    WXSTRING_TO_STRING(loadParametersDialog.GetPath()),
                    WXSTRING_TO_STRING(loadParametersDialog.GetPath())+string(".new")
                );

                fileMenu->FindItem(wxID_RUNEXPERIMENT_MENUITEM)->Enable(true);
                int genCount = experimentRun.getPopulation()->getGenerationCount();
                updateNumGenerations(genCount);
                setPopulationSize(int(NEAT::Globals::getSingleton()->getParameterValue("PopulationSize")));
                return;
            }
        }
    }
コード例 #11
0
 MyDirGuard() : _d( wxGetCwd() ) {}
コード例 #12
0
ファイル: filectrlg.cpp プロジェクト: chromylei/third_party
bool wxGenericFileCtrl::Create( wxWindow *parent,
                                wxWindowID id,
                                const wxString& defaultDirectory,
                                const wxString& defaultFileName,
                                const wxString& wildCard,
                                long style,
                                const wxPoint& pos,
                                const wxSize& size,
                                const wxString& name )
{
    this->m_style = style;
    m_inSelected = false;
    m_noSelChgEvent = false;
    m_check = NULL;

    // check that the styles are not contradictory
    wxASSERT_MSG( !( ( m_style & wxFC_SAVE ) && ( m_style & wxFC_OPEN ) ),
                  wxT( "can't specify both wxFC_SAVE and wxFC_OPEN at once" ) );

    wxASSERT_MSG( !( ( m_style & wxFC_SAVE ) && ( m_style & wxFC_MULTIPLE ) ),
                  wxT( "wxFC_MULTIPLE can't be used with wxFC_SAVE" ) );

    wxNavigationEnabled<wxControl>::Create( parent, id,
                                            pos, size,
                                            wxTAB_TRAVERSAL,
                                            wxDefaultValidator,
                                            name );

    m_dir = defaultDirectory;

    m_ignoreChanges = true;

    if ( ( m_dir.empty() ) || ( m_dir == wxT( "." ) ) )
    {
        m_dir = wxGetCwd();
        if ( m_dir.empty() )
            m_dir = wxFILE_SEP_PATH;
    }

    const size_t len = m_dir.length();
    if ( ( len > 1 ) && ( wxEndsWithPathSeparator( m_dir ) ) )
        m_dir.Remove( len - 1, 1 );

    m_filterExtension = wxEmptyString;

    // layout

    const bool is_pda = ( wxSystemSettings::GetScreenType() <= wxSYS_SCREEN_PDA );

    wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );

    wxBoxSizer *staticsizer = new wxBoxSizer( wxHORIZONTAL );
    if ( is_pda )
        staticsizer->Add( new wxStaticText( this, wxID_ANY, _( "Current directory:" ) ),
                          wxSizerFlags().DoubleBorder(wxRIGHT) );
    m_static = new wxStaticText( this, wxID_ANY, m_dir );
    staticsizer->Add( m_static, 1 );
    mainsizer->Add( staticsizer, wxSizerFlags().Expand().Border());

    long style2 = wxLC_LIST;
    if ( !( m_style & wxFC_MULTIPLE ) )
        style2 |= wxLC_SINGLE_SEL;

#ifdef __WXWINCE__
    style2 |= wxSIMPLE_BORDER;
#else
    style2 |= wxSUNKEN_BORDER;
#endif

    m_list = new wxFileListCtrl( this, ID_FILELIST_CTRL,
                                 wxEmptyString, false,
                                 wxDefaultPosition, wxSize( 400, 140 ),
                                 style2 );

    m_text = new wxTextCtrl( this, ID_TEXT, wxEmptyString,
                             wxDefaultPosition, wxDefaultSize,
                             wxTE_PROCESS_ENTER );
    m_choice = new wxChoice( this, ID_CHOICE );

    if ( is_pda )
    {
        // PDAs have a different screen layout
        mainsizer->Add( m_list, wxSizerFlags( 1 ).Expand().HorzBorder() );

        wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
        textsizer->Add( m_text, wxSizerFlags( 1 ).Centre().Border() );
        textsizer->Add( m_choice, wxSizerFlags( 1 ).Centre().Border() );
        mainsizer->Add( textsizer, wxSizerFlags().Expand() );

    }
    else // !is_pda
    {
        mainsizer->Add( m_list, wxSizerFlags( 1 ).Expand().Border() );
        mainsizer->Add( m_text, wxSizerFlags().Expand().Border() );

        wxBoxSizer *choicesizer = new wxBoxSizer( wxHORIZONTAL );
        choicesizer->Add( m_choice, wxSizerFlags( 1 ).Centre() );

        if ( !( m_style & wxFC_NOSHOWHIDDEN ) )
        {
            m_check = new wxCheckBox( this, ID_CHECK, _( "Show &hidden files" ) );
            choicesizer->Add( m_check, wxSizerFlags().Centre().DoubleBorder(wxLEFT) );
        }

        mainsizer->Add( choicesizer, wxSizerFlags().Expand().Border() );
    }

    SetWildcard( wildCard );

    SetAutoLayout( true );
    SetSizer( mainsizer );

    if ( !is_pda )
    {
        mainsizer->Fit( this );
    }

    m_list->GoToDir( m_dir );
    UpdateControls();
    m_text->SetValue( m_fileName );

    m_ignoreChanges = false;

    // must be after m_ignoreChanges = false
    SetFilename( defaultFileName );

    return true;
}
コード例 #13
0
wxExSampleFrame::wxExSampleFrame()
  : wxExManagedFrame(nullptr, wxID_ANY, wxTheApp->GetAppDisplayName(), 4)
  , m_Process(new wxExProcess())
  , m_Notebook(new wxExNotebook(this, this,
      wxID_ANY, wxDefaultPosition, wxDefaultSize,
      wxAUI_NB_TOP | wxAUI_NB_TAB_SPLIT | wxAUI_NB_TAB_MOVE | wxAUI_NB_SCROLL_BUTTONS))
  , m_STC(new wxExSTC(this))
  , m_Shell(new wxExShell(this, ">", "\n", true, 10))
  , m_STCLexers(new wxExSTC(this, wxExLexers::Get()->GetFileName()))
{
  wxExProcess::PrepareOutput(this);
  
  SetIcon(wxICON(app));

  wxExMenu* menuFile = new wxExMenu;
  menuFile->Append(wxID_OPEN);
  GetFileHistory().UseMenu(ID_RECENTFILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(ID_SHOW_VCS, "Show VCS");
  menuFile->AppendPrint();
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXECUTE);
  menuFile->Append(wxID_STOP);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu *menuEdit = new wxExMenu();
  menuEdit->Append(wxID_UNDO);
  menuEdit->Append(wxID_REDO);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT);
  menuEdit->Append(wxID_COPY);
  menuEdit->Append(wxID_PASTE);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_JUMP_TO);
  menuEdit->AppendSeparator();
  wxExMenu* menuFind = new wxExMenu();
  menuFind->Append(wxID_FIND);
  menuFind->Append(wxID_REPLACE);
  menuEdit->AppendSubMenu(menuFind, _("&Find And Replace"));
  
  wxExMenu* menuDialog = new wxExMenu;
  menuDialog->Append(ID_DLG_ITEM, wxExEllipsed("Item Dialog"));
  menuDialog->AppendSeparator();
  menuDialog->Append(ID_DLG_CONFIG_ITEM, wxExEllipsed("Config Dialog"));
  menuDialog->Append(ID_DLG_CONFIG_ITEM_COL, wxExEllipsed("Config Dialog Columns"));
  menuDialog->Append(ID_DLG_CONFIG_ITEM_READONLY, wxExEllipsed("Config Dialog Readonly"));
  menuDialog->AppendSeparator();
  menuDialog->Append(ID_DLG_LISTVIEW, wxExEllipsed("List Dialog"));
  menuDialog->AppendSeparator();
  menuDialog->Append(ID_DLG_STC_CONFIG, wxExEllipsed("STC Dialog"));
  menuDialog->Append(ID_DLG_STC_ENTRY, wxExEllipsed("STC Entry Dialog"));
  menuDialog->AppendSeparator();
  menuDialog->Append(ID_DLG_VCS, wxExEllipsed("VCS Dialog"));

  wxExMenu* menuSTC = new wxExMenu;
  menuSTC->Append(ID_STC_FLAGS, wxExEllipsed("Open Flag"));
  menuSTC->AppendSeparator();
  menuSTC->Append(ID_STC_SPLIT, "Split");

  wxExMenu *menuView = new wxExMenu;
  AppendPanes(menuView);
  menuView->AppendSeparator();
  menuView->Append(ID_STATISTICS_SHOW, "Statistics");
  
  wxExMenu* menuHelp = new wxExMenu;
  menuHelp->Append(wxID_ABOUT);

  wxMenuBar *menubar = new wxMenuBar;
  menubar->Append(menuFile, "&File");
  menubar->Append(menuEdit, "&Edit");
  menubar->Append(menuView, "&View");
  menubar->Append(menuDialog, "&Dialog");
  menubar->Append(menuSTC, "&STC");
  menubar->Append(menuHelp, "&Help");
  SetMenuBar(menubar);

#if wxUSE_GRID
  m_Grid = new wxExGrid(m_Notebook);
#endif
  m_ListView = new wxExListView(m_Notebook, wxExListView::LIST_NONE);

  GetManager().AddPane(m_Notebook, 
    wxAuiPaneInfo().CenterPane().MinSize(wxSize(250, 250)));
  GetManager().AddPane(m_STC, 
    wxAuiPaneInfo().Bottom().Caption("STC"));
  GetManager().AddPane(m_Shell, 
    wxAuiPaneInfo().Bottom().Caption("Shell").MinSize(wxSize(250, 250)));
  GetManager().AddPane(m_Process->GetShell(), wxAuiPaneInfo()
    .Bottom()
    .Name("PROCESS")
    .MinSize(250, 100)
    .Caption(_("Process")));

  GetManager().Update();

  m_Notebook->AddPage(m_STCLexers, wxExLexers::Get()->GetFileName().GetFullName());
  m_Notebook->AddPage(m_ListView, "wxExListView");

#if wxUSE_GRID
  m_Notebook->AddPage(m_Grid, "wxExGrid");
  m_Grid->CreateGrid(0, 0);
  m_Grid->AppendCols(2);
  wxExSampleDir dir(wxGetCwd().ToStdString(), "*.*", m_Grid);
  dir.FindFiles();
  m_Grid->AutoSizeColumns();
#endif

  m_ListView->SetSingleStyle(wxLC_REPORT);
  m_ListView->AppendColumn(wxExColumn("String", wxExColumn::COL_STRING));
  m_ListView->AppendColumn(wxExColumn("Number", wxExColumn::COL_INT));
  m_ListView->AppendColumn(wxExColumn("Float", wxExColumn::COL_FLOAT));
  m_ListView->AppendColumn(wxExColumn("Date", wxExColumn::COL_DATE));

  const int items = 50;

  for (auto i = 0; i < items; i++)
  {
    m_ListView->InsertItem(i, wxString::Format("item%d", i));
    m_ListView->SetItem(i, 1, std::to_string(i));
    m_ListView->SetItem(i, 2, wxString::Format("%f", (float)i / 2.0));
    m_ListView->SetItem(i, 3, wxDateTime::Now().FormatISOCombined(' '));

    // Set some images.
    if      (i == 0) m_ListView->SetItemImage(i, wxART_CDROM);
    else if (i == 1) m_ListView->SetItemImage(i, wxART_REMOVABLE);
    else if (i == 2) m_ListView->SetItemImage(i, wxART_FOLDER);
    else if (i == 3) m_ListView->SetItemImage(i, wxART_FOLDER_OPEN);
    else if (i == 4) m_ListView->SetItemImage(i, wxART_GO_DIR_UP);
    else if (i == 5) m_ListView->SetItemImage(i, wxART_EXECUTABLE_FILE);
    else if (i == 6) m_ListView->SetItemImage(i, wxART_NORMAL_FILE);
    else             m_ListView->SetItemImage(i, wxART_TICK_MARK);
  }

#if wxUSE_STATUSBAR
  SetupStatusBar(std::vector<wxExStatusBarPane>{
    wxExStatusBarPane(),
    wxExStatusBarPane("PaneFileType", 50, "File type"),
    wxExStatusBarPane("PaneInfo", 100, "Lines or items"),
    wxExStatusBarPane("PaneLexer", 60, "Lexer")});
#endif

  GetToolBar()->AddControls();
  GetOptionsToolBar()->AddControls();
  
  // The OnCommand keeps statistics.
  Bind(wxEVT_MENU, &wxExSampleFrame::OnCommand, this, wxID_COPY);
  Bind(wxEVT_MENU, &wxExSampleFrame::OnCommand, this, wxID_CUT);
  Bind(wxEVT_MENU, &wxExSampleFrame::OnCommand, this, wxID_EXECUTE);
  Bind(wxEVT_MENU, &wxExSampleFrame::OnCommand, this, wxID_JUMP_TO);
  Bind(wxEVT_MENU, &wxExSampleFrame::OnCommand, this, wxID_PASTE);
  Bind(wxEVT_MENU, &wxExSampleFrame::OnCommand, this, wxID_OPEN, wxID_SAVEAS);
  Bind(wxEVT_MENU, &wxExSampleFrame::OnCommand, this, wxID_UNDO, wxID_REDO);
  
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    wxAboutDialogInfo info;
    info.SetIcon(GetIcon());
    info.SetVersion(wxExGetVersionInfo().GetVersionOnlyString());
    info.SetCopyright(wxExGetVersionInfo().GetCopyright());
    wxAboutBox(info);}, wxID_ABOUT);
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    Close(true);}, wxID_EXIT);
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    m_ListView->Print();}, wxID_PRINT);
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    m_ListView->PrintPreview();}, wxID_PREVIEW);
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    wxExPrinting::Get()->GetHtmlPrinter()->PageSetup();}, wxID_PRINT_SETUP);
    
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    const long val = wxGetNumberFromUser("Input columns:",
      wxEmptyString, _("Columns"), 1, 1, 100);
    if (val >= 0)
    {
      wxExItemDialog(this, TestConfigItems(0, val), 
        "Config Dialog Columns", 0, val).ShowModal();
    }}, ID_DLG_CONFIG_ITEM_COL);
    
  Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
    wxExItemDialog* dlg = new wxExItemDialog(this, TestConfigItems(0, 1), 
      "Config Dialog",
      0, 1,
      wxAPPLY | wxCANCEL,
      wxID_ANY,
      wxDefaultPosition,
#ifdef __WXMSW__    
      wxSize(500, 500));
#else
      wxSize(600, 600));
#endif    
    //  dlg->ForceCheckBoxChecked("Group", "Checkboxes");
    dlg->Show();}, ID_DLG_CONFIG_ITEM);
コード例 #14
0
ファイル: envvar_table.cpp プロジェクト: chhlatnash/codelite
void EnvVarsTableDlg::OnExport(wxCommandEvent& event)
{
    int selection = m_notebook1->GetSelection();
    if(selection == wxNOT_FOUND)
        return;

#ifdef __WXMSW__
    bool isWindows = true;
#else
    bool isWindows = false;
#endif

    wxString text;
    if(selection == 0) {
        text = m_textCtrlDefault->GetText();
    } else {
        EnvVarSetPage* page = dynamic_cast<EnvVarSetPage*>(m_notebook1->GetPage((size_t)selection));
        if(page) {
            text = page->m_textCtrl->GetText();
        }
    }

    if(text.IsEmpty())
        return;

    wxArrayString lines = wxStringTokenize(text, wxT("\r\n"), wxTOKEN_STRTOK);
    wxString envfile;
    if(isWindows) {
        envfile << wxT("environment.bat");
    } else {
        envfile << wxT("environment");
    }

    wxFileName fn(wxGetCwd(), envfile);
    wxFFile fp(fn.GetFullPath(), wxT("w+b"));
    if(fp.IsOpened() == false) {
        wxMessageBox(wxString::Format(_("Failed to open file: '%s' for write"), fn.GetFullPath().c_str()),
                     wxT("CodeLite"),
                     wxOK | wxCENTER | wxICON_WARNING);
        return;
    }

    for(size_t i = 0; i < lines.GetCount(); i++) {

        wxString sLine = lines.Item(i).Trim().Trim(false);
        if(sLine.IsEmpty())
            continue;

        static wxRegEx reVarPattern(wxT("\\$\\(( *)([a-zA-Z0-9_]+)( *)\\)"));
        if(isWindows) {
            while(reVarPattern.Matches(sLine)) {
                wxString varName = reVarPattern.GetMatch(sLine, 2);
                wxString text = reVarPattern.GetMatch(sLine);
                sLine.Replace(text, wxString::Format(wxT("%%%s%%"), varName.c_str()));
            }
            sLine.Prepend(wxT("set "));
            sLine.Append(wxT("\r\n"));

        } else {
            while(reVarPattern.Matches(sLine)) {
                wxString varName = reVarPattern.GetMatch(sLine, 2);
                wxString text = reVarPattern.GetMatch(sLine);
                sLine.Replace(text, wxString::Format(wxT("$%s"), varName.c_str()));
            }
            sLine.Prepend(wxT("export "));
            sLine.Append(wxT("\n"));
        }
        fp.Write(sLine);
    }

    wxMessageBox(wxString::Format(_("Environment exported to: '%s' successfully"), fn.GetFullPath().c_str()),
                 wxT("CodeLite"));
}
コード例 #15
0
ファイル: emulator.cpp プロジェクト: mark711/Cafu
// Loads bitmaps
bool wxEmulatorInfo::Load(const wxString& appDir)
{
    // Try to find absolute path
    wxString absoluteConfigPath = m_emulatorFilename;
    if ( !::wxIsAbsolutePath(absoluteConfigPath) )
    {
        wxString currDir = wxGetCwd();
        absoluteConfigPath = currDir + wxString(wxFILE_SEP_PATH) + m_emulatorFilename;
        if ( !wxFile::Exists(absoluteConfigPath) )
        {
            absoluteConfigPath = appDir + wxString(wxFILE_SEP_PATH)
                + m_emulatorFilename;
        }
    }

    if ( !wxFile::Exists(absoluteConfigPath) )
    {
        wxString str;
        str.Printf( wxT("Could not find config file %s"),
            absoluteConfigPath.c_str() );

        wxMessageBox(str);
        return false;
    }

    wxString rootPath = wxPathOnly(absoluteConfigPath);

    {
        wxFileConfig config(wxT("wxEmulator"), wxT("wxWidgets"),
            absoluteConfigPath, wxEmptyString, wxCONFIG_USE_LOCAL_FILE);

        config.Read(wxT("/General/title"), & m_emulatorTitle);
        config.Read(wxT("/General/description"), & m_emulatorDescription);
        config.Read(wxT("/General/backgroundBitmap"), & m_emulatorBackgroundBitmapName);

        wxString colString;
        if (config.Read(wxT("/General/backgroundColour"), & colString) ||
            config.Read(wxT("/General/backgroundColor"), & colString)
           )
        {
            m_emulatorBackgroundColour = wxHexStringToColour(colString);
        }

        int x = 0, y = 0, w = 0, h = 0, dw = 0, dh = 0;
        config.Read(wxT("/General/screenX"), & x);
        config.Read(wxT("/General/screenY"), & y);
        config.Read(wxT("/General/screenWidth"), & w);
        config.Read(wxT("/General/screenHeight"), & h);
        if (config.Read(wxT("/General/deviceWidth"), & dw) && config.Read(wxT("/General/deviceHeight"), & dh))
        {
            m_emulatorDeviceSize = wxSize(dw, dh);
        }

        m_emulatorScreenPosition = wxPoint(x, y);
        m_emulatorScreenSize = wxSize(w, h);
    }

    if (!m_emulatorBackgroundBitmapName.empty())
    {
        wxString absoluteBackgroundBitmapName = rootPath + wxString(wxFILE_SEP_PATH) + m_emulatorBackgroundBitmapName;
        if ( !wxFile::Exists(absoluteBackgroundBitmapName) )
        {
            wxString str;
            str.Printf( wxT("Could not find bitmap %s"),
                absoluteBackgroundBitmapName.c_str() );
            wxMessageBox(str);
            return false;
        }

        wxBitmapType type = wxDetermineImageType(m_emulatorBackgroundBitmapName);
        if (type == wxBITMAP_TYPE_INVALID)
            return false;

        if (!m_emulatorBackgroundBitmap.LoadFile(m_emulatorBackgroundBitmapName, type))
        {
            wxString str;
            str.Printf( wxT("Could not load bitmap file %s"),
                m_emulatorBackgroundBitmapName.c_str() );
            wxMessageBox(str);
            return false;
        }

        m_emulatorDeviceSize = wxSize(m_emulatorBackgroundBitmap.GetWidth(),
            m_emulatorBackgroundBitmap.GetHeight());
    }
    return true;
}
コード例 #16
0
ファイル: emulator.cpp プロジェクト: mark711/Cafu
// 'Main program' equivalent: the program execution "starts" here
bool wxEmulatorApp::OnInit()
{
#if wxUSE_LOG
    wxLog::DisableTimestamp();
#endif // wxUSE_LOG
    wxInitAllImageHandlers();

    wxString currentDir = wxGetCwd();

    // Use argv to get current app directory
    m_appDir = wxFindAppPath(argv[0], currentDir, wxT("WXEMUDIR"));

    // If the development version, go up a directory.
#ifdef __WXMSW__
    if ((m_appDir.Right(5).CmpNoCase(wxT("DEBUG")) == 0) ||
        (m_appDir.Right(11).CmpNoCase(wxT("DEBUGSTABLE")) == 0) ||
        (m_appDir.Right(7).CmpNoCase(wxT("RELEASE")) == 0) ||
        (m_appDir.Right(13).CmpNoCase(wxT("RELEASESTABLE")) == 0)
        )
        m_appDir = wxPathOnly(m_appDir);
#endif

    // Parse the command-line parameters and options
    wxCmdLineParser parser(sg_cmdLineDesc, argc, argv);
    int res;
    {
        wxLogNull log;
        res = parser.Parse();
    }
    if (res == -1 || res > 0 || parser.Found(wxT("h")))
    {
#ifdef __X__
        wxLog::SetActiveTarget(new wxLogStderr);
#endif
        parser.Usage();
        return false;
    }
    if (parser.Found(wxT("v")))
    {
#ifdef __X__
        wxLog::SetActiveTarget(new wxLogStderr);
#endif
        wxString msg;
        msg.Printf(wxT("wxWidgets PDA Emulator (c) Julian Smart, 2002 Version %.2f, %s"), wxEMULATOR_VERSION, __DATE__);
        wxLogMessage(msg);
        return false;
    }
    if (parser.Found(wxT("u"), & m_displayNumber))
    {
        // Should only be number, so strip out anything before
        // and including a : character
        if (m_displayNumber.Find(wxT(':')) != -1)
        {
            m_displayNumber = m_displayNumber.AfterFirst(wxT(':'));
        }
    }
    if (parser.GetParamCount() == 0)
    {
        m_emulatorInfo.m_emulatorFilename = wxT("default.wxe");
    }
    else if (parser.GetParamCount() > 0)
    {
        m_emulatorInfo.m_emulatorFilename = parser.GetParam(0);
    }

    // Load the emulation info
    if (!LoadEmulator(m_appDir))
    {
        //wxMessageBox(wxT("Sorry, could not load this emulator. Please check bitmaps are valid."));
        return false;
    }

    // create the main application window
    wxEmulatorFrame *frame = new wxEmulatorFrame(wxT("wxEmulator"),
                                 wxPoint(50, 50), wxSize(450, 340));

#if wxUSE_STATUSBAR
    frame->SetStatusText(m_emulatorInfo.m_emulatorTitle, 0);

    wxString sizeStr;
    sizeStr.Printf(wxT("Screen: %dx%d"), (int) m_emulatorInfo.m_emulatorScreenSize.x,
            (int) m_emulatorInfo.m_emulatorScreenSize.y);
    frame->SetStatusText(sizeStr, 1);
#endif // wxUSE_STATUSBAR

    m_containerWindow = new wxEmulatorContainer(frame, wxID_ANY);

    frame->SetClientSize(m_emulatorInfo.m_emulatorDeviceSize.x,
                         m_emulatorInfo.m_emulatorDeviceSize.y);

    // and show it (the frames, unlike simple controls, are not shown when
    // created initially)
    frame->Show(true);

#ifdef __WXX11__
    m_xnestWindow = new wxAdoptedWindow;

    wxString cmd;
    cmd.Printf(wxT("Xnest :%s -geometry %dx%d"),
        m_displayNumber.c_str(),
        (int) m_emulatorInfo.m_emulatorScreenSize.x,
        (int) m_emulatorInfo.m_emulatorScreenSize.y);

    // Asynchronously executes Xnest
    m_xnestPID = wxExecute(cmd);
    if (0 == m_xnestPID)
    {
        frame->Destroy();
        wxMessageBox(wxT("Sorry, could not run Xnest. Please check your PATH."));
        return false;
    }

    wxReparenter reparenter;
    if (!reparenter.WaitAndReparent(m_containerWindow, m_xnestWindow, wxT("Xnest")))
    {
        wxMessageBox(wxT("Sorry, could not reparent Xnest.."));
        frame->Destroy();
        return false;
    }

#endif
    m_containerWindow->DoResize();

    // success: wxApp::OnRun() will be called which will enter the main message
    // loop and the application will run. If we returned false here, the
    // application would exit immediately.
    return true;
}
コード例 #17
0
ファイル: Ini.cpp プロジェクト: Ailick/rpcs3
//Ini
Ini::Ini()
{
	m_Config = new wxIniConfig( wxEmptyString, wxEmptyString,
			wxGetCwd() + "\\rpcs3.ini",
			wxEmptyString, wxCONFIG_USE_LOCAL_FILE );
}
コード例 #18
0
ファイル: crashreport.cpp プロジェクト: renemilk/springlobby
    void CrashReport::GenerateReport(EXCEPTION_POINTERS* p)
#endif
{
    wxLogMessage( _T( "Report generated in " ) );
	CwdGuard cwgGuard( wxFileName::GetTempDir() );
	NetDebugReport* report = new NetDebugReport( "http://debug.springlobby.info/upload" ) ;
//	NetDebugReport* report = new NetDebugReport( "http://localhost/upload" ) ;

	// add all standard files: currently this means just a minidump and an
	// XML file with system info and stack trace
	report->AddAll(  );

	wxString dir = report->GetDirectory();

	wxString SystemInfos;

	SystemInfos += _T( "SpringLobby version " ) + TowxString(GetSpringLobbyVersion()) + _T( "\n" ) ;
	SystemInfos += _T( "Built from " ) + wxString( wxVERSION_STRING ) + _T(" on ") + wxPlatformInfo::Get().GetOperatingSystemIdName() + _T( "\n" ) ;

	report->AddText( _T( "SystemInfos.txt" ), SystemInfos, _( "System informations" ) );
#if wxUSE_STD_IOSTREAM
	report->AddText( _T( "AppLog.txt" ), TowxString( crashlog.str() ), _( "Application verbose log" ) );
#endif
    wxString script_file = TowxString(SlPaths::GetDataDir()) + wxFileName::GetPathSeparator() + _T("script.txt");
    if ( wxFile::Exists( script_file ) )
        report->AddFile( script_file, _( "Last generated spring launching script" ) );

#if wxUSE_STACKWALKER && !__WXMSW__
    StackTrace stacktrace;
	stacktrace.Walk( 3, 20 );
	report->AddText( _T( "stacktrace.txt" ), _T("Call stack:\n") + stacktrace.GetStackTrace(), _( "StackTrace" ) );
#else
	wxString report_fn = ( wxGetCwd() + wxFileName::GetPathSeparator() + _T("stacktrace.txt") );
	if ( wxFile::Exists( report_fn ) )
		wxRemoveFile( report_fn );
	wxCharBuffer report_fn_char = report_fn.mb_str();
	DrMingwGenerateStacktrace( p, (const char*)report_fn_char );
	report->AddFile( report_fn, _( "StackTrace" ) );
#endif

	wxString SlBuildFlags;
	#ifdef DISABLE_SOUND
		SlBuildFlags += _T("sound=0");
	#else
		SlBuildFlags += _T("sound=1");
	#endif
	report->AddText( _T("buildflags.txt"), SlBuildFlags, _T("BuildFlags") );

	report->AddText( _T("nick.txt"),
		sett().GetServerAccountNick( sett().GetDefaultServer() ), _T("Nick") );

	wxDebugReportPreviewStd* bkl = new wxDebugReportPreviewStd();
	// calling Show() is not mandatory, but is more polite
	if ( bkl->Show( *report ) ) {
		if ( report->Process() ) {
			wxLogMessage( _T( "Report successfully uploaded." ) );
		}
		else {
				wxLogMessage( _T( "Report generated in \"%s\", but failed to upload" ), report->GetCompressedFileName().c_str() );
				report->Reset();
				wxLogMessage( _T("report reset") );
		}
	}
	//else: user cancelled the report

	delete report;
	wxLogMessage( _T("deleted report") );
}
コード例 #19
0
void wxGenericFileDialog::HandleAction( const wxString &fn )
{
    if (ignoreChanges)
        return;

    wxString filename( fn );
    wxString dir = m_list->GetDir();
    if (filename.empty()) return;
    if (filename == wxT(".")) return;

    // "some/place/" means they want to chdir not try to load "place"
    bool want_dir = filename.Last() == wxFILE_SEP_PATH;
    if (want_dir)
        filename = filename.RemoveLast();

    if (filename == wxT(".."))
    {
        ignoreChanges = true;
        m_list->GoToParentDir();
        m_list->SetFocus();
        UpdateControls();
        ignoreChanges = false;
        return;
    }

#ifdef __UNIX__
    if (filename == wxT("~"))
    {
        ignoreChanges = true;
        m_list->GoToHomeDir();
        m_list->SetFocus();
        UpdateControls();
        ignoreChanges = false;
        return;
    }

    if (filename.BeforeFirst(wxT('/')) == wxT("~"))
    {
        filename = wxString(wxGetUserHome()) + filename.Remove(0, 1);
    }
#endif // __UNIX__

    if (!(m_dialogStyle & wxSAVE))
    {
        if ((filename.Find(wxT('*')) != wxNOT_FOUND) ||
                (filename.Find(wxT('?')) != wxNOT_FOUND))
        {
            if (filename.Find(wxFILE_SEP_PATH) != wxNOT_FOUND)
            {
                wxMessageBox(_("Illegal file specification."), _("Error"), wxOK | wxICON_ERROR );
                return;
            }
            m_list->SetWild( filename );
            return;
        }
    }

    if (!IsTopMostDir(dir))
        dir += wxFILE_SEP_PATH;
    if (!wxIsAbsolutePath(filename))
    {
        dir += filename;
        filename = dir;
    }

    if (wxDirExists(filename))
    {
        ignoreChanges = true;
        m_list->GoToDir( filename );
        UpdateControls();
        ignoreChanges = false;
        return;
    }

    // they really wanted a dir, but it doesn't exist
    if (want_dir)
    {
        wxMessageBox(_("Directory doesn't exist."), _("Error"),
                     wxOK | wxICON_ERROR );
        return;
    }

    // append the default extension to the filename if it doesn't have any
    //
    // VZ: the logic of testing for !wxFileExists() only for the open file
    //     dialog is not entirely clear to me, why don't we allow saving to a
    //     file without extension as well?
    if ( !(m_dialogStyle & wxOPEN) || !wxFileExists(filename) )
    {
        filename = AppendExtension(filename, m_filterExtension);
    }

    // check that the file [doesn't] exist if necessary
    if ( (m_dialogStyle & wxSAVE) &&
            (m_dialogStyle & wxOVERWRITE_PROMPT) &&
            wxFileExists( filename ) )
    {
        wxString msg;
        msg.Printf( _("File '%s' already exists, do you really want to overwrite it?"), filename.c_str() );

        if (wxMessageBox(msg, _("Confirm"), wxYES_NO) != wxYES)
            return;
    }
    else if ( (m_dialogStyle & wxOPEN) &&
              (m_dialogStyle & wxFILE_MUST_EXIST) &&
              !wxFileExists(filename) )
    {
        wxMessageBox(_("Please choose an existing file."), _("Error"),
                     wxOK | wxICON_ERROR );
    }

    SetPath( filename );

    // change to the directory where the user went if asked
    if ( m_dialogStyle & wxCHANGE_DIR )
    {
        wxString cwd;
        wxSplitPath(filename, &cwd, NULL, NULL);

        if ( cwd != wxGetCwd() )
        {
            wxSetWorkingDirectory(cwd);
        }
    }

    wxCommandEvent event;
    wxDialog::OnOK(event);
}
コード例 #20
0
/*static*/
IProcess* WinProcessImpl::Execute(wxEvtHandler *parent, const wxString& cmd, wxString &errMsg, IProcessCreateFlags flags, const wxString &workingDir, IProcessCallback* cb)
{
    SECURITY_ATTRIBUTES saAttr;
    BOOL                fSuccess;

    MyDirGuard dg;

    wxString wd(workingDir);
    if (workingDir.IsEmpty()) {
        wd = wxGetCwd();
    }
    wxSetWorkingDirectory( wd );

    // Set the bInheritHandle flag so pipe handles are inherited.
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;
    WinProcessImpl *prc = new WinProcessImpl(parent);
    prc->m_callback = cb;
    prc->m_flags = flags;

    // The steps for redirecting child process's STDOUT:
    //     1. Save current STDOUT, to be restored later.
    //     2. Create anonymous pipe to be STDOUT for child process.
    //     3. Set STDOUT of the parent process to be write handle to
    //        the pipe, so it is inherited by the child process.
    //     4. Create a noninheritable duplicate of the read handle and
    //        close the inheritable read handle.

    // Save the handle to the current STDOUT.
    prc->hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);

    // Create a pipe for the child process's STDOUT.
    if ( !CreatePipe( &prc->hChildStdoutRd, &prc->hChildStdoutWr, &saAttr, 0) ) {
        delete prc;
        return NULL;
    }

    // Set a write handle to the pipe to be STDOUT.
    if ( !SetStdHandle(STD_OUTPUT_HANDLE, prc->hChildStdoutWr) ) {
        delete prc;
        return NULL;
    }

    // Create noninheritable read handle and close the inheritable read handle.
    fSuccess = DuplicateHandle( GetCurrentProcess(), prc->hChildStdoutRd,
                                GetCurrentProcess(),  &prc->hChildStdoutRdDup ,
                                0,  FALSE,
                                DUPLICATE_SAME_ACCESS );
    if ( !fSuccess ) {
        delete prc;
        return NULL;
    }
    CloseHandle( prc->hChildStdoutRd );

    // The steps for redirecting child process's STDERR:
    //     1. Save current STDERR, to be restored later.
    //     2. Create anonymous pipe to be STDERR for child process.
    //     3. Set STDERR of the parent process to be write handle to
    //        the pipe, so it is inherited by the child process.
    //     4. Create a noninheritable duplicate of the read handle and
    //        close the inheritable read handle.

    // Save the handle to the current STDERR.
    prc->hSaveStderr = GetStdHandle(STD_ERROR_HANDLE);

    // Create a pipe for the child process's STDERR.
    if ( !CreatePipe( &prc->hChildStderrRd, &prc->hChildStderrWr, &saAttr, 0) ) {
        delete prc;
        return NULL;
    }

    // Set a write handle to the pipe to be STDERR.
    if ( !SetStdHandle(STD_ERROR_HANDLE, prc->hChildStderrWr) ) {
        delete prc;
        return NULL;
    }

    // Create noninheritable read handle and close the inheritable read handle.
    fSuccess = DuplicateHandle( GetCurrentProcess(), prc->hChildStderrRd,
                                GetCurrentProcess(),  &prc->hChildStderrRdDup ,
                                0,  FALSE,
                                DUPLICATE_SAME_ACCESS );
    if ( !fSuccess ) {
        delete prc;
        return NULL;
    }
    CloseHandle( prc->hChildStderrRd );

    // The steps for redirecting child process's STDIN:
    //     1.  Save current STDIN, to be restored later.
    //     2.  Create anonymous pipe to be STDIN for child process.
    //     3.  Set STDIN of the parent to be the read handle to the
    //         pipe, so it is inherited by the child process.
    //     4.  Create a noninheritable duplicate of the write handle,
    //         and close the inheritable write handle.

    // Save the handle to the current STDIN.
    prc->hSaveStdin = GetStdHandle(STD_INPUT_HANDLE);

    // Create a pipe for the child process's STDIN.
    if ( !CreatePipe(&prc->hChildStdinRd, &prc->hChildStdinWr, &saAttr, 0) ) {
        delete prc;
        return NULL;
    }
    // Set a read handle to the pipe to be STDIN.
    if ( !SetStdHandle(STD_INPUT_HANDLE, prc->hChildStdinRd) ) {
        delete prc;
        return NULL;
    }
    // Duplicate the write handle to the pipe so it is not inherited.
    fSuccess = DuplicateHandle(GetCurrentProcess(), prc->hChildStdinWr,
                               GetCurrentProcess(), &prc->hChildStdinWrDup,
                               0, FALSE,                  // not inherited
                               DUPLICATE_SAME_ACCESS );
    if ( !fSuccess ) {
        delete prc;
        return NULL;
    }
    CloseHandle(prc->hChildStdinWr);

    // Execute the child process
    STARTUPINFO siStartInfo;

    // Set up members of STARTUPINFO structure.
    ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
    siStartInfo.cb = sizeof(STARTUPINFO);

    siStartInfo.dwFlags    = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; ;
    siStartInfo.hStdInput  = prc->hChildStdinRd;
    siStartInfo.hStdOutput = prc->hChildStdoutWr;
    siStartInfo.hStdError  = prc->hChildStderrWr;

    // Set the window to hide
    siStartInfo.wShowWindow = flags & IProcessCreateConsole ? SW_SHOW : SW_HIDE;
    DWORD creationFlags     = flags & IProcessCreateConsole ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW;

    if(flags & IProcessCreateWithHiddenConsole) {
        siStartInfo.wShowWindow = SW_HIDE;
        creationFlags           = CREATE_NEW_CONSOLE|CREATE_NEW_PROCESS_GROUP;
    }

    BOOL ret = CreateProcess( NULL,
                              cmd.wchar_str(),   // shell line execution command
                              NULL,              // process security attributes
                              NULL,              // primary thread security attributes
                              TRUE,              // handles are inherited
                              creationFlags,     // creation flags
                              NULL,              // use parent's environment
                              NULL,              // CD to tmp dir
                              &siStartInfo,      // STARTUPINFO pointer
                              &prc->piProcInfo); // receives PROCESS_INFORMATION
    if ( ret ) {
        prc->dwProcessId = prc->piProcInfo.dwProcessId;
    } else {
        int err = GetLastError();
        wxUnusedVar(err);
        delete prc;
        return NULL;
    }

    // After process creation, restore the saved STDIN and STDOUT.
    if ( !SetStdHandle(STD_INPUT_HANDLE, prc->hSaveStdin) ) {

        delete prc;
        return NULL;
    }
    if ( !SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStdout) ) {

        delete prc;
        return NULL;
    }
    if ( !SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStderr) ) {

        delete prc;
        return NULL;
    }
    
    if ( prc->m_flags & IProcessCreateConsole || prc->m_flags & IProcessCreateWithHiddenConsole ) {
        ConsoleAttacher ca(prc->GetPid());
        if ( ca.isAttached ) {
            freopen("CONOUT$","wb", stdout);  // reopen stout handle as console window output
            freopen("CONOUT$","wb", stderr);  // reopen stderr handle as console window output
        }
    }
    
    prc->SetPid( prc->dwProcessId );
    prc->StartReaderThread();
    return prc;
}
コード例 #21
0
ファイル: dlg_main.cpp プロジェクト: JohnnyonFlame/odamex
// Main window creation
dlgMain::dlgMain(wxWindow* parent, wxWindowID id)
{
    wxFileConfig ConfigInfo;   
    wxInt32 WindowPosX, WindowPosY, WindowWidth, WindowHeight;
    wxString Version;

    // Loads the frame from the xml resource file
	wxXmlResource::Get()->LoadFrame(this, parent, wxT("dlgMain")); 
    
    // Sets the title of the application with a version string to boot
    Version = wxString::Format(
        wxT("The Odamex Launcher v%d.%d.%d"), 
        VERSIONMAJOR(VERSION), VERSIONMINOR(VERSION), VERSIONPATCH(VERSION));
    
    SetLabel(Version);
    
    // Sets the window size
    ConfigInfo.Read(wxT("MainWindowWidth"), 
                    &WindowWidth, 
                    GetClientSize().GetWidth());
                    
    ConfigInfo.Read(wxT("MainWindowHeight"), 
                    &WindowHeight, 
                    GetClientSize().GetHeight());
    
    SetClientSize(WindowWidth, WindowHeight);
    
    // Set Window position
    ConfigInfo.Read(wxT("MainWindowPosX"), 
                    &WindowPosX, 
                    0);
                    
    ConfigInfo.Read(wxT("MainWindowPosY"), 
                    &WindowPosY, 
                    0);
    
    Move(WindowPosX, WindowPosY);
    
    launchercfg_s.get_list_on_start = 1;
    launchercfg_s.show_blocked_servers = 1;
    launchercfg_s.wad_paths = wxGetCwd();
    launchercfg_s.odamex_directory = wxGetCwd();

    // Set up icons, this is a hack because wxwidgets does not have an xml
    // handler for wxIconBundle :(
    wxIconBundle IconBundle;
    
    IconBundle.AddIcon(wxXmlResource::Get()->LoadIcon(wxT("icon16x16x32")));
    IconBundle.AddIcon(wxXmlResource::Get()->LoadIcon(wxT("icon32x32x32")));
    IconBundle.AddIcon(wxXmlResource::Get()->LoadIcon(wxT("icon48x48x32")));
    IconBundle.AddIcon(wxXmlResource::Get()->LoadIcon(wxT("icon16x16x8")));
    IconBundle.AddIcon(wxXmlResource::Get()->LoadIcon(wxT("icon32x32x8")));
    
    SetIcons(IconBundle);
    
    m_LstCtrlServers = wxDynamicCast(FindWindow(Id_LstCtrlServers), LstOdaServerList);
    m_LstCtrlPlayers = wxDynamicCast(FindWindow(Id_LstCtrlPlayers), LstOdaPlayerList);
    m_LstOdaSrvDetails = wxDynamicCast(FindWindow(Id_LstCtrlServerDetails), LstOdaSrvDetails);

    m_LstCtrlServers->SetupServerListColumns();
    m_LstCtrlPlayers->SetupPlayerListColumns();

	// set up the master server information
    MServer.AddMaster(_T("master1.odamex.net"), 15000);
    MServer.AddMaster(_T("voxelsoft.com"), 15000);
    
    /* Init sub dialogs and load settings */
    config_dlg = new dlgConfig(&launchercfg_s, this);
    server_dlg = new dlgServers(&MServer, this);
    AboutDialog = new dlgAbout(this);
    
    /* Get the first directory for wad downloading */
    wxInt32 Pos = launchercfg_s.wad_paths.Find(wxT(PATH_DELIMITER), false);
    wxString FirstDirectory = launchercfg_s.wad_paths.Mid(0, Pos);
    
    OdaGet = new frmOdaGet(this, -1, FirstDirectory);
    
    QServer = NULL;

    // get master list on application start
    if (launchercfg_s.get_list_on_start)
    {
        wxCommandEvent event(wxEVT_COMMAND_TOOL_CLICKED, Id_MnuItmGetList);
    
        wxPostEvent(this, event);
    }
}
コード例 #22
0
bool PythonDebugger::Debug(bool breakOnEntry)
{
    if(m_DebuggerActive)
        return 0;
    m_changeposition=false;
    m_DispatchedCommands.clear();
    m_curline=0;
    m_bufpos=0;
    m_debugbufpos=0;
    m_progbufpos=0;
    m_outbuf=_T("");
    m_outdebugbuf=_T("");
    m_outprogbuf=_T("");
    if(!m_RunTarget)
    {
        cbEditor *ed=Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
        if(!ed)
            return false;
        wxString s=ed->GetFilename();
        if(!ed->GetControl()->GetLexer()==wxSCI_LEX_PYTHON)
        {
            if(!(wxFileName(s).FileExists() && IsPythonFile(s)))
                return false;
        }
        m_RunTarget=s;
    }

    m_TimerPollDebugger.SetOwner(this, ID_TimerPollDebugger);
    m_pp=new wxProcess(this,ID_PipedProcess);
    m_pp->Redirect();
    wxString target=m_RunTarget;
    wxString olddir=wxGetCwd();
    wxSetWorkingDirectory(wxFileName(m_RunTarget).GetPath());
    target.Replace(_T("\\"),_T("/"),true);

    PyDebuggerConfiguration &cfg =  GetActiveConfigEx();
    wxString commandln = cfg.GetCommandLine(cfg.GetState());
    commandln.Replace(wxT("$target"),target);

    //TODO:
    //read args for this target from config
    //commandln.Replace(wxT("$args"),args);

    Manager::Get()->GetLogManager()->Log(_T("Running python debugger with command line\n")+commandln);
    m_pid=wxExecute(commandln,wxEXEC_ASYNC,m_pp);
    if(!m_pid)
    {
        wxSetWorkingDirectory(olddir);
        return -1;
    }
    m_ostream=m_pp->GetOutputStream();
    m_istream=m_pp->GetInputStream();

    wxSetWorkingDirectory(olddir);

//Send initial stream of commands
    PythonCmdDispatchData dd;
    dd.type=DBGCMDTYPE_FLOWCONTROL;
    dd.cmdtext=_T("Starting New Python Debug Session...");
    m_DispatchedCommands.push_back(dd);//the debug console reports a command prompt on startup, which should be included in the parse count
    m_DebugCommandCount=1;

    wxString acommands=AssembleAliasCommands();
    DispatchCommands(acommands,DBGCMDTYPE_OTHER,false);
    wxString bpcommands=AssembleBreakpointCommands();
    DispatchCommands(bpcommands,DBGCMDTYPE_BREAKPOINT,false);
    DispatchWatchCommands();
    DispatchCommands(_T("w\n"),DBGCMDTYPE_CALLSTACK,true); //where
    m_DebuggerActive=true;

    CodeBlocksLogEvent evtlog(cbEVT_SWITCH_TO_LOG_WINDOW,m_DebugLog);
    Manager::Get()->ProcessEvent(evtlog);

    return 0;
}
コード例 #23
0
ファイル: filedlgg.cpp プロジェクト: ruifig/nutcracker
bool wxGenericFileDialog::Create( wxWindow *parent,
                                  const wxString& message,
                                  const wxString& defaultDir,
                                  const wxString& defaultFile,
                                  const wxString& wildCard,
                                  long  style,
                                  const wxPoint& pos,
                                  const wxSize& sz,
                                  const wxString& name,
                                  bool  bypassGenericImpl )
{
    m_bypassGenericImpl = bypassGenericImpl;

    parent = GetParentForModalDialog(parent, style);

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

    if (m_bypassGenericImpl)
        return true;

    if (!wxDialog::Create( parent, wxID_ANY, message, pos, sz,
                           wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | style, name
                         ))
    {
        return false;
    }

#if wxUSE_CONFIG
    if (wxConfig::Get(false))
    {
        wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ViewStyle"),
                              &ms_lastViewStyle);
        wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ShowHidden"),
                              &ms_lastShowHidden);
    }
#endif

    if ((m_dir.empty()) || (m_dir == wxT(".")))
    {
        m_dir = wxGetCwd();
        if (m_dir.empty())
            m_dir = wxFILE_SEP_PATH;
    }

    const size_t len = m_dir.length();
    if ((len > 1) && (wxEndsWithPathSeparator(m_dir)))
        m_dir.Remove( len-1, 1 );

    m_filterExtension = wxEmptyString;

    // layout

    const bool is_pda = (wxSystemSettings::GetScreenType() <= wxSYS_SCREEN_PDA);

    wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );

    wxBoxSizer *buttonsizer = new wxBoxSizer( wxHORIZONTAL );
    AddBitmapButton( ID_LIST_MODE, wxART_LIST_VIEW,
                     _("View files as a list view"), buttonsizer );
    AddBitmapButton( ID_REPORT_MODE, wxART_REPORT_VIEW,
                     _("View files as a detailed view"), buttonsizer );
    buttonsizer->Add( 30, 5, 1 );
    m_upDirButton = AddBitmapButton( ID_UP_DIR, wxART_GO_DIR_UP,
                                     _("Go to parent directory"), buttonsizer );

#ifndef __DOS__ // VS: Home directory is meaningless in MS-DOS...
    AddBitmapButton( ID_HOME_DIR, wxART_GO_HOME,
                     _("Go to home directory"), buttonsizer );
    buttonsizer->Add( 20, 20 );
#endif //!__DOS__

    m_newDirButton = AddBitmapButton( ID_NEW_DIR, wxART_NEW_DIR,
                                      _("Create new directory"), buttonsizer );

    if (is_pda)
        mainsizer->Add( buttonsizer, wxSizerFlags().Expand() );
    else
        mainsizer->Add( buttonsizer, wxSizerFlags().Expand()
                        .Border( wxLEFT | wxRIGHT | wxTOP ) );

    long style2 = 0;
    if ( HasFdFlag(wxFD_MULTIPLE) )
        style2 |= wxFC_MULTIPLE;

    m_filectrl = new wxGenericFileCtrl( this, ID_FILE_CTRL,
                                        m_dir, defaultFile,
                                        wildCard,
                                        style2,
                                        wxDefaultPosition, wxSize(540,200)
                                      );

    m_filectrl->ShowHidden( ms_lastShowHidden );

    if (ms_lastViewStyle == wxLC_LIST)
    {
        m_filectrl->ChangeToListMode();
    }
    else if (ms_lastViewStyle == wxLC_REPORT)
    {
        m_filectrl->ChangeToReportMode();
    }

    mainsizer->Add(m_filectrl, wxSizerFlags(1).Expand().HorzBorder());

    wxSizer *bsizer = CreateButtonSizer(wxOK | wxCANCEL);
    if ( bsizer )
    {
        if (is_pda)
            mainsizer->Add(bsizer, wxSizerFlags().Expand().Border());
        else
            mainsizer->Add(bsizer, wxSizerFlags().Expand().DoubleBorder());
    }

    SetSizer( mainsizer );

    if (!is_pda)
    {
        mainsizer->SetSizeHints( this );

        Centre( wxBOTH );
    }

    return true;
}
コード例 #24
0
bool ObjectsPropgridHelper::OnPropertySelected(gd::Object * object, gd::Layout * layout, wxPropertyGridEvent& event)
{
    if ( !grid || !object ) return false;

    //Check if the object is global
    bool globalObject = false;
    for (std::size_t i = 0;i<project.GetObjectsCount();++i)
    {
        if ( &project.GetObject(i) == object )
        {
            globalObject = true;
            break;
        }
    }

    if ( event.GetColumn() == 1) //Manage button-like properties
    {
        if ( event.GetPropertyName() == _("Edit") )
        {
            object->EditObject(grid, project, mainFrameWrapper);
            for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                project.GetUsedPlatforms()[j]->GetChangesNotifier().OnObjectEdited(project, globalObject ? NULL : layout, *object);

            //Reload resources : Do not forget to switch the working directory.
            wxString oldWorkingDir = wxGetCwd();
            if ( wxDirExists(wxFileName::FileName(project.GetProjectFile()).GetPath()))
                wxSetWorkingDirectory(wxFileName::FileName(project.GetProjectFile()).GetPath());

            if (layout) object->LoadResources(project, *layout);

            wxSetWorkingDirectory(oldWorkingDir);
        }
        else if ( event.GetPropertyName() == _("Help"))
        {
            auto metadata = gd::MetadataProvider::GetObjectMetadata(project.GetCurrentPlatform(),
                object->GetType());

            gd::HelpFileAccess::Get()->OpenPage(metadata.GetHelpUrl());
        }
        else if ( event.GetPropertyName() == _("Variables") )
        {
            gd::ChooseVariableDialog dialog(grid, object->GetVariables(), true);
            dialog.SetAssociatedObject(&project, layout, object);
            if ( dialog.ShowModal() == 1 )
            {
                for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                    project.GetUsedPlatforms()[j]->GetChangesNotifier().OnObjectVariablesChanged(project, globalObject ? NULL : layout, *object);

                //Update the grid:
                if ( grid->GetProperty("OBJECT_VARIABLES_CATEGORY") != NULL)
                    grid->SetPropertyLabel("OBJECT_VARIABLES_CATEGORY",
                        _("Object variables") + " (" + gd::String::From(object->GetVariables().Count()) + ")");
            }
        }
        else if ( event.GetPropertyName() == "AUTO_ADD" )
        {
            return gd::ChooseBehaviorTypeDialog::ChooseAndAddBehaviorToObject(grid, project,
                object, layout, globalObject);
        }
        else if ( event.GetPropertyName() == "AUTO_REMOVE" )
        {
            //Create behavior array
            wxArrayString behaviorsStr;

            //Fill array
            std::vector <gd::String> behaviors = object->GetAllBehaviorNames();
            for (std::size_t i = 0;i<behaviors.size();++i)
                behaviorsStr.Add(object->GetBehavior(behaviors[i]).GetName());

            int selection = wxGetSingleChoiceIndex(_("Choose the behavior to delete"), _("Choose the behavior to delete"), behaviorsStr);
            if ( selection == -1 ) return false;

            object->RemoveBehavior(behaviors[selection]);
            UpdateBehaviorsSharedData(project, globalObject ? NULL : layout);

            for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                project.GetUsedPlatforms()[j]->GetChangesNotifier().OnBehaviorDeleted(project, globalObject ? NULL : layout, *object, behaviors[selection]);

            return true;
        }
        else if ( event.GetPropertyName().substr(0,12) == "AUTO_RENAME:" )
        {
            event.Veto();
            gd::String oldName = event.GetPropertyName().substr(12);
            if ( !object->HasBehaviorNamed(oldName)) return true;

            gd::Behavior & behavior = object->GetBehavior(oldName);

            gd::String newName = wxGetTextFromUser(_("Enter a new name for the behavior"), _("Rename a behavior"), behavior.GetName());
            if ( newName == behavior.GetName() || object->HasBehaviorNamed(newName) || newName.empty() ) return false;

            object->RenameBehavior(oldName, newName);
            UpdateBehaviorsSharedData(project, globalObject ? NULL : layout);

            for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                project.GetUsedPlatforms()[j]->GetChangesNotifier().OnBehaviorRenamed(project, globalObject ? NULL : layout, *object, behavior, oldName);

            return true;
        }
        else if ( event.GetPropertyName().substr(0,5) == "AUTO:" )
        {
            event.Veto();
            gd::String autoName = event.GetPropertyName().substr(5);
            if ( !object->HasBehaviorNamed(autoName)) return true;

            gd::Behavior & behavior = object->GetBehavior(autoName);

            behavior.EditBehavior(grid, project, layout, mainFrameWrapper); //EditBehavior always need a valid layout!
            for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                project.GetUsedPlatforms()[j]->GetChangesNotifier().OnBehaviorEdited(project, globalObject ? NULL : layout, *object, behavior);
        }
    }

    return false;
}
コード例 #25
0
bool wxGenericFileDialog::Create( wxWindow *parent,
                                  const wxString& message,
                                  const wxString& defaultDir,
                                  const wxString& defaultFile,
                                  const wxString& wildCard,
                                  long  style,
                                  const wxPoint& pos,
                                  bool  bypassGenericImpl )
{
    m_bypassGenericImpl = bypassGenericImpl;

    if (!wxFileDialogBase::Create(parent, message, defaultDir, defaultFile,
                                  wildCard, style, pos))
    {
        return false;
    }

    if (m_bypassGenericImpl)
        return true;

    if (!wxDialog::Create( parent, wxID_ANY, message, pos, wxDefaultSize,
                           wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER ))
    {
        return false;
    }

    ignoreChanges = true;

    if (wxConfig::Get(false))
    {
        wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ViewStyle"),
                              &ms_lastViewStyle);
        wxConfig::Get()->Read(wxT("/wxWindows/wxFileDialog/ShowHidden"),
                              &ms_lastShowHidden);
    }

    if (m_dialogStyle == 0)
        m_dialogStyle = wxOPEN;
    if ((m_dialogStyle & wxMULTIPLE ) && !(m_dialogStyle & wxOPEN))
        m_dialogStyle |= wxOPEN;

    if ((m_dir.empty()) || (m_dir == wxT(".")))
    {
        m_dir = wxGetCwd();
        if (m_dir.empty())
            m_dir = wxFILE_SEP_PATH;
    }

    size_t len = m_dir.Len();
    if ((len > 1) && (wxEndsWithPathSeparator(m_dir)))
        m_dir.Remove( len-1, 1 );

    m_path = m_dir;
    m_path += wxFILE_SEP_PATH;
    m_path += defaultFile;
    m_filterExtension = wxEmptyString;

    // layout

    bool is_pda = (wxSystemSettings::GetScreenType() <= wxSYS_SCREEN_PDA);

    wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );

    wxBoxSizer *buttonsizer = new wxBoxSizer( wxHORIZONTAL );

    wxBitmapButton *but;

    but = new wxBitmapButton(this, ID_LIST_MODE,
                             wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_BUTTON));
#if wxUSE_TOOLTIPS
    but->SetToolTip( _("View files as a list view") );
#endif
    buttonsizer->Add( but, 0, wxALL, 5 );

    but = new wxBitmapButton(this, ID_REPORT_MODE,
                             wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_BUTTON));
#if wxUSE_TOOLTIPS
    but->SetToolTip( _("View files as a detailed view") );
#endif
    buttonsizer->Add( but, 0, wxALL, 5 );

    buttonsizer->Add( 30, 5, 1 );

    m_upDirButton = new wxBitmapButton(this, ID_UP_DIR,
                                       wxArtProvider::GetBitmap(wxART_GO_DIR_UP, wxART_BUTTON));
#if wxUSE_TOOLTIPS
    m_upDirButton->SetToolTip( _("Go to parent directory") );
#endif
    buttonsizer->Add( m_upDirButton, 0, wxALL, 5 );

#ifndef __DOS__ // VS: Home directory is meaningless in MS-DOS...
    but = new wxBitmapButton(this, ID_PARENT_DIR,
                             wxArtProvider::GetBitmap(wxART_GO_HOME, wxART_BUTTON));
#if wxUSE_TOOLTIPS
    but->SetToolTip( _("Go to home directory") );
#endif
    buttonsizer->Add( but, 0, wxALL, 5);

    buttonsizer->Add( 20, 20 );
#endif //!__DOS__

    m_newDirButton = new wxBitmapButton(this, ID_NEW_DIR,
                                        wxArtProvider::GetBitmap(wxART_NEW_DIR, wxART_BUTTON));
#if wxUSE_TOOLTIPS
    m_newDirButton->SetToolTip( _("Create new directory") );
#endif
    buttonsizer->Add( m_newDirButton, 0, wxALL, 5 );

    if (is_pda)
        mainsizer->Add( buttonsizer, 0, wxALL | wxEXPAND, 0 );
    else
        mainsizer->Add( buttonsizer, 0, wxALL | wxEXPAND, 5 );

    wxBoxSizer *staticsizer = new wxBoxSizer( wxHORIZONTAL );
    if (!is_pda)
        staticsizer->Add( new wxStaticText( this, wxID_ANY, _("Current directory:") ), 0, wxRIGHT, 10 );
    m_static = new wxStaticText( this, wxID_ANY, m_dir );
    staticsizer->Add( m_static, 1 );
    mainsizer->Add( staticsizer, 0, wxEXPAND | wxLEFT|wxRIGHT|wxBOTTOM, 10 );

    long style2 = ms_lastViewStyle;
    if ( !(m_dialogStyle & wxMULTIPLE) )
        style2 |= wxLC_SINGLE_SEL;

#ifdef __WXWINCE__
    style2 |= wxSIMPLE_BORDER;
#else
    style2 |= wxSUNKEN_BORDER;
#endif

    wxSize list_size(500,240);
    if (is_pda) list_size = wxSize(50,80);

    m_list = new wxFileCtrl( this, ID_LIST_CTRL,
                             wxEmptyString, ms_lastShowHidden,
                             wxDefaultPosition, list_size,
                             style2);

    if (is_pda)
    {
        // PDAs have a different screen layout
        mainsizer->Add( m_list, 1, wxEXPAND|wxSHRINK | wxLEFT|wxRIGHT, 5 );

        wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
        m_text = new wxTextCtrl( this, ID_TEXT, m_fileName, wxDefaultPosition, wxDefaultSize, wxPROCESS_ENTER );
        textsizer->Add( m_text, 1, wxCENTER | wxALL, 5 );
        mainsizer->Add( textsizer, 0, wxEXPAND );

        m_check = NULL;
        m_choice = new wxChoice( this, ID_CHOICE );
        textsizer->Add( m_choice, 1, wxCENTER|wxALL, 5 );

        buttonsizer = new wxBoxSizer( wxHORIZONTAL );
        buttonsizer->Add( new wxButton( this, wxID_OK ), 0, wxCENTER | wxALL, 5 );
        buttonsizer->Add( new wxButton( this, wxID_CANCEL ), 0, wxCENTER | wxALL, 5 );
        mainsizer->Add( buttonsizer, 0, wxALIGN_RIGHT );
    }
    else
    {
        mainsizer->Add( m_list, 1, wxEXPAND | wxLEFT|wxRIGHT, 10 );

        wxBoxSizer *textsizer = new wxBoxSizer( wxHORIZONTAL );
        m_text = new wxTextCtrl( this, ID_TEXT, m_fileName, wxDefaultPosition, wxDefaultSize, wxPROCESS_ENTER );
        textsizer->Add( m_text, 1, wxCENTER | wxLEFT|wxRIGHT|wxTOP, 10 );
        textsizer->Add( new wxButton( this, wxID_OK ), 0, wxCENTER | wxLEFT|wxRIGHT|wxTOP, 10 );
        mainsizer->Add( textsizer, 0, wxEXPAND );

        wxBoxSizer *choicesizer = new wxBoxSizer( wxHORIZONTAL );
        m_choice = new wxChoice( this, ID_CHOICE );
        choicesizer->Add( m_choice, 1, wxCENTER|wxALL, 10 );
        m_check = new wxCheckBox( this, ID_CHECK, _("Show hidden files") );
        m_check->SetValue( ms_lastShowHidden );
        choicesizer->Add( m_check, 0, wxCENTER|wxALL, 10 );
        choicesizer->Add( new wxButton( this, wxID_CANCEL ), 0, wxCENTER | wxALL, 10 );
        mainsizer->Add( choicesizer, 0, wxEXPAND );
    }

    SetWildcard(wildCard);

    SetAutoLayout( true );
    SetSizer( mainsizer );

    if (!is_pda)
    {
        mainsizer->Fit( this );
        mainsizer->SetSizeHints( this );

        Centre( wxBOTH );
    }

    m_text->SetFocus();

    ignoreChanges = false;

    return true;
}
コード例 #26
0
ファイル: ToolsPlus.cpp プロジェクト: stahta01/EmBlocks
void ToolsPlus::OnRunTarget(wxCommandEvent& event)
{
    int ID=event.GetId();
    wxString commandstr;
    wxString consolename;
    wxString workingdir;
    bool windowed=false;
    bool console=false;
    if (ID>=ID_ContextMenu_0&&ID<=ID_ContextMenu_49)
    {
        m_interpnum=m_contextvec[ID-ID_ContextMenu_0];
        commandstr=m_ic.interps[m_interpnum].command;
        consolename=m_ic.interps[m_interpnum].name;
        windowed=(m_ic.interps[m_interpnum].mode==_("W"));
        console=(m_ic.interps[m_interpnum].mode==_("C"));
        workingdir=m_ic.interps[m_interpnum].wdir;
    }
    else if (ID>=ID_SubMenu_0&&ID<=ID_SubMenu_49)
    {
        m_interpnum=ID-ID_SubMenu_0;
        commandstr=m_ic.interps[m_interpnum].command;
        consolename=m_ic.interps[m_interpnum].name;
        windowed=(m_ic.interps[m_interpnum].mode==_("W"));
        console=(m_ic.interps[m_interpnum].mode==_("C"));
        workingdir=m_ic.interps[m_interpnum].wdir;
        m_wildcard=m_ic.interps[m_interpnum].wildcards;
        if (m_ic.interps[m_interpnum].command.Find(_("$file"))>0 ||
            m_ic.interps[m_interpnum].command.Find(_("$path"))>0)
        {
            m_RunTarget=wxEmptyString;
            EditorManager* edMan = Manager::Get()->GetEditorManager();
            if (edMan && edMan->GetActiveEditor() && edMan->GetActiveEditor()->GetFilename())
            {
                wxFileName activefile(edMan->GetActiveEditor()->GetFilename());
                wxString filename=activefile.GetFullPath();
                wxString name=activefile.GetFullName();
                if (WildCardListMatch(m_ic.interps[m_interpnum].wildcards,name))
                    m_RunTarget=filename;
            }
            if (m_RunTarget==wxEmptyString)
                OnSetTarget(event);
            if (!wxFileName::FileExists(m_RunTarget))
            {
                LogMessage(_("Tools Plus plugin: ")+m_RunTarget+_(" not found"));
                return;
            }
        }
        if (m_ic.interps[m_interpnum].command.Find(_("$dir"))>0)
        {
            OnSetDirTarget(event);
            if (!wxFileName::DirExists(m_RunTarget))
            {
                LogMessage(_("Tools Plus plugin: ")+m_RunTarget+_(" not found"));
                return;
            }
            if (m_RunTarget==_T(""))
                return;
        }
        if (m_ic.interps[m_interpnum].command.Find(_("$mpaths"))>0)
        {
            OnSetMultiTarget(event);
            if (m_RunTarget==_T(""))
                return;
        }
    }
    else
    {
        LogMessage(wxString::Format(_("WARNING: Unprocessed Tools Plus Menu Message: ID %i, IDbase %i, IDend %i, num items on menu %i"),ID,ID_ContextMenu_0,ID_ContextMenu_49,(int)m_contextvec.size()));
        return;
    }

    m_RunTarget.Replace(_T("*"),_T(" "));

    bool setdir=true;
    commandstr.Replace(_("$file"),wxFileName(m_RunTarget).GetShortPath());
    commandstr.Replace(_("$relfile"),wxFileName(m_RunTarget).GetFullName());
    commandstr.Replace(_("$fname"),wxFileName(m_RunTarget).GetName());
    commandstr.Replace(_("$fext"),wxFileName(m_RunTarget).GetExt());
    commandstr.Replace(_("$dir"),wxFileName(m_RunTarget).GetShortPath());
    commandstr.Replace(_("$reldir"),wxFileName(m_RunTarget).GetFullName());
    commandstr.Replace(_("$path"),wxFileName(m_RunTarget).GetShortPath());
    commandstr.Replace(_("$relpath"),wxFileName(m_RunTarget).GetFullPath());
    if (commandstr.Replace(_("$mpaths"),m_RunTarget)>0)
        setdir=false;

    // substitute user prompted values in the format: $inputstr{Enter your message}
    int promptind=commandstr.Find(_("$inputstr{"));
    wxString substitution;
    while (promptind>=0)
    {
        int promptend=commandstr.Mid(promptind+10).Find(_("}"));
        if (promptend<=0)
        {
            cbMessageBox(_("Malformed $inputstr in command line -- no closing '}' found: ")+commandstr);
            return;
        }
        else
            promptend++;
        wxTextEntryDialog ted(NULL,commandstr.Mid(promptind+10,promptend-1),consolename,_T(""),wxOK|wxCANCEL);
        if (ted.ShowModal()==wxID_OK)
            substitution=ted.GetValue();
        else
            return;
        commandstr=commandstr.Left(promptind)+substitution+commandstr.Mid(promptind+10+promptend);
        int nextind=commandstr.Mid(promptind+substitution.Len()).Find(_("$inputstr"));
        if (nextind>=0)
            promptind+=nextind+substitution.Len();
        else
            promptind=-1;
    }

    commandstr.Replace(_("$interpreter"),wxFileName(m_ic.interps[m_interpnum].command).GetShortPath());
    workingdir.Replace(_("$parentdir"),wxFileName(m_RunTarget).GetPath());
    if (wxFileName::DirExists(m_RunTarget))
        workingdir.Replace(_("$dir"),wxFileName(m_RunTarget).GetFullPath());

    if (Manager::Get()->GetMacrosManager())
    {
        Manager::Get()->GetMacrosManager()->RecalcVars(0, 0, 0); // hack to force-update macros
        Manager::Get()->GetMacrosManager()->ReplaceMacros(commandstr);
        Manager::Get()->GetMacrosManager()->ReplaceMacros(workingdir);
    }
    wxString olddir=wxGetCwd();
    if (setdir && workingdir!=_T(""))
    {
        if (!wxSetWorkingDirectory(workingdir))
        {
            LogMessage(_("Tools Plus Plugin: Can't change to working directory to ")+workingdir);
            return;
        }
    }

    LogMessage(wxString::Format(_("Launching '%s': %s (in %s)"), consolename.c_str(), commandstr.c_str(), workingdir.c_str()));

    if (windowed)
    {
        wxArrayString astr;
        m_shellmgr->LaunchProcess(commandstr,consolename,_("Piped Process Control"),astr);
        ShowConsole();
    } else if (console)
    {
        wxString cmdline;
#ifndef __WXMSW__
        // for non-win platforms, use m_ConsoleTerm to run the console app
        wxString term = Manager::Get()->GetConfigManager(_T("app"))->Read(_T("/console_terminal"), DEFAULT_CONSOLE_TERM);
        term.Replace(_T("$TITLE"), _T("'") + consolename + _T("'"));
        cmdline<< term << _T(" ");
        #define CONSOLE_RUNNER "cb_console_runner"
#else
        #define CONSOLE_RUNNER "cb_console_runner.exe"
#endif
        wxString baseDir = ConfigManager::GetExecutableFolder();
        if (wxFileExists(baseDir + wxT("/" CONSOLE_RUNNER)))
            cmdline << baseDir << wxT("/" CONSOLE_RUNNER " ");
        cmdline<<commandstr;

        if (!wxExecute(cmdline))
            cbMessageBox(_("Command Launch Failed: ")+commandstr);
    }
    else
    {
        if (!wxExecute(commandstr))
            cbMessageBox(_("Command Launch Failed: ")+commandstr);
    }
    wxSetWorkingDirectory(olddir);
}
コード例 #27
0
ファイル: procutils.cpp プロジェクト: HTshandou/codelite
bool ProcUtils::Shell(const wxString &programConsoleCommand)
{
    wxString cmd;
#ifdef __WXMSW__
    wxChar *shell = wxGetenv(wxT("COMSPEC"));
    if ( !shell ) {
        shell = (wxChar*) wxT("\\COMMAND.COM");
    }

    // just the shell
    cmd = shell;
#elif defined(__WXMAC__)
    wxString path = wxGetCwd();
    cmd = wxString( wxT("osascript -e 'tell application \"Terminal\"' -e 'activate' -e 'do script with command \"cd ") + path + wxT("\"' -e 'end tell'") );
#else //non-windows
    //try to locate the configured terminal
    wxString terminal;
    wxString where;
    wxArrayString tokens;
    wxArrayString configuredTerminal;
    /*if (Locate(wxT("gnome-terminal"), where)) {
    	terminal = where;
    } else if (Locate(wxT("konsole"), where)) {
    	wxString path = wxGetCwd();
    	terminal << where << wxT(" --workdir \"") << path << wxT("\"");
    } else if (Locate(wxT("terminal"), where)) {
    	terminal = where;
    } else if (Locate(wxT("lxterminal"), where)) {
    	terminal = where;
    } else if (Locate(wxT("xterm"), where)) {
    	terminal = where;
    }
    cmd = terminal;*/
    terminal = wxT ( "xterm" );
    if ( !programConsoleCommand.IsEmpty() ) {
        tokens = wxStringTokenize ( programConsoleCommand, wxT ( " " ), wxTOKEN_STRTOK );
        if ( !tokens.IsEmpty() ) {
            configuredTerminal = wxStringTokenize ( tokens.Item(0), wxT ( "/" ), wxTOKEN_STRTOK );
            if ( !configuredTerminal.IsEmpty() ) {
                terminal = configuredTerminal.Last();
                tokens.Clear();
                configuredTerminal.Clear();
            }
        }
    }
    if ( Locate ( terminal, where ) ) {
        if ( terminal == wxT("konsole") ) {
            wxString path = wxGetCwd();
            terminal.Clear();
            terminal << where << wxT(" --workdir \"") << path << wxT("\"");
        } else {
            terminal = where;
        }
    } else {
        return false;
    }
    cmd = terminal;
    terminal.Clear();
#endif
    return wxExecute(cmd, wxEXEC_ASYNC) != 0;
}
コード例 #28
0
ファイル: plugins.cpp プロジェクト: AnnaSkawinska/pgadmin3
wxWindow *pluginUtilityFactory::StartDialog(frmMain *form, pgObject *obj)
{
	wxString execCmd = command;
	wxArrayString environment = set_env;

	// Remember this as the last plugin used
	form->SetLastPluginUtility(this);

	// Replace all the place holders with appropriate values
	if (HaveDatabase(obj))
	{
		execCmd.Replace(wxT("$$HOSTNAME"), obj->GetConnection()->GetHostName());
		execCmd.Replace(wxT("$$HOSTADDR"), obj->GetConnection()->GetHostName());
		execCmd.Replace(wxT("$$PORT"), NumToStr((long)obj->GetConnection()->GetPort()));
		execCmd.Replace(wxT("$$SSLMODE"), obj->GetConnection()->GetSslModeName());
		execCmd.Replace(wxT("$$DATABASE"), obj->GetConnection()->GetDbname());
		execCmd.Replace(wxT("$$USERNAME"), obj->GetConnection()->GetUser());
		execCmd.Replace(wxT("$$PASSWORD"), obj->GetConnection()->GetPassword());

		// Set the PGPASSWORD variable if required.
		if (set_password && !obj->GetConnection()->GetPassword().IsEmpty())
			wxSetEnv(wxT("PGPASSWORD"), obj->GetConnection()->GetPassword());

		// Pass the SSL settings via the environment
		switch (obj->GetConnection()->GetSslMode())
		{
			case 1:
				wxSetEnv(wxT("PGREQUIRESSL"), wxT("1"));
				break;
			case 2:
				wxSetEnv(wxT("PGREQUIRESSL"), wxT("0"));
				break;
		}

		wxSetEnv(wxT("PGSSLMODE"), obj->GetConnection()->GetSslModeName());
		wxSetEnv(wxT("PGSSLCERT"), obj->GetConnection()->GetSSLCert());
		wxSetEnv(wxT("PGSSLKEY"), obj->GetConnection()->GetSSLKey());
		wxSetEnv(wxT("PGSSLROOTCERT"), obj->GetConnection()->GetSSLRootCert());
		wxSetEnv(wxT("PGSSLCRL"), obj->GetConnection()->GetSSLCrl());
	}
	else
	{
		// Blank the rest
		execCmd.Replace(wxT("$$HOSTNAME"), wxEmptyString);
		execCmd.Replace(wxT("$$HOSTADDR"), wxEmptyString);
		execCmd.Replace(wxT("$$PORT"), wxEmptyString);
		execCmd.Replace(wxT("$$SSLMODE"), wxEmptyString);
		execCmd.Replace(wxT("$$DATABASE"), wxEmptyString);
		execCmd.Replace(wxT("$$USERNAME"), wxEmptyString);
		execCmd.Replace(wxT("$$PASSWORD"), wxEmptyString);
	}

	// Name
	if (obj && obj->IsCollection())
		execCmd.Replace(wxT("$$OBJECTNAME"), wxT("*"));
	else if (obj)
		execCmd.Replace(wxT("$$OBJECTNAME"), obj->GetName());
	else
		execCmd.Replace(wxT("$$OBJECTNAME"), wxEmptyString);

	// Object type
	if (obj && obj->GetFactory())
		execCmd.Replace(wxT("$$OBJECTTYPE"), wxString(obj->GetFactory()->GetTypeName()).Upper());
	else
		execCmd.Replace(wxT("$$OBJECTTYPE"), wxEmptyString);

	// Schema
	if (obj)
	{
		if (obj->GetMetaType() == PGM_SCHEMA)
			execCmd.Replace(wxT("$$SCHEMA"), obj->GetName());
		else if (obj->GetSchema())
			execCmd.Replace(wxT("$$SCHEMA"), obj->GetSchema()->GetName());
	}
	else
		execCmd.Replace(wxT("$$SCHEMA"), wxEmptyString);

	// Table
	if (obj)
	{
		if (obj->GetMetaType() == PGM_TABLE || obj->GetMetaType() == GP_PARTITION)
			execCmd.Replace(wxT("$$TABLE"), obj->GetName());
		else if (obj->GetTable())
			execCmd.Replace(wxT("$$TABLE"), obj->GetTable()->GetName());
	}
	else
		execCmd.Replace(wxT("$$TABLE"), wxEmptyString);

	// Directory substitutions
	execCmd.Replace(wxT("$$BINDIR"), loadPath);
	execCmd.Replace(wxT("$$WORKINGDIR"), wxGetCwd());
	execCmd.Replace(wxT("$$PGBINDIR"), settings->GetPostgresqlPath());
	execCmd.Replace(wxT("$$EDBBINDIR"), settings->GetEnterprisedbPath());
	execCmd.Replace(wxT("$$SLONYBINDIR"), settings->GetSlonyPath());

	// set Environment variable.
	for (size_t i = 0 ; i < environment.GetCount() ; i++)
	{
		wxString str = environment.Item(i);
		wxSetEnv(str.BeforeFirst('='), str.AfterFirst('='));
	}

	// Let's go!!
	if (wxExecute(execCmd) == 0)
	{
		wxLogError(_("Failed to execute plugin %s (%s)"), title.c_str(), command.c_str());
	}

	// Reset the environment variables set by us
	wxUnsetEnv(wxT("PGPASSWORD"));
	wxUnsetEnv(wxT("PGSSLMODE"));
	wxUnsetEnv(wxT("PGREQUIRESSL"));
	wxUnsetEnv(wxT("PGSSLCERT"));
	wxUnsetEnv(wxT("PGSSLKEY"));
	wxUnsetEnv(wxT("PGSSLROOTCERT"));
	wxUnsetEnv(wxT("PGSSLCRL"));

	return 0;
}
コード例 #29
0
/*****************************************************************************
* Routine to save an EESchema file.											 *
* FileSave controls how the file is to be saved - under what name.			 *
* Returns TRUE if the file has been saved.									 *
*****************************************************************************/
bool WinEDA_SchematicFrame::SaveEEFile(BASE_SCREEN *Window, int FileSave)
{
wxString msg;
wxString Name, BakName;
const wxChar **LibNames;
char * layer, *width;
int ii, shape;
bool Failed = FALSE;
EDA_BaseStruct *Phead;
Ki_PageDescr * PlotSheet;
FILE *f;
wxString dirbuf;

	if ( Window == NULL ) Window = ActiveScreen;

	/* If no name exists in the window yet - save as new. */
	if( Window->m_FileName.IsEmpty() ) FileSave = FILE_SAVE_NEW;

	switch (FileSave)
	{
		case FILE_SAVE_AS:
			dirbuf = wxGetCwd() + STRING_DIR_SEP;
			Name = MakeFileName(dirbuf, Window->m_FileName, g_SchExtBuffer);
			/* Rename the old file to a '.bak' one: */
			BakName = Name;
			if ( wxFileExists(Name) )
			{
				ChangeFileNameExt(BakName, wxT(".bak"));
				wxRemoveFile(BakName);	/* delete Old .bak file */
				if( ! wxRenameFile(Name, BakName) )
				{
					DisplayError(this, wxT("Warning: unable to rename old file"), 10);
				}
			}
			break;

		case FILE_SAVE_NEW:
		{
			wxString mask = wxT("*") + g_SchExtBuffer;
			Name = EDA_FileSelector(_("Schematic files:"),
					wxEmptyString,					/* Chemin par defaut */
					Window->m_FileName,				/* nom fichier par defaut, et resultat */
					g_SchExtBuffer,		/* extension par defaut */
					mask,				/* Masque d'affichage */
					this,
					wxSAVE,
					FALSE
					);
			if ( Name.IsEmpty() ) return FALSE;

			Window->m_FileName = Name;
			dirbuf = wxGetCwd() + STRING_DIR_SEP;
			Name = MakeFileName(dirbuf, Name, g_SchExtBuffer);

			break;
		}

		default: break;
	}

	if ((f = wxFopen(Name, wxT("wt"))) == NULL)
	{
		msg = _("Failed to create file ") + Name;
		DisplayError(this, msg);
		return FALSE;
	}

	msg = _("Save file ") + Name;
	Affiche_Message(msg);

	LibNames = GetLibNames();
	BakName.Empty();	// temporary buffer!
	for (ii = 0; LibNames[ii] != NULL; ii++)
	{
		if (ii > 0) BakName += wxT(",");
		BakName += LibNames[ii];
	}
	MyFree( LibNames);

	if (fprintf(f, "%s %s %d\n", EESCHEMA_FILE_STAMP,
		SCHEMATIC_HEAD_STRING, EESCHEMA_VERSION) == EOF ||
		fprintf(f, "LIBS:%s\n", CONV_TO_UTF8(BakName)) == EOF)
	{
		DisplayError(this, _("File write operation failed."));
		fclose(f);
		return FALSE;
	}

	Window->ClrModify();

	SaveLayers(f);
	/* Sauvegarde des dimensions du schema, des textes du cartouche.. */
	
	PlotSheet = Window->m_CurrentSheet;
	fprintf(f,"$Descr %s %d %d\n",CONV_TO_UTF8(PlotSheet->m_Name),
			PlotSheet->m_Size.x, PlotSheet->m_Size.y);

	fprintf(f,"Sheet %d %d\n",Window->m_SheetNumber, Window->m_NumberOfSheet);
	fprintf(f,"Title \"%s\"\n",CONV_TO_UTF8(Window->m_Title));
	fprintf(f,"Date \"%s\"\n",CONV_TO_UTF8(Window->m_Date));
	fprintf(f,"Rev \"%s\"\n",CONV_TO_UTF8(Window->m_Revision));
	fprintf(f,"Comp \"%s\"\n",CONV_TO_UTF8(Window->m_Company));
	fprintf(f,"Comment1 \"%s\"\n", CONV_TO_UTF8(Window->m_Commentaire1));
	fprintf(f,"Comment2 \"%s\"\n", CONV_TO_UTF8(Window->m_Commentaire2));
	fprintf(f,"Comment3 \"%s\"\n", CONV_TO_UTF8(Window->m_Commentaire3));
	fprintf(f,"Comment4 \"%s\"\n", CONV_TO_UTF8(Window->m_Commentaire4));

	fprintf(f,"$EndDescr\n");

	/* Sauvegarde des elements du dessin */
	Phead = Window->EEDrawList;
	while (Phead)
		{
		switch(Phead->m_StructType)
			{
			case DRAW_LIB_ITEM_STRUCT_TYPE:		  /* Its a library item. */
				SavePartDescr( f, (EDA_SchComponentStruct *) Phead);
				break;

			case DRAW_SHEET_STRUCT_TYPE:	   /* Its a Sheet item. */
				SaveSheetDescr( f, (DrawSheetStruct *) Phead);
				break;

			case DRAW_SEGMENT_STRUCT_TYPE:		 /* Its a Segment item. */
				#undef STRUCT
				#define STRUCT ((EDA_DrawLineStruct *) Phead)
				layer = "Notes"; width = "Line";
				if (STRUCT->m_Layer == LAYER_WIRE) layer = "Wire";
				if (STRUCT->m_Layer == LAYER_BUS) layer = "Bus";
				if( STRUCT->m_Width != GR_NORM_WIDTH) layer = "Bus";
				if (fprintf(f, "Wire %s %s\n", layer, width ) == EOF)
					{
					Failed = TRUE; break;
					}
				if (fprintf(f, "\t%-4d %-4d %-4d %-4d\n",
						STRUCT->m_Start.x,STRUCT->m_Start.y,
						STRUCT->m_End.x,STRUCT->m_End.y) == EOF)
					{
					Failed = TRUE; break;
					}
				break;

			case DRAW_BUSENTRY_STRUCT_TYPE:		 /* Its a Raccord item. */
				#undef STRUCT
				#define STRUCT ((DrawBusEntryStruct *) Phead)
				layer = "Wire"; width = "Line";
				if (STRUCT->m_Layer == LAYER_BUS)
					{
					layer = "Bus"; width = "Bus";
					}

				if (fprintf(f, "Entry %s %s\n", layer, width) == EOF)
					{
					Failed = TRUE; break;
					}
				if( fprintf(f, "\t%-4d %-4d %-4d %-4d\n",
						STRUCT->m_Pos.x,STRUCT->m_Pos.y,
						STRUCT->m_End().x,STRUCT->m_End().y) == EOF)
						{
						Failed = TRUE; break;
						}
				break;

			case DRAW_POLYLINE_STRUCT_TYPE:		  /* Its a polyline item. */
				#undef STRUCT
				#define STRUCT ((DrawPolylineStruct *) Phead)
				layer = "Notes"; width = "Line";
				if (STRUCT->m_Layer == LAYER_WIRE) layer = "Wire";
				if (STRUCT->m_Layer == LAYER_BUS) layer = "Bus";
				if( STRUCT->m_Width != GR_NORM_WIDTH) width = "Bus";
				if (fprintf(f, "Poly %s %s %d\n",
							width, layer, STRUCT->m_NumOfPoints) == EOF)
					{
					Failed = TRUE; break;
					}
				for (ii = 0; ii < STRUCT->m_NumOfPoints; ii++)
					{
					if (fprintf(f, "\t%-4d %-4d\n",
						STRUCT->m_Points[ii*2],
						STRUCT->m_Points[ii*2+1]) == EOF)
						{
						Failed = TRUE;
						break;
						}
					}
				break;

			case DRAW_JUNCTION_STRUCT_TYPE:	/* Its a connection item. */
				#undef STRUCT
				#define STRUCT ((DrawJunctionStruct *) Phead)
				if (fprintf(f, "Connection ~ %-4d %-4d\n",
					STRUCT->m_Pos.x, STRUCT->m_Pos.y) == EOF)
					{
					Failed = TRUE;
					}
				break;

			case DRAW_NOCONNECT_STRUCT_TYPE:	/* Its a NoConnection item. */
				#undef STRUCT
				#define STRUCT ((DrawNoConnectStruct *) Phead)
				if (fprintf(f, "NoConn ~ %-4d %-4d\n",
					STRUCT->m_Pos.x, STRUCT->m_Pos.y) == EOF)
					{
					Failed = TRUE;
					}
				break;

			case DRAW_TEXT_STRUCT_TYPE:			/* Its a text item. */
				#undef STRUCT
				#define STRUCT ((DrawTextStruct *) Phead)
				if (fprintf(f, "Text Notes %-4d %-4d %-4d %-4d ~\n%s\n",
						STRUCT->m_Pos.x, STRUCT->m_Pos.y,
						STRUCT->m_Orient, STRUCT->m_Size.x,
						CONV_TO_UTF8(STRUCT->m_Text)) == EOF)
					Failed = TRUE;
				break;


			case DRAW_LABEL_STRUCT_TYPE:		/* Its a label item. */
				#undef STRUCT
				#define STRUCT ((DrawLabelStruct *) Phead)
				shape = '~';
				if (fprintf(f, "Text Label %-4d %-4d %-4d %-4d %c\n%s\n",
						STRUCT->m_Pos.x, STRUCT->m_Pos.y,
						STRUCT->m_Orient, STRUCT->m_Size.x, shape,
						CONV_TO_UTF8(STRUCT->m_Text)) == EOF)
					Failed = TRUE;
				break;


			case DRAW_GLOBAL_LABEL_STRUCT_TYPE: /* Its a Global label item. */
				#undef STRUCT
				#define STRUCT ((DrawGlobalLabelStruct *) Phead)
				shape = STRUCT->m_Shape;
			if (fprintf(f, "Text GLabel %-4d %-4d %-4d %-4d %s\n%s\n",
						STRUCT->m_Pos.x, STRUCT->m_Pos.y,
						STRUCT->m_Orient,	STRUCT->m_Size.x,
						SheetLabelType[shape],
						CONV_TO_UTF8(STRUCT->m_Text)) == EOF)
					Failed = TRUE;
				break;

			case DRAW_MARKER_STRUCT_TYPE:	/* Its a marker item. */
				#undef STRUCT
				#define STRUCT ((DrawMarkerStruct *) Phead)
				if( STRUCT->GetComment() ) msg = STRUCT->GetComment();
				else msg.Empty();
				if (fprintf(f, "Kmarq %c %-4d %-4d \"%s\" F=%X\n",
								(int) STRUCT->m_Type + 'A',
								STRUCT->m_Pos.x, STRUCT->m_Pos.y,
								CONV_TO_UTF8(msg), STRUCT->m_MarkFlags) == EOF)
					{
					Failed = TRUE;
					}
				break;

			case DRAW_SHEETLABEL_STRUCT_TYPE :
			case DRAW_PICK_ITEM_STRUCT_TYPE :
				break;

			default:
				break;
			}

		if (Failed)
			{
			DisplayError(this, _("File write operation failed."));
			break;
			}

		Phead = Phead->Pnext;
		}
	if (fprintf(f, "$EndSCHEMATC\n") == EOF) Failed = TRUE;

	fclose(f);

	if (FileSave == FILE_SAVE_NEW) Window->m_FileName = Name;

	return !Failed;
}
コード例 #30
0
ファイル: plugins.cpp プロジェクト: AnnaSkawinska/pgadmin3
void frmMain::LoadPluginUtilities()
{
	if (pluginsDir.IsEmpty())
		return;

	PluginUtility *util = new PluginUtility;
	ClearPluginUtility(util);

	// Loop through all the ini files we find in the directory.
	wxString iniFile;
	wxDir iniDir(pluginsDir);

	if (!iniDir.IsOpened())
		return;

	wxLogInfo(wxT("Loading plugin ini files from %s"), pluginsDir.c_str());

	bool cont = iniDir.GetFirst(&iniFile, wxT("*.ini"), wxDIR_FILES);

	while(cont)
	{
		// Load the config file
		wxFileName utilIni(pluginsDir + wxT("/") + iniFile);
		if (!utilIni.FileExists())
		{
			cont = iniDir.GetNext(&iniFile);
			continue;
		}

		wxLogInfo(wxT("Loading plugin utilities from %s"), utilIni.GetFullPath().c_str());
		wxString brCfg = FileRead(utilIni.GetFullPath());

		wxStringTokenizer tkz(brCfg, wxT("\r\n"));

		// Loop round the lines in the file. Everytime we find a new 'Title' value
		// we create the current plugin and start a new one
		while(tkz.HasMoreTokens())
		{
			wxString token = tkz.GetNextToken();

			if (token.Trim() == wxEmptyString || token.StartsWith(wxT(";")))
				continue;

			// Separator
			if (token.Lower().StartsWith(wxT("[separator]")))
			{
				// Add the previous app if required.
				AddPluginUtility(util);
				pluginsMenu->AppendSeparator();
			}

			// Title
			if (token.Lower().StartsWith(wxT("title=")))
			{
				// Add the previous app if required.
				AddPluginUtility(util);
				util->title = token.AfterFirst('=').Trim();
			}

			// Command
			if (token.Lower().StartsWith(wxT("command=")))
				util->command = token.AfterFirst('=').Trim();

			// Description
			if (token.Lower().StartsWith(wxT("description=")))
				util->description = token.AfterFirst('=').Trim();

			// KeyFile
			if (token.Lower().StartsWith(wxT("keyfile=")))
			{
				wxString keyfile = token.AfterFirst('=').Trim();

				// Substitute path placeholders
				keyfile.Replace(wxT("$$BINDIR"), loadPath);
				keyfile.Replace(wxT("$$WORKINGDIR"), wxGetCwd());
				keyfile.Replace(wxT("$$PGBINDIR"), settings->GetPostgresqlPath());
				keyfile.Replace(wxT("$$EDBBINDIR"), settings->GetEnterprisedbPath());
				keyfile.Replace(wxT("$$SLONYBINDIR"), settings->GetSlonyPath());

				util->keyfile = keyfile;
			}

			// Platform
			if (token.Lower().StartsWith(wxT("platform=")))
				util->platform = token.AfterFirst('=').Trim();

			// Server types
			if (token.Lower().StartsWith(wxT("servertype=")))
			{
				util->server_types.Clear();

				// This is a comma delimited list of values going into an array.
				wxStringTokenizer valueTkz(token.AfterFirst('='), wxT(","));

				while(valueTkz.HasMoreTokens())
					util->server_types.Add(valueTkz.GetNextToken());
			}

			// Database
			if (token.Lower().StartsWith(wxT("database=")))
			{
				if (token.AfterFirst('=').Trim().Lower() == wxT("yes"))
					util->database = true;
				else
					util->database = false;
			}

			// Applies to
			if (token.Lower().StartsWith(wxT("appliesto=")))
			{
				util->applies_to.Clear();

				// This is a comma delimited list of values going into an array.
				wxStringTokenizer valueTkz(token.AfterFirst('='), wxT(","));

				while(valueTkz.HasMoreTokens())
					util->applies_to.Add(valueTkz.GetNextToken());
			}

			// Set password
			if (token.Lower().StartsWith(wxT("setpassword="******"yes"))
					util->set_password = true;
				else
					util->set_password = false;
			}
			// Environment
			if (token.Lower().StartsWith(wxT("environment=")))
			{
				util->set_env.Clear();

				// This is a comma delimited list of values going into an array.
				wxStringTokenizer valueTkz(token.AfterFirst('='), wxT(","));

				while(valueTkz.HasMoreTokens())
					util->set_env.Add(valueTkz.GetNextToken());
			}
		}

		// Add the last app if required.
		AddPluginUtility(util);

		// Get the next file
		cont = iniDir.GetNext(&iniFile);
	}

	if (util)
		delete util;
}