1. wxProcess changes to make capturing subprocess output easier (and more
[wxWidgets.git] / samples / exec / exec.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: exec.cpp
3 // Purpose: exec sample demonstrates wxExecute and related functions
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 15.01.00
7 // RCS-ID: $Id$
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "exec.cpp"
22 #pragma interface "exec.cpp"
23 #endif
24
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
27
28 #ifdef __BORLANDC__
29 #pragma hdrstop
30 #endif
31
32 // for all others, include the necessary headers (this file is usually all you
33 // need because it includes almost all "standard" wxWindows headers
34 #ifndef WX_PRECOMP
35 #include "wx/app.h"
36 #include "wx/frame.h"
37 #include "wx/utils.h"
38 #include "wx/menu.h"
39 #include "wx/msgdlg.h"
40 #include "wx/textdlg.h"
41 #include "wx/listbox.h"
42 #endif
43
44 #include "wx/txtstrm.h"
45
46 #include "wx/process.h"
47
48 #ifdef __WINDOWS__
49 #include "wx/dde.h"
50 #endif // __WINDOWS__
51
52 // ----------------------------------------------------------------------------
53 // private classes
54 // ----------------------------------------------------------------------------
55
56 // Define a new application type, each program should derive a class from wxApp
57 class MyApp : public wxApp
58 {
59 public:
60 // override base class virtuals
61 // ----------------------------
62
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();
67 };
68
69 // Define an array of process pointers used by MyFrame
70 class MyPipedProcess;
71 WX_DEFINE_ARRAY(MyPipedProcess *, MyProcessesArray);
72
73 // Define a new frame type: this is going to be our main frame
74 class MyFrame : public wxFrame
75 {
76 public:
77 // ctor(s)
78 MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
79
80 // event handlers (these functions should _not_ be virtual)
81 void OnQuit(wxCommandEvent& event);
82
83 void OnClear(wxCommandEvent& event);
84
85 void OnSyncExec(wxCommandEvent& event);
86 void OnAsyncExec(wxCommandEvent& event);
87 void OnShell(wxCommandEvent& event);
88 void OnExecWithRedirect(wxCommandEvent& event);
89 void OnDDEExec(wxCommandEvent& event);
90
91 void OnAbout(wxCommandEvent& event);
92
93 // polling output of async processes
94 void OnIdle(wxIdleEvent& event);
95
96 // for MyPipedProcess
97 void OnProcessTerminated(MyPipedProcess *process)
98 { m_running.Remove(process); }
99 wxListBox *GetLogListBox() const { return m_lbox; }
100
101 private:
102 wxString m_cmdLast;
103
104 wxListBox *m_lbox;
105
106 MyProcessesArray m_running;
107
108 // any class wishing to process wxWindows events must use this macro
109 DECLARE_EVENT_TABLE()
110 };
111
112 // This is the handler for process termination events
113 class MyProcess : public wxProcess
114 {
115 public:
116 MyProcess(MyFrame *parent, const wxString& cmd)
117 : wxProcess(parent), m_cmd(cmd)
118 {
119 m_parent = parent;
120 }
121
122 // instead of overriding this virtual function we might as well process the
123 // event from it in the frame class - this might be more convenient in some
124 // cases
125 virtual void OnTerminate(int pid, int status);
126
127 protected:
128 MyFrame *m_parent;
129 wxString m_cmd;
130 };
131
132 // A specialization of MyProcess for redirecting the output
133 class MyPipedProcess : public MyProcess
134 {
135 public:
136 MyPipedProcess(MyFrame *parent, const wxString& cmd)
137 : MyProcess(parent, cmd)
138 {
139 Redirect();
140 }
141
142 virtual void OnTerminate(int pid, int status);
143
144 bool HasInput();
145 };
146
147 // ----------------------------------------------------------------------------
148 // constants
149 // ----------------------------------------------------------------------------
150
151 // IDs for the controls and the menu commands
152 enum
153 {
154 // menu items
155 Exec_Quit = 100,
156 Exec_ClearLog,
157 Exec_SyncExec = 200,
158 Exec_AsyncExec,
159 Exec_Shell,
160 Exec_DDEExec,
161 Exec_Redirect,
162 Exec_About = 300
163 };
164
165 static const wxChar *DIALOG_TITLE = _T("Exec sample");
166
167 // ----------------------------------------------------------------------------
168 // event tables and other macros for wxWindows
169 // ----------------------------------------------------------------------------
170
171 // the event tables connect the wxWindows events with the functions (event
172 // handlers) which process them. It can be also done at run-time, but for the
173 // simple menu events like this the static method is much simpler.
174 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
175 EVT_MENU(Exec_Quit, MyFrame::OnQuit)
176 EVT_MENU(Exec_ClearLog, MyFrame::OnClear)
177
178 EVT_MENU(Exec_SyncExec, MyFrame::OnSyncExec)
179 EVT_MENU(Exec_AsyncExec, MyFrame::OnAsyncExec)
180 EVT_MENU(Exec_Shell, MyFrame::OnShell)
181 EVT_MENU(Exec_Redirect, MyFrame::OnExecWithRedirect)
182 EVT_MENU(Exec_DDEExec, MyFrame::OnDDEExec)
183
184 EVT_MENU(Exec_About, MyFrame::OnAbout)
185
186 EVT_IDLE(MyFrame::OnIdle)
187 END_EVENT_TABLE()
188
189 // Create a new application object: this macro will allow wxWindows to create
190 // the application object during program execution (it's better than using a
191 // static object for many reasons) and also declares the accessor function
192 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
193 // not wxApp)
194 IMPLEMENT_APP(MyApp)
195
196 // ============================================================================
197 // implementation
198 // ============================================================================
199
200 // ----------------------------------------------------------------------------
201 // the application class
202 // ----------------------------------------------------------------------------
203
204 // `Main program' equivalent: the program execution "starts" here
205 bool MyApp::OnInit()
206 {
207 // Create the main application window
208 MyFrame *frame = new MyFrame(_T("Exec wxWindows sample"),
209 wxDefaultPosition, wxSize(500, 140));
210
211 // Show it and tell the application that it's our main window
212 frame->Show(TRUE);
213 SetTopWindow(frame);
214
215 // success: wxApp::OnRun() will be called which will enter the main message
216 // loop and the application will run. If we returned FALSE here, the
217 // application would exit immediately.
218 return TRUE;
219 }
220
221 // ----------------------------------------------------------------------------
222 // main frame
223 // ----------------------------------------------------------------------------
224
225 // frame constructor
226 MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
227 : wxFrame((wxFrame *)NULL, -1, title, pos, size)
228 {
229 #ifdef __WXMAC__
230 // we need this in order to allow the about menu relocation, since ABOUT is
231 // not the default id of the about menu
232 wxApp::s_macAboutMenuItemId = Exec_About;
233 #endif
234
235 // set the frame icon
236 #ifndef __WXGTK__
237 SetIcon(wxICON(mondrian));
238 #endif
239
240 // create a menu bar
241 wxMenu *menuFile = new wxMenu(_T(""), wxMENU_TEAROFF);
242 menuFile->Append(Exec_ClearLog, _T("&Clear log\tCtrl-C"),
243 _T("Clear the log window"));
244 menuFile->AppendSeparator();
245 menuFile->Append(Exec_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
246
247 wxMenu *execMenu = new wxMenu;
248 execMenu->Append(Exec_SyncExec, _T("Sync &execution...\tCtrl-E"),
249 _T("Launch a program and return when it terminates"));
250 execMenu->Append(Exec_AsyncExec, _T("&Async execution...\tCtrl-A"),
251 _T("Launch a program and return immediately"));
252 execMenu->Append(Exec_Shell, _T("Execute &shell command...\tCtrl-S"),
253 _T("Launch a shell and execute a command in it"));
254 execMenu->Append(Exec_Redirect, _T("Capture command &output...\tCtrl-O"),
255 _T("Launch a program and capture its output"));
256
257 #ifdef __WINDOWS__
258 execMenu->AppendSeparator();
259 execMenu->Append(Exec_DDEExec, _T("Execute command via &DDE...\tCtrl-D"));
260 #endif
261
262 wxMenu *helpMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
263 helpMenu->Append(Exec_About, _T("&About...\tF1"), _T("Show about dialog"));
264
265 // now append the freshly created menu to the menu bar...
266 wxMenuBar *menuBar = new wxMenuBar();
267 menuBar->Append(menuFile, _T("&File"));
268 menuBar->Append(execMenu, _T("&Exec"));
269 menuBar->Append(helpMenu, _T("&Help"));
270
271 // ... and attach this menu bar to the frame
272 SetMenuBar(menuBar);
273
274 // create the listbox in which we will show misc messages as they come
275 m_lbox = new wxListBox(this, -1);
276
277 #if wxUSE_STATUSBAR
278 // create a status bar just for fun (by default with 1 pane only)
279 CreateStatusBar();
280 SetStatusText(_T("Welcome to wxWindows exec sample!"));
281 #endif // wxUSE_STATUSBAR
282 }
283
284
285 // event handlers
286
287 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
288 {
289 // TRUE is to force the frame to close
290 Close(TRUE);
291 }
292
293 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
294 {
295 m_lbox->Clear();
296 }
297
298 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
299 {
300 wxMessageBox(_T("Exec sample\n© 2000 Vadim Zeitlin"),
301 _T("About Exec"), wxOK | wxICON_INFORMATION, this);
302 }
303
304 void MyFrame::OnSyncExec(wxCommandEvent& WXUNUSED(event))
305 {
306 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
307 DIALOG_TITLE,
308 m_cmdLast);
309
310 if ( !cmd )
311 return;
312
313 int code = wxExecute(cmd, TRUE /* sync */);
314 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
315 cmd.c_str(), code);
316 m_cmdLast = cmd;
317 }
318
319 void MyFrame::OnAsyncExec(wxCommandEvent& WXUNUSED(event))
320 {
321 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
322 DIALOG_TITLE,
323 m_cmdLast);
324
325 if ( !cmd )
326 return;
327
328 wxProcess *process = new MyProcess(this, cmd);
329 if ( !wxExecute(cmd, FALSE /* async */, process) )
330 {
331 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
332
333 delete process;
334 }
335 else
336 {
337 m_cmdLast = cmd;
338 }
339 }
340
341 void MyFrame::OnShell(wxCommandEvent& WXUNUSED(event))
342 {
343 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
344 DIALOG_TITLE,
345 m_cmdLast);
346
347 if ( !cmd )
348 return;
349
350 int code = wxShell(cmd);
351 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
352 cmd.c_str(), code);
353 m_cmdLast = cmd;
354 }
355
356 void MyFrame::OnExecWithRedirect(wxCommandEvent& WXUNUSED(event))
357 {
358 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
359 DIALOG_TITLE,
360 m_cmdLast);
361
362 if ( !cmd )
363 return;
364
365 bool sync;
366 switch ( wxMessageBox(_T("Execute it synchronously?"),
367 _T("Exec question"),
368 wxYES_NO | wxCANCEL | wxICON_QUESTION, this) )
369 {
370 case wxYES:
371 sync = TRUE;
372 break;
373
374 case wxNO:
375 sync = FALSE;
376 break;
377
378 default:
379 return;
380 }
381
382 if ( sync )
383 {
384 wxArrayString output;
385 int code = wxExecute(cmd, output);
386 wxLogStatus(_T("command '%s' terminated with exit code %d."),
387 cmd.c_str(), code);
388
389 if ( code != -1 )
390 {
391 m_lbox->Append(wxString::Format(_T("--- Output of '%s' ---"),
392 cmd.c_str()));
393
394 size_t count = output.GetCount();
395 for ( size_t n = 0; n < count; n++ )
396 {
397 m_lbox->Append(output[n]);
398 }
399 }
400 }
401 else // async exec
402 {
403 MyPipedProcess *process = new MyPipedProcess(this, cmd);
404 if ( !wxExecute(cmd, FALSE /* async */, process) )
405 {
406 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
407
408 delete process;
409 }
410 else
411 {
412 m_running.Add(process);
413 }
414 }
415
416 m_cmdLast = cmd;
417 }
418
419 void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
420 {
421 #ifdef __WINDOWS__
422 wxString server = wxGetTextFromUser(_T("Server to connect to:"),
423 DIALOG_TITLE, _T("IExplore"));
424 if ( !server )
425 return;
426
427 wxString topic = wxGetTextFromUser(_T("DDE topic:"),
428 DIALOG_TITLE, _T("WWW_OpenURL"));
429 if ( !topic )
430 return;
431
432 wxString cmd = wxGetTextFromUser(_T("DDE command:"),
433 DIALOG_TITLE,
434 _T("\"file:F:\\wxWindows\\samples\\"
435 "image\\horse.gif\",,-1,,,,,"));
436 if ( !cmd )
437 return;
438
439 wxDDEClient client;
440 wxConnectionBase *conn = client.MakeConnection("", server, topic);
441 if ( !conn )
442 {
443 wxLogError(_T("Failed to connect to the DDE server '%s'."),
444 server.c_str());
445 }
446 else
447 {
448 if ( !conn->Execute(cmd) )
449 {
450 wxLogError(_T("Failed to execute command '%s' via DDE."),
451 cmd.c_str());
452 }
453 else
454 {
455 wxLogStatus(_T("Successfully executed DDE command"));
456 }
457 }
458 #endif // __WINDOWS__
459 }
460
461 // input polling
462 void MyFrame::OnIdle(wxIdleEvent& event)
463 {
464 size_t count = m_running.GetCount();
465 for ( size_t n = 0; n < count; n++ )
466 {
467 if ( m_running[n]->HasInput() )
468 {
469 event.RequestMore();
470 }
471 }
472 }
473
474 // ----------------------------------------------------------------------------
475 // MyProcess
476 // ----------------------------------------------------------------------------
477
478 void MyProcess::OnTerminate(int pid, int status)
479 {
480 wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
481 pid, m_cmd.c_str(), status);
482
483 // we're not needed any more
484 delete this;
485 }
486
487 // ----------------------------------------------------------------------------
488 // MyPipedProcess
489 // ----------------------------------------------------------------------------
490
491 bool MyPipedProcess::HasInput()
492 {
493 wxInputStream& is = *GetInputStream();
494 if ( !is.Eof() )
495 {
496 wxTextInputStream tis(is);
497
498 // this assumes that the output is always line buffered
499 wxString msg;
500 msg << m_cmd << _T(": ") << tis.ReadLine();
501
502 m_parent->GetLogListBox()->Append(msg);
503
504 return TRUE;
505 }
506 else
507 {
508 return FALSE;
509 }
510 }
511
512 void MyPipedProcess::OnTerminate(int pid, int status)
513 {
514 // show the rest of the output
515 while ( HasInput() )
516 ;
517
518 m_parent->OnProcessTerminated(this);
519
520 MyProcess::OnTerminate(pid, status);
521 }