added demo of capturing program output - doesn't work very well though
[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 a new frame type: this is going to be our main frame
70 class MyFrame : public wxFrame
71 {
72 public:
73 // ctor(s)
74 MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
75
76 // event handlers (these functions should _not_ be virtual)
77 void OnQuit(wxCommandEvent& event);
78
79 void OnClear(wxCommandEvent& event);
80
81 void OnSyncExec(wxCommandEvent& event);
82 void OnAsyncExec(wxCommandEvent& event);
83 void OnShell(wxCommandEvent& event);
84 void OnExecWithRedirect(wxCommandEvent& event);
85 void OnDDEExec(wxCommandEvent& event);
86
87 void OnAbout(wxCommandEvent& event);
88
89 // for MyPipedProcess
90 wxListBox *GetLogListBox() const { return m_lbox; }
91
92 private:
93 wxString m_cmdLast;
94
95 wxListBox *m_lbox;
96
97 // any class wishing to process wxWindows events must use this macro
98 DECLARE_EVENT_TABLE()
99 };
100
101 // This is the handler for process termination events
102 class MyProcess : public wxProcess
103 {
104 public:
105 MyProcess(MyFrame *parent, const wxString& cmd)
106 : wxProcess(parent), m_cmd(cmd)
107 {
108 m_parent = parent;
109 }
110
111 // instead of overriding this virtual function we might as well process the
112 // event from it in the frame class - this might be more convenient in some
113 // cases
114 virtual void OnTerminate(int pid, int status);
115
116 protected:
117 MyFrame *m_parent;
118 wxString m_cmd;
119 };
120
121 // A specialization of MyProcess for redirecting the output
122 class MyPipedProcess : public MyProcess
123 {
124 public:
125 MyPipedProcess(MyFrame *parent, const wxString& cmd)
126 : MyProcess(parent, cmd)
127 {
128 m_needPipe = TRUE;
129 }
130
131 virtual void OnTerminate(int pid, int status);
132 };
133
134 // ----------------------------------------------------------------------------
135 // constants
136 // ----------------------------------------------------------------------------
137
138 // IDs for the controls and the menu commands
139 enum
140 {
141 // menu items
142 Exec_Quit = 100,
143 Exec_ClearLog,
144 Exec_SyncExec = 200,
145 Exec_AsyncExec,
146 Exec_Shell,
147 Exec_DDEExec,
148 Exec_Redirect,
149 Exec_About = 300
150 };
151
152 static const wxChar *DIALOG_TITLE = _T("Exec sample");
153
154 // ----------------------------------------------------------------------------
155 // event tables and other macros for wxWindows
156 // ----------------------------------------------------------------------------
157
158 // the event tables connect the wxWindows events with the functions (event
159 // handlers) which process them. It can be also done at run-time, but for the
160 // simple menu events like this the static method is much simpler.
161 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
162 EVT_MENU(Exec_Quit, MyFrame::OnQuit)
163 EVT_MENU(Exec_ClearLog, MyFrame::OnClear)
164
165 EVT_MENU(Exec_SyncExec, MyFrame::OnSyncExec)
166 EVT_MENU(Exec_AsyncExec, MyFrame::OnAsyncExec)
167 EVT_MENU(Exec_Shell, MyFrame::OnShell)
168 EVT_MENU(Exec_Redirect, MyFrame::OnExecWithRedirect)
169 EVT_MENU(Exec_DDEExec, MyFrame::OnDDEExec)
170
171 EVT_MENU(Exec_About, MyFrame::OnAbout)
172 END_EVENT_TABLE()
173
174 // Create a new application object: this macro will allow wxWindows to create
175 // the application object during program execution (it's better than using a
176 // static object for many reasons) and also declares the accessor function
177 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
178 // not wxApp)
179 IMPLEMENT_APP(MyApp)
180
181 // ============================================================================
182 // implementation
183 // ============================================================================
184
185 // ----------------------------------------------------------------------------
186 // the application class
187 // ----------------------------------------------------------------------------
188
189 // `Main program' equivalent: the program execution "starts" here
190 bool MyApp::OnInit()
191 {
192 // Create the main application window
193 MyFrame *frame = new MyFrame(_T("Exec wxWindows sample"),
194 wxDefaultPosition, wxSize(500, 140));
195
196 // Show it and tell the application that it's our main window
197 frame->Show(TRUE);
198 SetTopWindow(frame);
199
200 // success: wxApp::OnRun() will be called which will enter the main message
201 // loop and the application will run. If we returned FALSE here, the
202 // application would exit immediately.
203 return TRUE;
204 }
205
206 // ----------------------------------------------------------------------------
207 // main frame
208 // ----------------------------------------------------------------------------
209
210 // frame constructor
211 MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
212 : wxFrame((wxFrame *)NULL, -1, title, pos, size)
213 {
214 #ifdef __WXMAC__
215 // we need this in order to allow the about menu relocation, since ABOUT is
216 // not the default id of the about menu
217 wxApp::s_macAboutMenuItemId = Exec_About;
218 #endif
219
220 // set the frame icon
221 #ifndef __WXGTK__
222 SetIcon(wxICON(mondrian));
223 #endif
224
225 // create a menu bar
226 wxMenu *menuFile = new wxMenu(_T(""), wxMENU_TEAROFF);
227 menuFile->Append(Exec_ClearLog, _T("&Clear log\tCtrl-C"),
228 _T("Clear the log window"));
229 menuFile->AppendSeparator();
230 menuFile->Append(Exec_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
231
232 wxMenu *execMenu = new wxMenu;
233 execMenu->Append(Exec_SyncExec, _T("Sync &execution...\tCtrl-E"),
234 _T("Launch a program and return when it terminates"));
235 execMenu->Append(Exec_AsyncExec, _T("&Async execution...\tCtrl-A"),
236 _T("Launch a program and return immediately"));
237 execMenu->Append(Exec_Shell, _T("Execute &shell command...\tCtrl-S"),
238 _T("Launch a shell and execute a command in it"));
239 execMenu->Append(Exec_Redirect, _T("Capture command &output...\tCtrl-O"),
240 _T("Launch a program and capture its output"));
241
242 #ifdef __WINDOWS__
243 execMenu->AppendSeparator();
244 execMenu->Append(Exec_DDEExec, _T("Execute command via &DDE...\tCtrl-D"));
245 #endif
246
247 wxMenu *helpMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
248 helpMenu->Append(Exec_About, _T("&About...\tF1"), _T("Show about dialog"));
249
250 // now append the freshly created menu to the menu bar...
251 wxMenuBar *menuBar = new wxMenuBar();
252 menuBar->Append(menuFile, _T("&File"));
253 menuBar->Append(execMenu, _T("&Exec"));
254 menuBar->Append(helpMenu, _T("&Help"));
255
256 // ... and attach this menu bar to the frame
257 SetMenuBar(menuBar);
258
259 // create the listbox in which we will show misc messages as they come
260 m_lbox = new wxListBox(this, -1);
261
262 #if wxUSE_STATUSBAR
263 // create a status bar just for fun (by default with 1 pane only)
264 CreateStatusBar();
265 SetStatusText(_T("Welcome to wxWindows exec sample!"));
266 #endif // wxUSE_STATUSBAR
267 }
268
269
270 // event handlers
271
272 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
273 {
274 // TRUE is to force the frame to close
275 Close(TRUE);
276 }
277
278 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
279 {
280 m_lbox->Clear();
281 }
282
283 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
284 {
285 wxMessageBox(_T("Exec sample\n© 2000 Vadim Zeitlin"),
286 _T("About Exec"), wxOK | wxICON_INFORMATION, this);
287 }
288
289 void MyFrame::OnSyncExec(wxCommandEvent& WXUNUSED(event))
290 {
291 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
292 DIALOG_TITLE,
293 m_cmdLast);
294
295 if ( !cmd )
296 return;
297
298 int code = wxExecute(cmd, TRUE /* sync */);
299 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
300 cmd.c_str(), code);
301 m_cmdLast = cmd;
302 }
303
304 void MyFrame::OnAsyncExec(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 wxProcess *process = new MyProcess(this, cmd);
314 if ( !wxExecute(cmd, FALSE /* async */, process) )
315 {
316 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
317
318 delete process;
319 }
320 else
321 {
322 m_cmdLast = cmd;
323 }
324 }
325
326 void MyFrame::OnShell(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 int code = wxShell(cmd);
336 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
337 cmd.c_str(), code);
338 m_cmdLast = cmd;
339 }
340
341 void MyFrame::OnExecWithRedirect(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 wxProcess *process = new MyPipedProcess(this, cmd);
351 if ( !wxExecute(cmd, FALSE /* async */, process) )
352 {
353 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
354
355 delete process;
356 }
357 else
358 {
359 m_cmdLast = cmd;
360 }
361 }
362
363 void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
364 {
365 #ifdef __WINDOWS__
366 wxString server = wxGetTextFromUser(_T("Server to connect to:"),
367 DIALOG_TITLE, _T("IExplore"));
368 if ( !server )
369 return;
370
371 wxString topic = wxGetTextFromUser(_T("DDE topic:"),
372 DIALOG_TITLE, _T("WWW_OpenURL"));
373 if ( !topic )
374 return;
375
376 wxString cmd = wxGetTextFromUser(_T("DDE command:"),
377 DIALOG_TITLE,
378 _T("\"file:F:\\wxWindows\\samples\\"
379 "image\\horse.gif\",,-1,,,,,"));
380 if ( !cmd )
381 return;
382
383 wxDDEClient client;
384 wxConnectionBase *conn = client.MakeConnection("", server, topic);
385 if ( !conn )
386 {
387 wxLogError(_T("Failed to connect to the DDE server '%s'."),
388 server.c_str());
389 }
390 else
391 {
392 if ( !conn->Execute(cmd) )
393 {
394 wxLogError(_T("Failed to execute command '%s' via DDE."),
395 cmd.c_str());
396 }
397 else
398 {
399 wxLogStatus(_T("Successfully executed DDE command"));
400 }
401 }
402 #endif // __WINDOWS__
403 }
404
405 // ----------------------------------------------------------------------------
406 // MyProcess
407 // ----------------------------------------------------------------------------
408
409 void MyProcess::OnTerminate(int pid, int status)
410 {
411 wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
412 pid, m_cmd.c_str(), status);
413
414 // we're not needed any more
415 delete this;
416 }
417
418 void MyPipedProcess::OnTerminate(int pid, int status)
419 {
420 // show the program output
421 wxListBox *lbox = m_parent->GetLogListBox();
422 lbox->Append(wxString::Format(_T("--- Output of '%s' ---"), m_cmd.c_str()));
423
424 wxTextInputStream tis(*m_in_stream);
425 while ( !m_in_stream->LastError() )
426 {
427 lbox->Append(tis.ReadLine());
428 }
429
430 MyProcess::OnTerminate(pid, status);
431 }