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