More name changes
[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 #if defined(__GNUG__) && !defined(__APPLE__)
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" wxWidgets headers
34 #ifndef WX_PRECOMP
35 #include "wx/app.h"
36 #include "wx/log.h"
37 #include "wx/frame.h"
38 #include "wx/panel.h"
39
40 #include "wx/timer.h"
41
42 #include "wx/utils.h"
43 #include "wx/menu.h"
44
45 #include "wx/msgdlg.h"
46 #include "wx/textdlg.h"
47 #include "wx/filedlg.h"
48 #include "wx/choicdlg.h"
49
50 #include "wx/button.h"
51 #include "wx/textctrl.h"
52 #include "wx/listbox.h"
53
54 #include "wx/sizer.h"
55 #endif
56
57 #include "wx/txtstrm.h"
58 #include "wx/numdlg.h"
59
60 #include "wx/process.h"
61
62 #include "wx/mimetype.h"
63
64 #ifdef __WINDOWS__
65 #include "wx/dde.h"
66 #endif // __WINDOWS__
67
68 // ----------------------------------------------------------------------------
69 // the usual application and main frame classes
70 // ----------------------------------------------------------------------------
71
72 // Define a new application type, each program should derive a class from wxApp
73 class MyApp : public wxApp
74 {
75 public:
76 // override base class virtuals
77 // ----------------------------
78
79 // this one is called on application startup and is a good place for the app
80 // initialization (doing it here and not in the ctor allows to have an error
81 // return: if OnInit() returns false, the application terminates)
82 virtual bool OnInit();
83 };
84
85 // Define an array of process pointers used by MyFrame
86 class MyPipedProcess;
87 WX_DEFINE_ARRAY_PTR(MyPipedProcess *, MyProcessesArray);
88
89 // Define a new frame type: this is going to be our main frame
90 class MyFrame : public wxFrame
91 {
92 public:
93 // ctor(s)
94 MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
95
96 // event handlers (these functions should _not_ be virtual)
97 void OnQuit(wxCommandEvent& event);
98
99 void OnKill(wxCommandEvent& event);
100
101 void OnClear(wxCommandEvent& event);
102
103 void OnSyncExec(wxCommandEvent& event);
104 void OnAsyncExec(wxCommandEvent& event);
105 void OnShell(wxCommandEvent& event);
106 void OnExecWithRedirect(wxCommandEvent& event);
107 void OnExecWithPipe(wxCommandEvent& event);
108
109 void OnPOpen(wxCommandEvent& event);
110
111 void OnFileExec(wxCommandEvent& event);
112
113 void OnAbout(wxCommandEvent& event);
114
115 // polling output of async processes
116 void OnTimer(wxTimerEvent& event);
117 void OnIdle(wxIdleEvent& event);
118
119 // for MyPipedProcess
120 void OnProcessTerminated(MyPipedProcess *process);
121 wxListBox *GetLogListBox() const { return m_lbox; }
122
123 private:
124 void ShowOutput(const wxString& cmd,
125 const wxArrayString& output,
126 const wxString& title);
127
128 void DoAsyncExec(const wxString& cmd);
129
130 void AddAsyncProcess(MyPipedProcess *process)
131 {
132 if ( m_running.IsEmpty() )
133 {
134 // we want to start getting the timer events to ensure that a
135 // steady stream of idle events comes in -- otherwise we
136 // wouldn't be able to poll the child process input
137 m_timerIdleWakeUp.Start(100);
138 }
139 //else: the timer is already running
140
141 m_running.Add(process);
142 }
143
144 void RemoveAsyncProcess(MyPipedProcess *process)
145 {
146 m_running.Remove(process);
147
148 if ( m_running.IsEmpty() )
149 {
150 // we don't need to get idle events all the time any more
151 m_timerIdleWakeUp.Stop();
152 }
153 }
154
155 // the PID of the last process we launched asynchronously
156 long m_pidLast;
157
158 // last command we executed
159 wxString m_cmdLast;
160
161 #ifdef __WINDOWS__
162 void OnDDEExec(wxCommandEvent& event);
163 void OnDDERequest(wxCommandEvent& event);
164
165 bool GetDDEServer();
166
167 // last params of a DDE transaction
168 wxString m_server,
169 m_topic,
170 m_cmdDde;
171 #endif // __WINDOWS__
172
173 wxListBox *m_lbox;
174
175 MyProcessesArray m_running;
176
177 // the idle event wake up timer
178 wxTimer m_timerIdleWakeUp;
179
180 // any class wishing to process wxWidgets events must use this macro
181 DECLARE_EVENT_TABLE()
182 };
183
184 // ----------------------------------------------------------------------------
185 // MyPipeFrame: allows the user to communicate with the child process
186 // ----------------------------------------------------------------------------
187
188 class MyPipeFrame : public wxFrame
189 {
190 public:
191 MyPipeFrame(wxFrame *parent,
192 const wxString& cmd,
193 wxProcess *process);
194
195 protected:
196 void OnTextEnter(wxCommandEvent& WXUNUSED(event)) { DoSend(); }
197 void OnBtnSend(wxCommandEvent& WXUNUSED(event)) { DoSend(); }
198 void OnBtnGet(wxCommandEvent& WXUNUSED(event)) { DoGet(); }
199
200 void OnClose(wxCloseEvent& event);
201
202 void OnProcessTerm(wxProcessEvent& event);
203
204 void DoSend()
205 {
206 m_out.WriteString(m_textIn->GetValue() + _T('\n'));
207 m_textIn->Clear();
208
209 DoGet();
210 }
211
212 void DoGet();
213
214 private:
215 wxProcess *m_process;
216
217 wxTextInputStream m_in;
218 wxTextOutputStream m_out;
219
220 wxTextCtrl *m_textIn,
221 *m_textOut;
222
223 DECLARE_EVENT_TABLE()
224 };
225
226 // ----------------------------------------------------------------------------
227 // wxProcess-derived classes
228 // ----------------------------------------------------------------------------
229
230 // This is the handler for process termination events
231 class MyProcess : public wxProcess
232 {
233 public:
234 MyProcess(MyFrame *parent, const wxString& cmd)
235 : wxProcess(parent), m_cmd(cmd)
236 {
237 m_parent = parent;
238 }
239
240 // instead of overriding this virtual function we might as well process the
241 // event from it in the frame class - this might be more convenient in some
242 // cases
243 virtual void OnTerminate(int pid, int status);
244
245 protected:
246 MyFrame *m_parent;
247 wxString m_cmd;
248 };
249
250 // A specialization of MyProcess for redirecting the output
251 class MyPipedProcess : public MyProcess
252 {
253 public:
254 MyPipedProcess(MyFrame *parent, const wxString& cmd)
255 : MyProcess(parent, cmd)
256 {
257 Redirect();
258 }
259
260 virtual void OnTerminate(int pid, int status);
261
262 virtual bool HasInput();
263 };
264
265 // A version of MyPipedProcess which also sends input to the stdin of the
266 // child process
267 class MyPipedProcess2 : public MyPipedProcess
268 {
269 public:
270 MyPipedProcess2(MyFrame *parent, const wxString& cmd, const wxString& input)
271 : MyPipedProcess(parent, cmd), m_input(input)
272 {
273 }
274
275 virtual bool HasInput();
276
277 private:
278 wxString m_input;
279 };
280
281 // ----------------------------------------------------------------------------
282 // constants
283 // ----------------------------------------------------------------------------
284
285 // IDs for the controls and the menu commands
286 enum
287 {
288 // menu items
289 Exec_Quit = 100,
290 Exec_Kill,
291 Exec_ClearLog,
292 Exec_SyncExec = 200,
293 Exec_AsyncExec,
294 Exec_Shell,
295 Exec_POpen,
296 Exec_OpenFile,
297 Exec_DDEExec,
298 Exec_DDERequest,
299 Exec_Redirect,
300 Exec_Pipe,
301 Exec_About = 300,
302
303 // control ids
304 Exec_Btn_Send = 1000,
305 Exec_Btn_Get
306 };
307
308 static const wxChar *DIALOG_TITLE = _T("Exec sample");
309
310 // ----------------------------------------------------------------------------
311 // event tables and other macros for wxWidgets
312 // ----------------------------------------------------------------------------
313
314 // the event tables connect the wxWidgets events with the functions (event
315 // handlers) which process them. It can be also done at run-time, but for the
316 // simple menu events like this the static method is much simpler.
317 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
318 EVT_MENU(Exec_Quit, MyFrame::OnQuit)
319 EVT_MENU(Exec_Kill, MyFrame::OnKill)
320 EVT_MENU(Exec_ClearLog, MyFrame::OnClear)
321
322 EVT_MENU(Exec_SyncExec, MyFrame::OnSyncExec)
323 EVT_MENU(Exec_AsyncExec, MyFrame::OnAsyncExec)
324 EVT_MENU(Exec_Shell, MyFrame::OnShell)
325 EVT_MENU(Exec_Redirect, MyFrame::OnExecWithRedirect)
326 EVT_MENU(Exec_Pipe, MyFrame::OnExecWithPipe)
327
328 EVT_MENU(Exec_POpen, MyFrame::OnPOpen)
329
330 EVT_MENU(Exec_OpenFile, MyFrame::OnFileExec)
331
332 #ifdef __WINDOWS__
333 EVT_MENU(Exec_DDEExec, MyFrame::OnDDEExec)
334 EVT_MENU(Exec_DDERequest, MyFrame::OnDDERequest)
335 #endif // __WINDOWS__
336
337 EVT_MENU(Exec_About, MyFrame::OnAbout)
338
339 EVT_IDLE(MyFrame::OnIdle)
340
341 EVT_TIMER(-1, MyFrame::OnTimer)
342 END_EVENT_TABLE()
343
344 BEGIN_EVENT_TABLE(MyPipeFrame, wxFrame)
345 EVT_BUTTON(Exec_Btn_Send, MyPipeFrame::OnBtnSend)
346 EVT_BUTTON(Exec_Btn_Get, MyPipeFrame::OnBtnGet)
347
348 EVT_TEXT_ENTER(-1, MyPipeFrame::OnTextEnter)
349
350 EVT_CLOSE(MyPipeFrame::OnClose)
351
352 EVT_END_PROCESS(-1, MyPipeFrame::OnProcessTerm)
353 END_EVENT_TABLE()
354
355 // Create a new application object: this macro will allow wxWidgets to create
356 // the application object during program execution (it's better than using a
357 // static object for many reasons) and also declares the accessor function
358 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
359 // not wxApp)
360 IMPLEMENT_APP(MyApp)
361
362 // ============================================================================
363 // implementation
364 // ============================================================================
365
366 // ----------------------------------------------------------------------------
367 // the application class
368 // ----------------------------------------------------------------------------
369
370 // `Main program' equivalent: the program execution "starts" here
371 bool MyApp::OnInit()
372 {
373 // Create the main application window
374 MyFrame *frame = new MyFrame(_T("Exec wxWidgets sample"),
375 wxDefaultPosition, wxSize(500, 140));
376
377 // Show it and tell the application that it's our main window
378 frame->Show(TRUE);
379 SetTopWindow(frame);
380
381 // success: wxApp::OnRun() will be called which will enter the main message
382 // loop and the application will run. If we returned FALSE here, the
383 // application would exit immediately.
384 return TRUE;
385 }
386
387 // ----------------------------------------------------------------------------
388 // main frame
389 // ----------------------------------------------------------------------------
390
391 #ifdef __VISUALC__
392 #pragma warning(disable: 4355) // this used in base member initializer list
393 #endif
394
395 // frame constructor
396 MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
397 : wxFrame((wxFrame *)NULL, -1, title, pos, size),
398 m_timerIdleWakeUp(this)
399 {
400 m_pidLast = 0;
401
402 #ifdef __WXMAC__
403 // we need this in order to allow the about menu relocation, since ABOUT is
404 // not the default id of the about menu
405 wxApp::s_macAboutMenuItemId = Exec_About;
406 #endif
407
408 // create a menu bar
409 wxMenu *menuFile = new wxMenu(_T(""), wxMENU_TEAROFF);
410 menuFile->Append(Exec_Kill, _T("&Kill process...\tCtrl-K"),
411 _T("Kill a process by PID"));
412 menuFile->AppendSeparator();
413 menuFile->Append(Exec_ClearLog, _T("&Clear log\tCtrl-C"),
414 _T("Clear the log window"));
415 menuFile->AppendSeparator();
416 menuFile->Append(Exec_Quit, _T("E&xit\tAlt-X"), _T("Quit this program"));
417
418 wxMenu *execMenu = new wxMenu;
419 execMenu->Append(Exec_SyncExec, _T("Sync &execution...\tCtrl-E"),
420 _T("Launch a program and return when it terminates"));
421 execMenu->Append(Exec_AsyncExec, _T("&Async execution...\tCtrl-A"),
422 _T("Launch a program and return immediately"));
423 execMenu->Append(Exec_Shell, _T("Execute &shell command...\tCtrl-S"),
424 _T("Launch a shell and execute a command in it"));
425 execMenu->AppendSeparator();
426 execMenu->Append(Exec_Redirect, _T("Capture command &output...\tCtrl-O"),
427 _T("Launch a program and capture its output"));
428 execMenu->Append(Exec_Pipe, _T("&Pipe through command..."),
429 _T("Pipe a string through a filter"));
430 execMenu->Append(Exec_POpen, _T("&Open a pipe to a command...\tCtrl-P"),
431 _T("Open a pipe to and from another program"));
432
433 execMenu->AppendSeparator();
434 execMenu->Append(Exec_OpenFile, _T("Open &file...\tCtrl-F"),
435 _T("Launch the command to open this kind of files"));
436 #ifdef __WINDOWS__
437 execMenu->AppendSeparator();
438 execMenu->Append(Exec_DDEExec, _T("Execute command via &DDE...\tCtrl-D"));
439 execMenu->Append(Exec_DDERequest, _T("Send DDE &request...\tCtrl-R"));
440 #endif
441
442 wxMenu *helpMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
443 helpMenu->Append(Exec_About, _T("&About...\tF1"), _T("Show about dialog"));
444
445 // now append the freshly created menu to the menu bar...
446 wxMenuBar *menuBar = new wxMenuBar();
447 menuBar->Append(menuFile, _T("&File"));
448 menuBar->Append(execMenu, _T("&Exec"));
449 menuBar->Append(helpMenu, _T("&Help"));
450
451 // ... and attach this menu bar to the frame
452 SetMenuBar(menuBar);
453
454 // create the listbox in which we will show misc messages as they come
455 m_lbox = new wxListBox(this, -1);
456 wxFont font(12, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL,
457 wxFONTWEIGHT_NORMAL);
458 if ( font.Ok() )
459 m_lbox->SetFont(font);
460
461 #if wxUSE_STATUSBAR
462 // create a status bar just for fun (by default with 1 pane only)
463 CreateStatusBar();
464 SetStatusText(_T("Welcome to wxWidgets exec sample!"));
465 #endif // wxUSE_STATUSBAR
466 }
467
468 // ----------------------------------------------------------------------------
469 // event handlers: file and help menu
470 // ----------------------------------------------------------------------------
471
472 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
473 {
474 // TRUE is to force the frame to close
475 Close(TRUE);
476 }
477
478 void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event))
479 {
480 m_lbox->Clear();
481 }
482
483 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
484 {
485 wxMessageBox(_T("Exec wxWidgets Sample\n© 2000-2002 Vadim Zeitlin"),
486 _T("About Exec"), wxOK | wxICON_INFORMATION, this);
487 }
488
489 void MyFrame::OnKill(wxCommandEvent& WXUNUSED(event))
490 {
491 long pid = wxGetNumberFromUser(_T("Please specify the process to kill"),
492 _T("Enter PID:"),
493 _T("Exec question"),
494 m_pidLast,
495 // we need the full unsigned int range
496 -INT_MAX, INT_MAX,
497 this);
498 if ( pid == -1 )
499 {
500 // cancelled
501 return;
502 }
503
504 static const wxString signalNames[] =
505 {
506 _T("Just test (SIGNONE)"),
507 _T("Hangup (SIGHUP)"),
508 _T("Interrupt (SIGINT)"),
509 _T("Quit (SIGQUIT)"),
510 _T("Illegal instruction (SIGILL)"),
511 _T("Trap (SIGTRAP)"),
512 _T("Abort (SIGABRT)"),
513 _T("Emulated trap (SIGEMT)"),
514 _T("FP exception (SIGFPE)"),
515 _T("Kill (SIGKILL)"),
516 _T("Bus (SIGBUS)"),
517 _T("Segment violation (SIGSEGV)"),
518 _T("System (SIGSYS)"),
519 _T("Broken pipe (SIGPIPE)"),
520 _T("Alarm (SIGALRM)"),
521 _T("Terminate (SIGTERM)"),
522 };
523
524 int sig = wxGetSingleChoiceIndex(_T("How to kill the process?"),
525 _T("Exec question"),
526 WXSIZEOF(signalNames), signalNames,
527 this);
528 switch ( sig )
529 {
530 default:
531 wxFAIL_MSG( _T("unexpected return value") );
532 // fall through
533
534 case -1:
535 // cancelled
536 return;
537
538 case wxSIGNONE:
539 case wxSIGHUP:
540 case wxSIGINT:
541 case wxSIGQUIT:
542 case wxSIGILL:
543 case wxSIGTRAP:
544 case wxSIGABRT:
545 case wxSIGEMT:
546 case wxSIGFPE:
547 case wxSIGKILL:
548 case wxSIGBUS:
549 case wxSIGSEGV:
550 case wxSIGSYS:
551 case wxSIGPIPE:
552 case wxSIGALRM:
553 case wxSIGTERM:
554 break;
555 }
556
557 if ( sig == 0 )
558 {
559 if ( wxProcess::Exists(pid) )
560 wxLogStatus(_T("Process %ld is running."), pid);
561 else
562 wxLogStatus(_T("No process with pid = %ld."), pid);
563 }
564 else // not SIGNONE
565 {
566 wxKillError rc = wxProcess::Kill(pid, (wxSignal)sig);
567 if ( rc == wxKILL_OK )
568 {
569 wxLogStatus(_T("Process %ld killed with signal %d."), pid, sig);
570 }
571 else
572 {
573 static const wxChar *errorText[] =
574 {
575 _T(""), // no error
576 _T("signal not supported"),
577 _T("permission denied"),
578 _T("no such process"),
579 _T("unspecified error"),
580 };
581
582 wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
583 pid, sig, errorText[rc]);
584 }
585 }
586 }
587
588 // ----------------------------------------------------------------------------
589 // event handlers: exec menu
590 // ----------------------------------------------------------------------------
591
592 void MyFrame::DoAsyncExec(const wxString& cmd)
593 {
594 wxProcess *process = new MyProcess(this, cmd);
595 m_pidLast = wxExecute(cmd, wxEXEC_ASYNC, process);
596 if ( !m_pidLast )
597 {
598 wxLogError( _T("Execution of '%s' failed."), cmd.c_str() );
599
600 delete process;
601 }
602 else
603 {
604 wxLogStatus( _T("Process %ld (%s) launched."),
605 m_pidLast, cmd.c_str() );
606
607 m_cmdLast = cmd;
608 }
609 }
610
611 void MyFrame::OnSyncExec(wxCommandEvent& WXUNUSED(event))
612 {
613 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
614 DIALOG_TITLE,
615 m_cmdLast);
616
617 if ( !cmd )
618 return;
619
620 wxLogStatus( _T("'%s' is running please wait..."), cmd.c_str() );
621
622 int code = wxExecute(cmd, wxEXEC_SYNC);
623
624 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
625 cmd.c_str(), code);
626
627 m_cmdLast = cmd;
628 }
629
630 void MyFrame::OnAsyncExec(wxCommandEvent& WXUNUSED(event))
631 {
632 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
633 DIALOG_TITLE,
634 m_cmdLast);
635
636 if ( !cmd )
637 return;
638
639 DoAsyncExec(cmd);
640 }
641
642 void MyFrame::OnShell(wxCommandEvent& WXUNUSED(event))
643 {
644 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
645 DIALOG_TITLE,
646 m_cmdLast);
647
648 if ( !cmd )
649 return;
650
651 int code = wxShell(cmd);
652 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
653 cmd.c_str(), code);
654 m_cmdLast = cmd;
655 }
656
657 void MyFrame::OnExecWithRedirect(wxCommandEvent& WXUNUSED(event))
658 {
659 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
660 DIALOG_TITLE,
661 m_cmdLast);
662
663 if ( !cmd )
664 return;
665
666 bool sync;
667 switch ( wxMessageBox(_T("Execute it synchronously?"),
668 _T("Exec question"),
669 wxYES_NO | wxCANCEL | wxICON_QUESTION, this) )
670 {
671 case wxYES:
672 sync = TRUE;
673 break;
674
675 case wxNO:
676 sync = FALSE;
677 break;
678
679 default:
680 return;
681 }
682
683 if ( sync )
684 {
685 wxArrayString output, errors;
686 int code = wxExecute(cmd, output, errors);
687 wxLogStatus(_T("command '%s' terminated with exit code %d."),
688 cmd.c_str(), code);
689
690 if ( code != -1 )
691 {
692 ShowOutput(cmd, output, _T("Output"));
693 ShowOutput(cmd, errors, _T("Errors"));
694 }
695 }
696 else // async exec
697 {
698 MyPipedProcess *process = new MyPipedProcess(this, cmd);
699 if ( !wxExecute(cmd, wxEXEC_ASYNC, process) )
700 {
701 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
702
703 delete process;
704 }
705 else
706 {
707 AddAsyncProcess(process);
708 }
709 }
710
711 m_cmdLast = cmd;
712 }
713
714 void MyFrame::OnExecWithPipe(wxCommandEvent& WXUNUSED(event))
715 {
716 if ( !m_cmdLast )
717 m_cmdLast = _T("tr [a-z] [A-Z]");
718
719 wxString cmd = wxGetTextFromUser(_T("Enter the command: "),
720 DIALOG_TITLE,
721 m_cmdLast);
722
723 if ( !cmd )
724 return;
725
726 wxString input = wxGetTextFromUser(_T("Enter the string to send to it: "),
727 DIALOG_TITLE);
728 if ( !input )
729 return;
730
731 // always execute the filter asynchronously
732 MyPipedProcess2 *process = new MyPipedProcess2(this, cmd, input);
733 long pid = wxExecute(cmd, wxEXEC_ASYNC, process);
734 if ( pid )
735 {
736 wxLogStatus( _T("Process %ld (%s) launched."), pid, cmd.c_str() );
737
738 AddAsyncProcess(process);
739 }
740 else
741 {
742 wxLogError(_T("Execution of '%s' failed."), cmd.c_str());
743
744 delete process;
745 }
746
747 m_cmdLast = cmd;
748 }
749
750 void MyFrame::OnPOpen(wxCommandEvent& WXUNUSED(event))
751 {
752 wxString cmd = wxGetTextFromUser(_T("Enter the command to launch: "),
753 DIALOG_TITLE,
754 m_cmdLast);
755 if ( cmd.empty() )
756 return;
757
758 wxProcess *process = wxProcess::Open(cmd);
759 if ( !process )
760 {
761 wxLogError(_T("Failed to launch the command."));
762 return;
763 }
764
765 wxOutputStream *out = process->GetOutputStream();
766 if ( !out )
767 {
768 wxLogError(_T("Failed to connect to child stdin"));
769 return;
770 }
771
772 wxInputStream *in = process->GetInputStream();
773 if ( !in )
774 {
775 wxLogError(_T("Failed to connect to child stdout"));
776 return;
777 }
778
779 new MyPipeFrame(this, cmd, process);
780 }
781
782 void MyFrame::OnFileExec(wxCommandEvent& WXUNUSED(event))
783 {
784 static wxString s_filename;
785
786 wxString filename = wxLoadFileSelector(_T(""), _T(""), s_filename);
787 if ( !filename )
788 return;
789
790 s_filename = filename;
791
792 wxString ext = filename.AfterFirst(_T('.'));
793 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
794 if ( !ft )
795 {
796 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
797 ext.c_str());
798 return;
799 }
800
801 wxString cmd;
802 bool ok = ft->GetOpenCommand(&cmd,
803 wxFileType::MessageParameters(filename, _T("")));
804 delete ft;
805 if ( !ok )
806 {
807 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
808 ext.c_str());
809 return;
810 }
811
812 DoAsyncExec(cmd);
813 }
814
815 // ----------------------------------------------------------------------------
816 // DDE stuff
817 // ----------------------------------------------------------------------------
818
819 #ifdef __WINDOWS__
820
821 bool MyFrame::GetDDEServer()
822 {
823 wxString server = wxGetTextFromUser(_T("Server to connect to:"),
824 DIALOG_TITLE, m_server);
825 if ( !server )
826 return FALSE;
827
828 m_server = server;
829
830 wxString topic = wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE, m_topic);
831 if ( !topic )
832 return FALSE;
833
834 m_topic = topic;
835
836 wxString cmd = wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE, m_cmdDde);
837 if ( !cmd )
838 return FALSE;
839
840 m_cmdDde = cmd;
841
842 return TRUE;
843 }
844
845 void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event))
846 {
847 if ( !GetDDEServer() )
848 return;
849
850 wxDDEClient client;
851 wxConnectionBase *conn = client.MakeConnection(_T(""), m_server, m_topic);
852 if ( !conn )
853 {
854 wxLogError(_T("Failed to connect to the DDE server '%s'."),
855 m_server.c_str());
856 }
857 else
858 {
859 if ( !conn->Execute(m_cmdDde) )
860 {
861 wxLogError(_T("Failed to execute command '%s' via DDE."),
862 m_cmdDde.c_str());
863 }
864 else
865 {
866 wxLogStatus(_T("Successfully executed DDE command"));
867 }
868 }
869 }
870
871 void MyFrame::OnDDERequest(wxCommandEvent& WXUNUSED(event))
872 {
873 if ( !GetDDEServer() )
874 return;
875
876 wxDDEClient client;
877 wxConnectionBase *conn = client.MakeConnection(_T(""), m_server, m_topic);
878 if ( !conn )
879 {
880 wxLogError(_T("Failed to connect to the DDE server '%s'."),
881 m_server.c_str());
882 }
883 else
884 {
885 if ( !conn->Request(m_cmdDde) )
886 {
887 wxLogError(_T("Failed to send request '%s' via DDE."),
888 m_cmdDde.c_str());
889 }
890 else
891 {
892 wxLogStatus(_T("Successfully sent DDE request."));
893 }
894 }
895 }
896
897 #endif // __WINDOWS__
898
899 // ----------------------------------------------------------------------------
900 // various helpers
901 // ----------------------------------------------------------------------------
902
903 // input polling
904 void MyFrame::OnIdle(wxIdleEvent& event)
905 {
906 size_t count = m_running.GetCount();
907 for ( size_t n = 0; n < count; n++ )
908 {
909 if ( m_running[n]->HasInput() )
910 {
911 event.RequestMore();
912 }
913 }
914 }
915
916 void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
917 {
918 wxWakeUpIdle();
919 }
920
921 void MyFrame::OnProcessTerminated(MyPipedProcess *process)
922 {
923 RemoveAsyncProcess(process);
924 }
925
926
927 void MyFrame::ShowOutput(const wxString& cmd,
928 const wxArrayString& output,
929 const wxString& title)
930 {
931 size_t count = output.GetCount();
932 if ( !count )
933 return;
934
935 m_lbox->Append(wxString::Format(_T("--- %s of '%s' ---"),
936 title.c_str(), cmd.c_str()));
937
938 for ( size_t n = 0; n < count; n++ )
939 {
940 m_lbox->Append(output[n]);
941 }
942
943 m_lbox->Append(wxString::Format(_T("--- End of %s ---"),
944 title.Lower().c_str()));
945 }
946
947 // ----------------------------------------------------------------------------
948 // MyProcess
949 // ----------------------------------------------------------------------------
950
951 void MyProcess::OnTerminate(int pid, int status)
952 {
953 wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
954 pid, m_cmd.c_str(), status);
955
956 // we're not needed any more
957 delete this;
958 }
959
960 // ----------------------------------------------------------------------------
961 // MyPipedProcess
962 // ----------------------------------------------------------------------------
963
964 bool MyPipedProcess::HasInput()
965 {
966 bool hasInput = FALSE;
967
968 if ( IsInputAvailable() )
969 {
970 wxTextInputStream tis(*GetInputStream());
971
972 // this assumes that the output is always line buffered
973 wxString msg;
974 msg << m_cmd << _T(" (stdout): ") << tis.ReadLine();
975
976 m_parent->GetLogListBox()->Append(msg);
977
978 hasInput = TRUE;
979 }
980
981 if ( IsErrorAvailable() )
982 {
983 wxTextInputStream tis(*GetErrorStream());
984
985 // this assumes that the output is always line buffered
986 wxString msg;
987 msg << m_cmd << _T(" (stderr): ") << tis.ReadLine();
988
989 m_parent->GetLogListBox()->Append(msg);
990
991 hasInput = TRUE;
992 }
993
994 return hasInput;
995 }
996
997 void MyPipedProcess::OnTerminate(int pid, int status)
998 {
999 // show the rest of the output
1000 while ( HasInput() )
1001 ;
1002
1003 m_parent->OnProcessTerminated(this);
1004
1005 MyProcess::OnTerminate(pid, status);
1006 }
1007
1008 // ----------------------------------------------------------------------------
1009 // MyPipedProcess2
1010 // ----------------------------------------------------------------------------
1011
1012 bool MyPipedProcess2::HasInput()
1013 {
1014 if ( !!m_input )
1015 {
1016 wxTextOutputStream os(*GetOutputStream());
1017 os.WriteString(m_input);
1018
1019 CloseOutput();
1020 m_input.clear();
1021
1022 // call us once again - may be we'll have output
1023 return TRUE;
1024 }
1025
1026 return MyPipedProcess::HasInput();
1027 }
1028
1029 // ============================================================================
1030 // MyPipeFrame implementation
1031 // ============================================================================
1032
1033 MyPipeFrame::MyPipeFrame(wxFrame *parent,
1034 const wxString& cmd,
1035 wxProcess *process)
1036 : wxFrame(parent, -1, cmd),
1037 m_process(process),
1038 // in a real program we'd check that the streams are !NULL here
1039 m_in(*process->GetInputStream()),
1040 m_out(*process->GetOutputStream())
1041 {
1042 m_process->SetNextHandler(this);
1043
1044 wxPanel *panel = new wxPanel(this, -1);
1045
1046 m_textIn = new wxTextCtrl(panel, -1, _T(""),
1047 wxDefaultPosition, wxDefaultSize,
1048 wxTE_PROCESS_ENTER);
1049 m_textOut = new wxTextCtrl(panel, -1, _T(""));
1050 m_textOut->SetEditable(FALSE);
1051
1052 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
1053 sizerTop->Add(m_textIn, 0, wxGROW | wxALL, 5);
1054
1055 wxSizer *sizerBtns = new wxBoxSizer(wxHORIZONTAL);
1056 sizerBtns->Add(new wxButton(panel, Exec_Btn_Send, _T("&Send")), 0,
1057 wxALL, 10);
1058 sizerBtns->Add(new wxButton(panel, Exec_Btn_Get, _T("&Get")), 0,
1059 wxALL, 10);
1060
1061 sizerTop->Add(sizerBtns, 0, wxCENTRE | wxALL, 5);
1062 sizerTop->Add(m_textOut, 0, wxGROW | wxALL, 5);
1063
1064 panel->SetSizer(sizerTop);
1065 sizerTop->Fit(this);
1066
1067 Show();
1068 }
1069
1070 void MyPipeFrame::DoGet()
1071 {
1072 // we don't have any way to be notified when any input appears on the
1073 // stream so we have to poll it :-(
1074 //
1075 // NB: this really must be done because otherwise the other program might
1076 // not have enough time to receive or process our data and we'd read
1077 // an empty string
1078 while ( !m_process->IsInputAvailable() && m_process->IsInputOpened() )
1079 ;
1080
1081 m_textOut->SetValue(m_in.ReadLine());
1082 }
1083
1084 void MyPipeFrame::OnClose(wxCloseEvent& event)
1085 {
1086 if ( m_process )
1087 {
1088 // we're not interested in getting the process termination notification
1089 // if we are closing it ourselves
1090 wxProcess *process = m_process;
1091 m_process = NULL;
1092 process->SetNextHandler(NULL);
1093
1094 process->CloseOutput();
1095 }
1096
1097 event.Skip();
1098 }
1099
1100 void MyPipeFrame::OnProcessTerm(wxProcessEvent& WXUNUSED(event))
1101 {
1102 delete m_process;
1103 m_process = NULL;
1104
1105 wxLogWarning(_T("The other process has terminated, closing"));
1106
1107 Close();
1108 }