1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: exec sample demonstrates wxExecute and related functions
4 // Author: Vadim Zeitlin
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "exec.cpp"
22 #pragma interface "exec.cpp"
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
32 // for all others, include the necessary headers (this file is usually all you
33 // need because it includes almost all "standard" wxWindows headers
39 #include "wx/msgdlg.h"
40 #include "wx/textdlg.h"
41 #include "wx/listbox.h"
44 #include "wx/txtstrm.h"
46 #include "wx/process.h"
52 // ----------------------------------------------------------------------------
54 // ----------------------------------------------------------------------------
56 // Define a new application type, each program should derive a class from wxApp
57 class MyApp
: public wxApp
60 // override base class virtuals
61 // ----------------------------
63 // this one is called on application startup and is a good place for the app
64 // initialization (doing it here and not in the ctor allows to have an error
65 // return: if OnInit() returns false, the application terminates)
66 virtual bool OnInit();
69 // Define an array of process pointers used by MyFrame
71 WX_DEFINE_ARRAY(MyPipedProcess
*, MyProcessesArray
);
73 // Define a new frame type: this is going to be our main frame
74 class MyFrame
: public wxFrame
78 MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
);
80 // event handlers (these functions should _not_ be virtual)
81 void OnQuit(wxCommandEvent
& event
);
83 void OnClear(wxCommandEvent
& event
);
85 void OnSyncExec(wxCommandEvent
& event
);
86 void OnAsyncExec(wxCommandEvent
& event
);
87 void OnShell(wxCommandEvent
& event
);
88 void OnExecWithRedirect(wxCommandEvent
& event
);
89 void OnExecWithPipe(wxCommandEvent
& event
);
91 void OnDDEExec(wxCommandEvent
& event
);
93 void OnAbout(wxCommandEvent
& event
);
95 // polling output of async processes
96 void OnIdle(wxIdleEvent
& event
);
99 void OnProcessTerminated(MyPipedProcess
*process
);
100 wxListBox
*GetLogListBox() const { return m_lbox
; }
103 void ShowOutput(const wxString
& cmd
,
104 const wxArrayString
& output
,
105 const wxString
& title
);
111 MyProcessesArray m_running
;
113 // any class wishing to process wxWindows events must use this macro
114 DECLARE_EVENT_TABLE()
117 // This is the handler for process termination events
118 class MyProcess
: public wxProcess
121 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
122 : wxProcess(parent
), m_cmd(cmd
)
127 // instead of overriding this virtual function we might as well process the
128 // event from it in the frame class - this might be more convenient in some
130 virtual void OnTerminate(int pid
, int status
);
137 // A specialization of MyProcess for redirecting the output
138 class MyPipedProcess
: public MyProcess
141 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
142 : MyProcess(parent
, cmd
)
147 virtual void OnTerminate(int pid
, int status
);
149 virtual bool HasInput();
152 // A version of MyPipedProcess which also sends input to the stdin of the
154 class MyPipedProcess2
: public MyPipedProcess
157 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
158 : MyPipedProcess(parent
, cmd
), m_input(input
)
162 virtual bool HasInput();
168 // ----------------------------------------------------------------------------
170 // ----------------------------------------------------------------------------
172 // IDs for the controls and the menu commands
187 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
189 // ----------------------------------------------------------------------------
190 // event tables and other macros for wxWindows
191 // ----------------------------------------------------------------------------
193 // the event tables connect the wxWindows events with the functions (event
194 // handlers) which process them. It can be also done at run-time, but for the
195 // simple menu events like this the static method is much simpler.
196 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
197 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
198 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
200 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
201 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
202 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
203 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
204 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
206 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
208 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
210 EVT_IDLE(MyFrame::OnIdle
)
213 // Create a new application object: this macro will allow wxWindows to create
214 // the application object during program execution (it's better than using a
215 // static object for many reasons) and also declares the accessor function
216 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
220 // ============================================================================
222 // ============================================================================
224 // ----------------------------------------------------------------------------
225 // the application class
226 // ----------------------------------------------------------------------------
228 // `Main program' equivalent: the program execution "starts" here
231 // Create the main application window
232 MyFrame
*frame
= new MyFrame(_T("Exec wxWindows sample"),
233 wxDefaultPosition
, wxSize(500, 140));
235 // Show it and tell the application that it's our main window
239 // success: wxApp::OnRun() will be called which will enter the main message
240 // loop and the application will run. If we returned FALSE here, the
241 // application would exit immediately.
245 // ----------------------------------------------------------------------------
247 // ----------------------------------------------------------------------------
250 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
251 : wxFrame((wxFrame
*)NULL
, -1, title
, pos
, size
)
254 // we need this in order to allow the about menu relocation, since ABOUT is
255 // not the default id of the about menu
256 wxApp::s_macAboutMenuItemId
= Exec_About
;
260 wxMenu
*menuFile
= new wxMenu(_T(""), wxMENU_TEAROFF
);
261 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-C"),
262 _T("Clear the log window"));
263 menuFile
->AppendSeparator();
264 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
266 wxMenu
*execMenu
= new wxMenu
;
267 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
268 _T("Launch a program and return when it terminates"));
269 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
270 _T("Launch a program and return immediately"));
271 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
272 _T("Launch a shell and execute a command in it"));
273 execMenu
->AppendSeparator();
274 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
275 _T("Launch a program and capture its output"));
276 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command...\tCtrl-P"),
277 _T("Pipe a string through a filter"));
280 execMenu
->AppendSeparator();
281 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
284 wxMenu
*helpMenu
= new wxMenu(_T(""), wxMENU_TEAROFF
);
285 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
287 // now append the freshly created menu to the menu bar...
288 wxMenuBar
*menuBar
= new wxMenuBar();
289 menuBar
->Append(menuFile
, _T("&File"));
290 menuBar
->Append(execMenu
, _T("&Exec"));
291 menuBar
->Append(helpMenu
, _T("&Help"));
293 // ... and attach this menu bar to the frame
296 // create the listbox in which we will show misc messages as they come
297 m_lbox
= new wxListBox(this, -1);
300 // create a status bar just for fun (by default with 1 pane only)
302 SetStatusText(_T("Welcome to wxWindows exec sample!"));
303 #endif // wxUSE_STATUSBAR
309 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
311 // TRUE is to force the frame to close
315 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
320 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
322 wxMessageBox(_T("Exec sample\n© 2000 Vadim Zeitlin"),
323 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
326 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
328 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
335 wxLogStatus(_T("'%s' is running please wait..."), cmd
.c_str());
337 int code
= wxExecute(cmd
, TRUE
/* sync */);
339 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
344 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
346 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
353 wxProcess
*process
= new MyProcess(this, cmd
);
354 long pid
= wxExecute(cmd
, FALSE
/* async */, process
);
357 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
363 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
369 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
371 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
378 int code
= wxShell(cmd
);
379 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
384 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
386 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
394 switch ( wxMessageBox(_T("Execute it synchronously?"),
396 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
412 wxArrayString output
, errors
;
413 int code
= wxExecute(cmd
, output
, errors
);
414 wxLogStatus(_T("command '%s' terminated with exit code %d."),
419 ShowOutput(cmd
, output
, _T("Output"));
420 ShowOutput(cmd
, errors
, _T("Errors"));
425 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
426 if ( !wxExecute(cmd
, FALSE
/* async */, process
) )
428 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
434 m_running
.Add(process
);
441 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
444 m_cmdLast
= _T("tr [a-z] [A-Z]");
446 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
453 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
458 // always execute the filter asynchronously
459 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
460 int pid
= wxExecute(cmd
, FALSE
/* async */, process
);
463 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
465 m_running
.Add(process
);
469 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
477 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
480 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
481 DIALOG_TITLE
, _T("IExplore"));
485 wxString topic
= wxGetTextFromUser(_T("DDE topic:"),
486 DIALOG_TITLE
, _T("WWW_OpenURL"));
490 wxString cmd
= wxGetTextFromUser(_T("DDE command:"),
492 _T("\"file:F:\\wxWindows\\samples\\"
493 "image\\horse.gif\",,-1,,,,,"));
498 wxConnectionBase
*conn
= client
.MakeConnection("", server
, topic
);
501 wxLogError(_T("Failed to connect to the DDE server '%s'."),
506 if ( !conn
->Execute(cmd
) )
508 wxLogError(_T("Failed to execute command '%s' via DDE."),
513 wxLogStatus(_T("Successfully executed DDE command"));
516 #endif // __WINDOWS__
520 void MyFrame::OnIdle(wxIdleEvent
& event
)
522 size_t count
= m_running
.GetCount();
523 for ( size_t n
= 0; n
< count
; n
++ )
525 if ( m_running
[n
]->HasInput() )
532 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
534 m_running
.Remove(process
);
538 void MyFrame::ShowOutput(const wxString
& cmd
,
539 const wxArrayString
& output
,
540 const wxString
& title
)
542 size_t count
= output
.GetCount();
546 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
547 title
.c_str(), cmd
.c_str()));
549 for ( size_t n
= 0; n
< count
; n
++ )
551 m_lbox
->Append(output
[n
]);
554 m_lbox
->Append(_T("--- End of output ---"));
557 // ----------------------------------------------------------------------------
559 // ----------------------------------------------------------------------------
561 void MyProcess::OnTerminate(int pid
, int status
)
563 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
564 pid
, m_cmd
.c_str(), status
);
566 // we're not needed any more
570 // ----------------------------------------------------------------------------
572 // ----------------------------------------------------------------------------
574 bool MyPipedProcess::HasInput()
576 bool hasInput
= FALSE
;
578 wxInputStream
& is
= *GetInputStream();
581 wxTextInputStream
tis(is
);
583 // this assumes that the output is always line buffered
585 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
587 m_parent
->GetLogListBox()->Append(msg
);
592 wxInputStream
& es
= *GetErrorStream();
595 wxTextInputStream
tis(es
);
597 // this assumes that the output is always line buffered
599 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
601 m_parent
->GetLogListBox()->Append(msg
);
609 void MyPipedProcess::OnTerminate(int pid
, int status
)
611 // show the rest of the output
615 m_parent
->OnProcessTerminated(this);
617 MyProcess::OnTerminate(pid
, status
);
620 // ----------------------------------------------------------------------------
622 // ----------------------------------------------------------------------------
624 bool MyPipedProcess2::HasInput()
628 wxTextOutputStream
os(*GetOutputStream());
629 os
.WriteString(m_input
);
634 // call us once again - may be we'll have output
638 return MyPipedProcess::HasInput();