]> git.saurik.com Git - wxWidgets.git/blob - samples/exec/exec.cpp
Loads of framework and dll fixes
[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 wxLogStatus(_T("'%s' is running please wait..."), cmd.c_str());
314
315 int code = wxExecute(cmd, TRUE /* sync */);
316
317 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
318 cmd.c_str(), code);
319 m_cmdLast = cmd;
320 }
321
322 void MyFrame::OnAsyncExec(wxCommandEvent& WXUNUSED(event))
323 {
324 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
325 DIALOG_TITLE,
326 m_cmdLast);
327
328 if ( !cmd )
329 return;
330
331 wxProcess *process = new MyProcess(this, cmd);
332 long pid = wxExecute(cmd, FALSE /* async */, process);
333 if ( !pid )
334 {
335 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
336
337 delete process;
338 }
339 else
340 {
341 wxLogStatus(_T("Process %ld (%s) launched."), pid, cmd.c_str());
342
343 m_cmdLast = cmd;
344 }
345 }
346
347 void MyFrame::OnShell(wxCommandEvent& WXUNUSED(event))
348 {
349 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
350 DIALOG_TITLE,
351 m_cmdLast);
352
353 if ( !cmd )
354 return;
355
356 int code = wxShell(cmd);
357 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
358 cmd.c_str(), code);
359 m_cmdLast = cmd;
360 }
361
362 void MyFrame::OnExecWithRedirect(wxCommandEvent& WXUNUSED(event))
363 {
364 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
365 DIALOG_TITLE,
366 m_cmdLast);
367
368 if ( !cmd )
369 return;
370
371 bool sync;
372 switch ( wxMessageBox(_T("Execute it synchronously?"),
373 _T("Exec question"),
374 wxYES_NO | wxCANCEL | wxICON_QUESTION, this) )
375 {
376 case wxYES:
377 sync = TRUE;
378 break;
379
380 case wxNO:
381 sync = FALSE;
382 break;
383
384 default:
385 return;
386 }
387
388 if ( sync )
389 {
390 wxArrayString output;
391 int code = wxExecute(cmd, output);
392 wxLogStatus(_T("command '%s' terminated with exit code %d."),
393 cmd.c_str(), code);
394
395 if ( code != -1 )
396 {
397 m_lbox->Append(wxString::Format(_T("--- Output of '%s' ---"),
398 cmd.c_str()));
399
400 size_t count = output.GetCount();
401 for ( size_t n = 0; n < count; n++ )
402 {
403 m_lbox->Append(output[n]);
404 }
405 }
406 }
407 else // async exec
408 {
409 MyPipedProcess *process = new MyPipedProcess(this, cmd);
410 if ( !wxExecute(cmd, FALSE /* async */, process) )
411 {
412 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
413
414 delete process;
415 }
416 else
417 {
418 m_running.Add(process);
419 }
420 }
421
422 m_cmdLast = cmd;
423 }
424
425 void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
426 {
427 #ifdef __WINDOWS__
428 wxString server = wxGetTextFromUser(_T("Server to connect to:"),
429 DIALOG_TITLE, _T("IExplore"));
430 if ( !server )
431 return;
432
433 wxString topic = wxGetTextFromUser(_T("DDE topic:"),
434 DIALOG_TITLE, _T("WWW_OpenURL"));
435 if ( !topic )
436 return;
437
438 wxString cmd = wxGetTextFromUser(_T("DDE command:"),
439 DIALOG_TITLE,
440 _T("\"file:F:\\wxWindows\\samples\\"
441 "image\\horse.gif\",,-1,,,,,"));
442 if ( !cmd )
443 return;
444
445 wxDDEClient client;
446 wxConnectionBase *conn = client.MakeConnection("", server, topic);
447 if ( !conn )
448 {
449 wxLogError(_T("Failed to connect to the DDE server '%s'."),
450 server.c_str());
451 }
452 else
453 {
454 if ( !conn->Execute(cmd) )
455 {
456 wxLogError(_T("Failed to execute command '%s' via DDE."),
457 cmd.c_str());
458 }
459 else
460 {
461 wxLogStatus(_T("Successfully executed DDE command"));
462 }
463 }
464 #endif // __WINDOWS__
465 }
466
467 // input polling
468 void MyFrame::OnIdle(wxIdleEvent& event)
469 {
470 size_t count = m_running.GetCount();
471 for ( size_t n = 0; n < count; n++ )
472 {
473 if ( m_running[n]->HasInput() )
474 {
475 event.RequestMore();
476 }
477 }
478 }
479
480 // ----------------------------------------------------------------------------
481 // MyProcess
482 // ----------------------------------------------------------------------------
483
484 void MyProcess::OnTerminate(int pid, int status)
485 {
486 wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
487 pid, m_cmd.c_str(), status);
488
489 // we're not needed any more
490 delete this;
491 }
492
493 // ----------------------------------------------------------------------------
494 // MyPipedProcess
495 // ----------------------------------------------------------------------------
496
497 bool MyPipedProcess::HasInput()
498 {
499 wxInputStream& is = *GetInputStream();
500 if ( !is.Eof() )
501 {
502 wxTextInputStream tis(is);
503
504 // this assumes that the output is always line buffered
505 wxString msg;
506 msg << m_cmd << _T(": ") << tis.ReadLine();
507
508 m_parent->GetLogListBox()->Append(msg);
509
510 return TRUE;
511 }
512 else
513 {
514 return FALSE;
515 }
516 }
517
518 void MyPipedProcess::OnTerminate(int pid, int status)
519 {
520 // show the rest of the output
521 while ( HasInput() )
522 ;
523
524 m_parent->OnProcessTerminated(this);
525
526 MyProcess::OnTerminate(pid, status);
527 }