]> git.saurik.com Git - wxWidgets.git/blob - samples/exec/exec.cpp
Fix cvs conflict.
[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 #include "wx/filedlg.h"
43 #endif
44
45 #include "wx/txtstrm.h"
46
47 #include "wx/process.h"
48
49 #include "wx/mimetype.h"
50
51 #ifdef __WINDOWS__
52 #include "wx/dde.h"
53 #endif // __WINDOWS__
54
55 // ----------------------------------------------------------------------------
56 // private classes
57 // ----------------------------------------------------------------------------
58
59 // Define a new application type, each program should derive a class from wxApp
60 class MyApp : public wxApp
61 {
62 public:
63 // override base class virtuals
64 // ----------------------------
65
66 // this one is called on application startup and is a good place for the app
67 // initialization (doing it here and not in the ctor allows to have an error
68 // return: if OnInit() returns false, the application terminates)
69 virtual bool OnInit();
70 };
71
72 // Define an array of process pointers used by MyFrame
73 class MyPipedProcess;
74 WX_DEFINE_ARRAY(MyPipedProcess *, MyProcessesArray);
75
76 // Define a new frame type: this is going to be our main frame
77 class MyFrame : public wxFrame
78 {
79 public:
80 // ctor(s)
81 MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
82
83 // event handlers (these functions should _not_ be virtual)
84 void OnQuit(wxCommandEvent& event);
85
86 void OnClear(wxCommandEvent& event);
87
88 void OnSyncExec(wxCommandEvent& event);
89 void OnAsyncExec(wxCommandEvent& event);
90 void OnShell(wxCommandEvent& event);
91 void OnExecWithRedirect(wxCommandEvent& event);
92 void OnExecWithPipe(wxCommandEvent& event);
93
94 void OnFileExec(wxCommandEvent& event);
95
96 void OnAbout(wxCommandEvent& event);
97
98 // polling output of async processes
99 void OnIdle(wxIdleEvent& event);
100
101 // for MyPipedProcess
102 void OnProcessTerminated(MyPipedProcess *process);
103 wxListBox *GetLogListBox() const { return m_lbox; }
104
105 private:
106 void ShowOutput(const wxString& cmd,
107 const wxArrayString& output,
108 const wxString& title);
109
110 void DoAsyncExec(const wxString& cmd);
111
112 // last command we executed
113 wxString m_cmdLast;
114
115 #ifdef __WINDOWS__
116 void OnDDEExec(wxCommandEvent& event);
117 void OnDDERequest(wxCommandEvent& event);
118
119 bool GetDDEServer();
120
121 // last params of a DDE transaction
122 wxString m_server,
123 m_topic,
124 m_cmdDde;
125 #endif // __WINDOWS__
126
127 wxListBox *m_lbox;
128
129 MyProcessesArray m_running;
130
131 // any class wishing to process wxWindows events must use this macro
132 DECLARE_EVENT_TABLE()
133 };
134
135 // This is the handler for process termination events
136 class MyProcess : public wxProcess
137 {
138 public:
139 MyProcess(MyFrame *parent, const wxString& cmd)
140 : wxProcess(parent), m_cmd(cmd)
141 {
142 m_parent = parent;
143 }
144
145 // instead of overriding this virtual function we might as well process the
146 // event from it in the frame class - this might be more convenient in some
147 // cases
148 virtual void OnTerminate(int pid, int status);
149
150 protected:
151 MyFrame *m_parent;
152 wxString m_cmd;
153 };
154
155 // A specialization of MyProcess for redirecting the output
156 class MyPipedProcess : public MyProcess
157 {
158 public:
159 MyPipedProcess(MyFrame *parent, const wxString& cmd)
160 : MyProcess(parent, cmd)
161 {
162 Redirect();
163 }
164
165 virtual void OnTerminate(int pid, int status);
166
167 virtual bool HasInput();
168 };
169
170 // A version of MyPipedProcess which also sends input to the stdin of the
171 // child process
172 class MyPipedProcess2 : public MyPipedProcess
173 {
174 public:
175 MyPipedProcess2(MyFrame *parent, const wxString& cmd, const wxString& input)
176 : MyPipedProcess(parent, cmd), m_input(input)
177 {
178 }
179
180 virtual bool HasInput();
181
182 private:
183 wxString m_input;
184 };
185
186 // ----------------------------------------------------------------------------
187 // constants
188 // ----------------------------------------------------------------------------
189
190 // IDs for the controls and the menu commands
191 enum
192 {
193 // menu items
194 Exec_Quit = 100,
195 Exec_ClearLog,
196 Exec_SyncExec = 200,
197 Exec_AsyncExec,
198 Exec_Shell,
199 Exec_OpenFile,
200 Exec_DDEExec,
201 Exec_DDERequest,
202 Exec_Redirect,
203 Exec_Pipe,
204 Exec_About = 300
205 };
206
207 static const wxChar *DIALOG_TITLE = _T("Exec sample");
208
209 // ----------------------------------------------------------------------------
210 // event tables and other macros for wxWindows
211 // ----------------------------------------------------------------------------
212
213 // the event tables connect the wxWindows events with the functions (event
214 // handlers) which process them. It can be also done at run-time, but for the
215 // simple menu events like this the static method is much simpler.
216 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
217 EVT_MENU(Exec_Quit, MyFrame::OnQuit)
218 EVT_MENU(Exec_ClearLog, MyFrame::OnClear)
219
220 EVT_MENU(Exec_SyncExec, MyFrame::OnSyncExec)
221 EVT_MENU(Exec_AsyncExec, MyFrame::OnAsyncExec)
222 EVT_MENU(Exec_Shell, MyFrame::OnShell)
223 EVT_MENU(Exec_Redirect, MyFrame::OnExecWithRedirect)
224 EVT_MENU(Exec_Pipe, MyFrame::OnExecWithPipe)
225
226 EVT_MENU(Exec_OpenFile, MyFrame::OnFileExec)
227
228 EVT_MENU(Exec_DDEExec, MyFrame::OnDDEExec)
229 EVT_MENU(Exec_DDERequest, MyFrame::OnDDERequest)
230
231 EVT_MENU(Exec_About, MyFrame::OnAbout)
232
233 EVT_IDLE(MyFrame::OnIdle)
234 END_EVENT_TABLE()
235
236 // Create a new application object: this macro will allow wxWindows to create
237 // the application object during program execution (it's better than using a
238 // static object for many reasons) and also declares the accessor function
239 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
240 // not wxApp)
241 IMPLEMENT_APP(MyApp)
242
243 // ============================================================================
244 // implementation
245 // ============================================================================
246
247 // ----------------------------------------------------------------------------
248 // the application class
249 // ----------------------------------------------------------------------------
250
251 // `Main program' equivalent: the program execution "starts" here
252 bool MyApp::OnInit()
253 {
254 // Create the main application window
255 MyFrame *frame = new MyFrame(_T("Exec wxWindows sample"),
256 wxDefaultPosition, wxSize(500, 140));
257
258 // Show it and tell the application that it's our main window
259 frame->Show(TRUE);
260 SetTopWindow(frame);
261
262 // success: wxApp::OnRun() will be called which will enter the main message
263 // loop and the application will run. If we returned FALSE here, the
264 // application would exit immediately.
265 return TRUE;
266 }
267
268 // ----------------------------------------------------------------------------
269 // main frame
270 // ----------------------------------------------------------------------------
271
272 // frame constructor
273 MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
274 : wxFrame((wxFrame *)NULL, -1, title, pos, size)
275 {
276 #ifdef __WXMAC__
277 // we need this in order to allow the about menu relocation, since ABOUT is
278 // not the default id of the about menu
279 wxApp::s_macAboutMenuItemId = Exec_About;
280 #endif
281
282 // create a menu bar
283 wxMenu *menuFile = new wxMenu(_T(""), wxMENU_TEAROFF);
284 menuFile->Append(Exec_ClearLog, _T("&Clear log\tCtrl-C"),
285 _T("Clear the log window"));
286 menuFile->AppendSeparator();
287 menuFile->Append(Exec_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
288
289 wxMenu *execMenu = new wxMenu;
290 execMenu->Append(Exec_SyncExec, _T("Sync &execution...\tCtrl-E"),
291 _T("Launch a program and return when it terminates"));
292 execMenu->Append(Exec_AsyncExec, _T("&Async execution...\tCtrl-A"),
293 _T("Launch a program and return immediately"));
294 execMenu->Append(Exec_Shell, _T("Execute &shell command...\tCtrl-S"),
295 _T("Launch a shell and execute a command in it"));
296 execMenu->AppendSeparator();
297 execMenu->Append(Exec_Redirect, _T("Capture command &output...\tCtrl-O"),
298 _T("Launch a program and capture its output"));
299 execMenu->Append(Exec_Pipe, _T("&Pipe through command...\tCtrl-P"),
300 _T("Pipe a string through a filter"));
301
302 execMenu->AppendSeparator();
303 execMenu->Append(Exec_OpenFile, _T("Open &file...\tCtrl-F"),
304 _T("Launch the command to open this kind of files"));
305 #ifdef __WINDOWS__
306 execMenu->AppendSeparator();
307 execMenu->Append(Exec_DDEExec, _T("Execute command via &DDE...\tCtrl-D"));
308 execMenu->Append(Exec_DDERequest, _T("Send DDE &request...\tCtrl-R"));
309 #endif
310
311 wxMenu *helpMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
312 helpMenu->Append(Exec_About, _T("&About...\tF1"), _T("Show about dialog"));
313
314 // now append the freshly created menu to the menu bar...
315 wxMenuBar *menuBar = new wxMenuBar();
316 menuBar->Append(menuFile, _T("&File"));
317 menuBar->Append(execMenu, _T("&Exec"));
318 menuBar->Append(helpMenu, _T("&Help"));
319
320 // ... and attach this menu bar to the frame
321 SetMenuBar(menuBar);
322
323 // create the listbox in which we will show misc messages as they come
324 m_lbox = new wxListBox(this, -1);
325 wxFont font(12, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL,
326 wxFONTWEIGHT_NORMAL);
327 if ( font.Ok() )
328 m_lbox->SetFont(font);
329
330 #if wxUSE_STATUSBAR
331 // create a status bar just for fun (by default with 1 pane only)
332 CreateStatusBar();
333 SetStatusText(_T("Welcome to wxWindows exec sample!"));
334 #endif // wxUSE_STATUSBAR
335 }
336
337
338 // event handlers
339
340 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
341 {
342 // TRUE is to force the frame to close
343 Close(TRUE);
344 }
345
346 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
347 {
348 m_lbox->Clear();
349 }
350
351 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
352 {
353 wxMessageBox(_T("Exec sample\n© 2000 Vadim Zeitlin"),
354 _T("About Exec"), wxOK | wxICON_INFORMATION, this);
355 }
356
357 void MyFrame::DoAsyncExec(const wxString& cmd)
358 {
359 wxProcess *process = new MyProcess(this, cmd);
360 long pid = wxExecute(cmd, FALSE /* async */, process);
361 if ( !pid )
362 {
363 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
364
365 delete process;
366 }
367 else
368 {
369 wxLogStatus(_T("Process %ld (%s) launched."), pid, cmd.c_str());
370
371 m_cmdLast = cmd;
372 }
373 }
374
375 void MyFrame::OnSyncExec(wxCommandEvent& WXUNUSED(event))
376 {
377 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
378 DIALOG_TITLE,
379 m_cmdLast);
380
381 if ( !cmd )
382 return;
383
384 wxLogStatus(_T("'%s' is running please wait..."), cmd.c_str());
385
386 int code = wxExecute(cmd, TRUE /* sync */);
387
388 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
389 cmd.c_str(), code);
390 m_cmdLast = cmd;
391 }
392
393 void MyFrame::OnAsyncExec(wxCommandEvent& WXUNUSED(event))
394 {
395 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
396 DIALOG_TITLE,
397 m_cmdLast);
398
399 if ( !cmd )
400 return;
401
402 DoAsyncExec(cmd);
403 }
404
405 void MyFrame::OnShell(wxCommandEvent& WXUNUSED(event))
406 {
407 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
408 DIALOG_TITLE,
409 m_cmdLast);
410
411 if ( !cmd )
412 return;
413
414 int code = wxShell(cmd);
415 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
416 cmd.c_str(), code);
417 m_cmdLast = cmd;
418 }
419
420 void MyFrame::OnExecWithRedirect(wxCommandEvent& WXUNUSED(event))
421 {
422 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
423 DIALOG_TITLE,
424 m_cmdLast);
425
426 if ( !cmd )
427 return;
428
429 bool sync;
430 switch ( wxMessageBox(_T("Execute it synchronously?"),
431 _T("Exec question"),
432 wxYES_NO | wxCANCEL | wxICON_QUESTION, this) )
433 {
434 case wxYES:
435 sync = TRUE;
436 break;
437
438 case wxNO:
439 sync = FALSE;
440 break;
441
442 default:
443 return;
444 }
445
446 if ( sync )
447 {
448 wxArrayString output, errors;
449 int code = wxExecute(cmd, output, errors);
450 wxLogStatus(_T("command '%s' terminated with exit code %d."),
451 cmd.c_str(), code);
452
453 if ( code != -1 )
454 {
455 ShowOutput(cmd, output, _T("Output"));
456 ShowOutput(cmd, errors, _T("Errors"));
457 }
458 }
459 else // async exec
460 {
461 MyPipedProcess *process = new MyPipedProcess(this, cmd);
462 if ( !wxExecute(cmd, FALSE /* async */, process) )
463 {
464 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
465
466 delete process;
467 }
468 else
469 {
470 m_running.Add(process);
471 }
472 }
473
474 m_cmdLast = cmd;
475 }
476
477 void MyFrame::OnExecWithPipe(wxCommandEvent& WXUNUSED(event))
478 {
479 if ( !m_cmdLast )
480 m_cmdLast = _T("tr [a-z] [A-Z]");
481
482 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
483 DIALOG_TITLE,
484 m_cmdLast);
485
486 if ( !cmd )
487 return;
488
489 wxString input = wxGetTextFromUser(_T("Enter the string to send to it: "),
490 DIALOG_TITLE);
491 if ( !input )
492 return;
493
494 // always execute the filter asynchronously
495 MyPipedProcess2 *process = new MyPipedProcess2(this, cmd, input);
496 int pid = wxExecute(cmd, FALSE /* async */, process);
497 if ( pid )
498 {
499 wxLogStatus(_T("Process %ld (%s) launched."), pid, cmd.c_str());
500
501 m_running.Add(process);
502 }
503 else
504 {
505 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
506
507 delete process;
508 }
509
510 m_cmdLast = cmd;
511 }
512
513 void MyFrame::OnFileExec(wxCommandEvent& event)
514 {
515 static wxString s_filename;
516
517 wxString filename = wxLoadFileSelector(_T("file"), _T(""), s_filename);
518 if ( !filename )
519 return;
520
521 s_filename = filename;
522
523 wxString ext = filename.AfterFirst(_T('.'));
524 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
525 if ( !ft )
526 {
527 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
528 ext.c_str());
529 return;
530 }
531
532 wxString cmd;
533 bool ok = ft->GetOpenCommand(&cmd,
534 wxFileType::MessageParameters(filename, _T("")));
535 delete ft;
536 if ( !ok )
537 {
538 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
539 ext.c_str());
540 return;
541 }
542
543 DoAsyncExec(cmd);
544 }
545
546 #ifdef __WINDOWS__
547
548 bool MyFrame::GetDDEServer()
549 {
550 wxString server = wxGetTextFromUser(_T("Server to connect to:"),
551 DIALOG_TITLE, m_server);
552 if ( !server )
553 return FALSE;
554
555 m_server = server;
556
557 wxString topic = wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE, m_topic);
558 if ( !topic )
559 return FALSE;
560
561 m_topic = topic;
562
563 wxString cmd = wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE, m_cmdDde);
564 if ( !cmd )
565 return FALSE;
566
567 m_cmdDde = cmd;
568
569 return TRUE;
570 }
571
572 void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
573 {
574 if ( !GetDDEServer() )
575 return;
576
577 wxDDEClient client;
578 wxConnectionBase *conn = client.MakeConnection("", m_server, m_topic);
579 if ( !conn )
580 {
581 wxLogError(_T("Failed to connect to the DDE server '%s'."),
582 m_server.c_str());
583 }
584 else
585 {
586 if ( !conn->Execute(m_cmdDde) )
587 {
588 wxLogError(_T("Failed to execute command '%s' via DDE."),
589 m_cmdDde.c_str());
590 }
591 else
592 {
593 wxLogStatus(_T("Successfully executed DDE command"));
594 }
595 }
596 }
597
598 void MyFrame::OnDDERequest(wxCommandEvent& WXUNUSED(event))
599 {
600 if ( !GetDDEServer() )
601 return;
602
603 wxDDEClient client;
604 wxConnectionBase *conn = client.MakeConnection("", m_server, m_topic);
605 if ( !conn )
606 {
607 wxLogError(_T("Failed to connect to the DDE server '%s'."),
608 m_server.c_str());
609 }
610 else
611 {
612 if ( !conn->Request(m_cmdDde) )
613 {
614 wxLogError(_T("Failed to send request '%s' via DDE."),
615 m_cmdDde.c_str());
616 }
617 else
618 {
619 wxLogStatus(_T("Successfully sent DDE request."));
620 }
621 }
622 }
623
624 #endif // __WINDOWS__
625
626 // input polling
627 void MyFrame::OnIdle(wxIdleEvent& event)
628 {
629 size_t count = m_running.GetCount();
630 for ( size_t n = 0; n < count; n++ )
631 {
632 if ( m_running[n]->HasInput() )
633 {
634 event.RequestMore();
635 }
636 }
637 }
638
639 void MyFrame::OnProcessTerminated(MyPipedProcess *process)
640 {
641 m_running.Remove(process);
642 }
643
644
645 void MyFrame::ShowOutput(const wxString& cmd,
646 const wxArrayString& output,
647 const wxString& title)
648 {
649 size_t count = output.GetCount();
650 if ( !count )
651 return;
652
653 m_lbox->Append(wxString::Format(_T("--- %s of '%s' ---"),
654 title.c_str(), cmd.c_str()));
655
656 for ( size_t n = 0; n < count; n++ )
657 {
658 m_lbox->Append(output[n]);
659 }
660
661 m_lbox->Append(_T("--- End of output ---"));
662 }
663
664 // ----------------------------------------------------------------------------
665 // MyProcess
666 // ----------------------------------------------------------------------------
667
668 void MyProcess::OnTerminate(int pid, int status)
669 {
670 wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
671 pid, m_cmd.c_str(), status);
672
673 // we're not needed any more
674 delete this;
675 }
676
677 // ----------------------------------------------------------------------------
678 // MyPipedProcess
679 // ----------------------------------------------------------------------------
680
681 bool MyPipedProcess::HasInput()
682 {
683 bool hasInput = FALSE;
684
685 wxInputStream& is = *GetInputStream();
686 if ( !is.Eof() )
687 {
688 wxTextInputStream tis(is);
689
690 // this assumes that the output is always line buffered
691 wxString msg;
692 msg << m_cmd << _T(" (stdout): ") << tis.ReadLine();
693
694 m_parent->GetLogListBox()->Append(msg);
695
696 hasInput = TRUE;
697 }
698
699 wxInputStream& es = *GetErrorStream();
700 if ( !es.Eof() )
701 {
702 wxTextInputStream tis(es);
703
704 // this assumes that the output is always line buffered
705 wxString msg;
706 msg << m_cmd << _T(" (stderr): ") << tis.ReadLine();
707
708 m_parent->GetLogListBox()->Append(msg);
709
710 hasInput = TRUE;
711 }
712
713 return hasInput;
714 }
715
716 void MyPipedProcess::OnTerminate(int pid, int status)
717 {
718 // show the rest of the output
719 while ( HasInput() )
720 ;
721
722 m_parent->OnProcessTerminated(this);
723
724 MyProcess::OnTerminate(pid, status);
725 }
726
727 // ----------------------------------------------------------------------------
728 // MyPipedProcess2
729 // ----------------------------------------------------------------------------
730
731 bool MyPipedProcess2::HasInput()
732 {
733 if ( !!m_input )
734 {
735 wxTextOutputStream os(*GetOutputStream());
736 os.WriteString(m_input);
737
738 CloseOutput();
739 m_input.clear();
740
741 // call us once again - may be we'll have output
742 return TRUE;
743 }
744
745 return MyPipedProcess::HasInput();
746 }