]> git.saurik.com Git - wxWidgets.git/blob - samples/exec/exec.cpp
e8483a828aefd5fe4ffa049c3a3e8409a05fcbd2
[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 OnExecWithPipe(wxCommandEvent& event);
90
91 void OnDDEExec(wxCommandEvent& event);
92
93 void OnAbout(wxCommandEvent& event);
94
95 // polling output of async processes
96 void OnIdle(wxIdleEvent& event);
97
98 // for MyPipedProcess
99 void OnProcessTerminated(MyPipedProcess *process);
100 wxListBox *GetLogListBox() const { return m_lbox; }
101
102 private:
103 void ShowOutput(const wxString& cmd,
104 const wxArrayString& output,
105 const wxString& title);
106
107 wxString m_cmdLast;
108
109 wxListBox *m_lbox;
110
111 MyProcessesArray m_running;
112
113 // any class wishing to process wxWindows events must use this macro
114 DECLARE_EVENT_TABLE()
115 };
116
117 // This is the handler for process termination events
118 class MyProcess : public wxProcess
119 {
120 public:
121 MyProcess(MyFrame *parent, const wxString& cmd)
122 : wxProcess(parent), m_cmd(cmd)
123 {
124 m_parent = parent;
125 }
126
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
129 // cases
130 virtual void OnTerminate(int pid, int status);
131
132 protected:
133 MyFrame *m_parent;
134 wxString m_cmd;
135 };
136
137 // A specialization of MyProcess for redirecting the output
138 class MyPipedProcess : public MyProcess
139 {
140 public:
141 MyPipedProcess(MyFrame *parent, const wxString& cmd)
142 : MyProcess(parent, cmd)
143 {
144 Redirect();
145 }
146
147 virtual void OnTerminate(int pid, int status);
148
149 virtual bool HasInput();
150 };
151
152 // A version of MyPipedProcess which also sends input to the stdin of the
153 // child process
154 class MyPipedProcess2 : public MyPipedProcess
155 {
156 public:
157 MyPipedProcess2(MyFrame *parent, const wxString& cmd, const wxString& input)
158 : MyPipedProcess(parent, cmd), m_input(input)
159 {
160 }
161
162 virtual bool HasInput();
163
164 private:
165 wxString m_input;
166 };
167
168 // ----------------------------------------------------------------------------
169 // constants
170 // ----------------------------------------------------------------------------
171
172 // IDs for the controls and the menu commands
173 enum
174 {
175 // menu items
176 Exec_Quit = 100,
177 Exec_ClearLog,
178 Exec_SyncExec = 200,
179 Exec_AsyncExec,
180 Exec_Shell,
181 Exec_DDEExec,
182 Exec_Redirect,
183 Exec_Pipe,
184 Exec_About = 300
185 };
186
187 static const wxChar *DIALOG_TITLE = _T("Exec sample");
188
189 // ----------------------------------------------------------------------------
190 // event tables and other macros for wxWindows
191 // ----------------------------------------------------------------------------
192
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)
199
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)
205
206 EVT_MENU(Exec_DDEExec, MyFrame::OnDDEExec)
207
208 EVT_MENU(Exec_About, MyFrame::OnAbout)
209
210 EVT_IDLE(MyFrame::OnIdle)
211 END_EVENT_TABLE()
212
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
217 // not wxApp)
218 IMPLEMENT_APP(MyApp)
219
220 // ============================================================================
221 // implementation
222 // ============================================================================
223
224 // ----------------------------------------------------------------------------
225 // the application class
226 // ----------------------------------------------------------------------------
227
228 // `Main program' equivalent: the program execution "starts" here
229 bool MyApp::OnInit()
230 {
231 // Create the main application window
232 MyFrame *frame = new MyFrame(_T("Exec wxWindows sample"),
233 wxDefaultPosition, wxSize(500, 140));
234
235 // Show it and tell the application that it's our main window
236 frame->Show(TRUE);
237 SetTopWindow(frame);
238
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.
242 return TRUE;
243 }
244
245 // ----------------------------------------------------------------------------
246 // main frame
247 // ----------------------------------------------------------------------------
248
249 // frame constructor
250 MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
251 : wxFrame((wxFrame *)NULL, -1, title, pos, size)
252 {
253 #ifdef __WXMAC__
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;
257 #endif
258
259 // create a menu bar
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"));
265
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"));
278
279 #ifdef __WINDOWS__
280 execMenu->AppendSeparator();
281 execMenu->Append(Exec_DDEExec, _T("Execute command via &DDE...\tCtrl-D"));
282 #endif
283
284 wxMenu *helpMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
285 helpMenu->Append(Exec_About, _T("&About...\tF1"), _T("Show about dialog"));
286
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"));
292
293 // ... and attach this menu bar to the frame
294 SetMenuBar(menuBar);
295
296 // create the listbox in which we will show misc messages as they come
297 m_lbox = new wxListBox(this, -1);
298
299 #if wxUSE_STATUSBAR
300 // create a status bar just for fun (by default with 1 pane only)
301 CreateStatusBar();
302 SetStatusText(_T("Welcome to wxWindows exec sample!"));
303 #endif // wxUSE_STATUSBAR
304 }
305
306
307 // event handlers
308
309 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
310 {
311 // TRUE is to force the frame to close
312 Close(TRUE);
313 }
314
315 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
316 {
317 m_lbox->Clear();
318 }
319
320 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
321 {
322 wxMessageBox(_T("Exec sample\n© 2000 Vadim Zeitlin"),
323 _T("About Exec"), wxOK | wxICON_INFORMATION, this);
324 }
325
326 void MyFrame::OnSyncExec(wxCommandEvent& WXUNUSED(event))
327 {
328 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
329 DIALOG_TITLE,
330 m_cmdLast);
331
332 if ( !cmd )
333 return;
334
335 wxLogStatus(_T("'%s' is running please wait..."), cmd.c_str());
336
337 int code = wxExecute(cmd, TRUE /* sync */);
338
339 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
340 cmd.c_str(), code);
341 m_cmdLast = cmd;
342 }
343
344 void MyFrame::OnAsyncExec(wxCommandEvent& WXUNUSED(event))
345 {
346 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
347 DIALOG_TITLE,
348 m_cmdLast);
349
350 if ( !cmd )
351 return;
352
353 wxProcess *process = new MyProcess(this, cmd);
354 long pid = wxExecute(cmd, FALSE /* async */, process);
355 if ( !pid )
356 {
357 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
358
359 delete process;
360 }
361 else
362 {
363 wxLogStatus(_T("Process %ld (%s) launched."), pid, cmd.c_str());
364
365 m_cmdLast = cmd;
366 }
367 }
368
369 void MyFrame::OnShell(wxCommandEvent& WXUNUSED(event))
370 {
371 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
372 DIALOG_TITLE,
373 m_cmdLast);
374
375 if ( !cmd )
376 return;
377
378 int code = wxShell(cmd);
379 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
380 cmd.c_str(), code);
381 m_cmdLast = cmd;
382 }
383
384 void MyFrame::OnExecWithRedirect(wxCommandEvent& WXUNUSED(event))
385 {
386 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
387 DIALOG_TITLE,
388 m_cmdLast);
389
390 if ( !cmd )
391 return;
392
393 bool sync;
394 switch ( wxMessageBox(_T("Execute it synchronously?"),
395 _T("Exec question"),
396 wxYES_NO | wxCANCEL | wxICON_QUESTION, this) )
397 {
398 case wxYES:
399 sync = TRUE;
400 break;
401
402 case wxNO:
403 sync = FALSE;
404 break;
405
406 default:
407 return;
408 }
409
410 if ( sync )
411 {
412 wxArrayString output, errors;
413 int code = wxExecute(cmd, output, errors);
414 wxLogStatus(_T("command '%s' terminated with exit code %d."),
415 cmd.c_str(), code);
416
417 if ( code != -1 )
418 {
419 ShowOutput(cmd, output, _T("Output"));
420 ShowOutput(cmd, errors, _T("Errors"));
421 }
422 }
423 else // async exec
424 {
425 MyPipedProcess *process = new MyPipedProcess(this, cmd);
426 if ( !wxExecute(cmd, FALSE /* async */, process) )
427 {
428 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
429
430 delete process;
431 }
432 else
433 {
434 m_running.Add(process);
435 }
436 }
437
438 m_cmdLast = cmd;
439 }
440
441 void MyFrame::OnExecWithPipe(wxCommandEvent& WXUNUSED(event))
442 {
443 if ( !m_cmdLast )
444 m_cmdLast = _T("tr [a-z] [A-Z]");
445
446 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
447 DIALOG_TITLE,
448 m_cmdLast);
449
450 if ( !cmd )
451 return;
452
453 wxString input = wxGetTextFromUser(_T("Enter the string to send to it: "),
454 DIALOG_TITLE);
455 if ( !input )
456 return;
457
458 // always execute the filter asynchronously
459 MyPipedProcess2 *process = new MyPipedProcess2(this, cmd, input);
460 int pid = wxExecute(cmd, FALSE /* async */, process);
461 if ( pid )
462 {
463 wxLogStatus(_T("Process %ld (%s) launched."), pid, cmd.c_str());
464
465 m_running.Add(process);
466 }
467 else
468 {
469 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
470
471 delete process;
472 }
473
474 m_cmdLast = cmd;
475 }
476
477 void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
478 {
479 #ifdef __WINDOWS__
480 wxString server = wxGetTextFromUser(_T("Server to connect to:"),
481 DIALOG_TITLE, _T("IExplore"));
482 if ( !server )
483 return;
484
485 wxString topic = wxGetTextFromUser(_T("DDE topic:"),
486 DIALOG_TITLE, _T("WWW_OpenURL"));
487 if ( !topic )
488 return;
489
490 wxString cmd = wxGetTextFromUser(_T("DDE command:"),
491 DIALOG_TITLE,
492 _T("\"file:F:\\wxWindows\\samples\\"
493 "image\\horse.gif\",,-1,,,,,"));
494 if ( !cmd )
495 return;
496
497 wxDDEClient client;
498 wxConnectionBase *conn = client.MakeConnection("", server, topic);
499 if ( !conn )
500 {
501 wxLogError(_T("Failed to connect to the DDE server '%s'."),
502 server.c_str());
503 }
504 else
505 {
506 if ( !conn->Execute(cmd) )
507 {
508 wxLogError(_T("Failed to execute command '%s' via DDE."),
509 cmd.c_str());
510 }
511 else
512 {
513 wxLogStatus(_T("Successfully executed DDE command"));
514 }
515 }
516 #endif // __WINDOWS__
517 }
518
519 // input polling
520 void MyFrame::OnIdle(wxIdleEvent& event)
521 {
522 size_t count = m_running.GetCount();
523 for ( size_t n = 0; n < count; n++ )
524 {
525 if ( m_running[n]->HasInput() )
526 {
527 event.RequestMore();
528 }
529 }
530 }
531
532 void MyFrame::OnProcessTerminated(MyPipedProcess *process)
533 {
534 m_running.Remove(process);
535 }
536
537
538 void MyFrame::ShowOutput(const wxString& cmd,
539 const wxArrayString& output,
540 const wxString& title)
541 {
542 size_t count = output.GetCount();
543 if ( !count )
544 return;
545
546 m_lbox->Append(wxString::Format(_T("--- %s of '%s' ---"),
547 title.c_str(), cmd.c_str()));
548
549 for ( size_t n = 0; n < count; n++ )
550 {
551 m_lbox->Append(output[n]);
552 }
553
554 m_lbox->Append(_T("--- End of output ---"));
555 }
556
557 // ----------------------------------------------------------------------------
558 // MyProcess
559 // ----------------------------------------------------------------------------
560
561 void MyProcess::OnTerminate(int pid, int status)
562 {
563 wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
564 pid, m_cmd.c_str(), status);
565
566 // we're not needed any more
567 delete this;
568 }
569
570 // ----------------------------------------------------------------------------
571 // MyPipedProcess
572 // ----------------------------------------------------------------------------
573
574 bool MyPipedProcess::HasInput()
575 {
576 bool hasInput = FALSE;
577
578 wxInputStream& is = *GetInputStream();
579 if ( !is.Eof() )
580 {
581 wxTextInputStream tis(is);
582
583 // this assumes that the output is always line buffered
584 wxString msg;
585 msg << m_cmd << _T(" (stdout): ") << tis.ReadLine();
586
587 m_parent->GetLogListBox()->Append(msg);
588
589 hasInput = TRUE;
590 }
591
592 wxInputStream& es = *GetErrorStream();
593 if ( !es.Eof() )
594 {
595 wxTextInputStream tis(es);
596
597 // this assumes that the output is always line buffered
598 wxString msg;
599 msg << m_cmd << _T(" (stderr): ") << tis.ReadLine();
600
601 m_parent->GetLogListBox()->Append(msg);
602
603 hasInput = TRUE;
604 }
605
606 return hasInput;
607 }
608
609 void MyPipedProcess::OnTerminate(int pid, int status)
610 {
611 // show the rest of the output
612 while ( HasInput() )
613 ;
614
615 m_parent->OnProcessTerminated(this);
616
617 MyProcess::OnTerminate(pid, status);
618 }
619
620 // ----------------------------------------------------------------------------
621 // MyPipedProcess2
622 // ----------------------------------------------------------------------------
623
624 bool MyPipedProcess2::HasInput()
625 {
626 if ( !!m_input )
627 {
628 wxTextOutputStream os(*GetOutputStream());
629 os.WriteString(m_input);
630
631 CloseOutput();
632 m_input.clear();
633
634 // call us once again - may be we'll have output
635 return TRUE;
636 }
637
638 return MyPipedProcess::HasInput();
639 }