1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: exec sample demonstrates wxExecute and related functions
4 // Author: Vadim Zeitlin
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx/wx.h".
21 #include "wx/wxprec.h"
27 // for all others, include the necessary headers (this file is usually all you
28 // need because it includes almost all "standard" wxWidgets headers
40 #include "wx/msgdlg.h"
41 #include "wx/textdlg.h"
42 #include "wx/filedlg.h"
43 #include "wx/choicdlg.h"
45 #include "wx/button.h"
46 #include "wx/textctrl.h"
47 #include "wx/listbox.h"
52 #include "wx/txtstrm.h"
53 #include "wx/numdlg.h"
54 #include "wx/textdlg.h"
57 #include "wx/process.h"
59 #include "wx/mimetype.h"
65 // ----------------------------------------------------------------------------
66 // the usual application and main frame classes
67 // ----------------------------------------------------------------------------
69 // Define a new application type, each program should derive a class from wxApp
70 class MyApp
: public wxApp
73 // override base class virtuals
74 // ----------------------------
76 // this one is called on application startup and is a good place for the app
77 // initialization (doing it here and not in the ctor allows to have an error
78 // return: if OnInit() returns false, the application terminates)
79 virtual bool OnInit();
82 // Define an array of process pointers used by MyFrame
84 WX_DEFINE_ARRAY_PTR(MyPipedProcess
*, MyProcessesArray
);
86 // Define a new frame type: this is going to be our main frame
87 class MyFrame
: public wxFrame
91 MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
);
93 // event handlers (these functions should _not_ be virtual)
94 void OnQuit(wxCommandEvent
& event
);
96 void OnKill(wxCommandEvent
& event
);
98 void OnClear(wxCommandEvent
& event
);
100 void OnSyncExec(wxCommandEvent
& event
);
101 void OnSyncNoEventsExec(wxCommandEvent
& event
);
102 void OnAsyncExec(wxCommandEvent
& event
);
103 void OnShell(wxCommandEvent
& event
);
104 void OnExecWithRedirect(wxCommandEvent
& event
);
105 void OnExecWithPipe(wxCommandEvent
& event
);
107 void OnPOpen(wxCommandEvent
& event
);
109 void OnFileExec(wxCommandEvent
& event
);
110 void OnOpenURL(wxCommandEvent
& event
);
112 void OnAbout(wxCommandEvent
& event
);
114 // polling output of async processes
115 void OnTimer(wxTimerEvent
& event
);
116 void OnIdle(wxIdleEvent
& event
);
118 // for MyPipedProcess
119 void OnProcessTerminated(MyPipedProcess
*process
);
120 wxListBox
*GetLogListBox() const { return m_lbox
; }
123 void ShowOutput(const wxString
& cmd
,
124 const wxArrayString
& output
,
125 const wxString
& title
);
127 void DoAsyncExec(const wxString
& cmd
);
129 void AddAsyncProcess(MyPipedProcess
*process
)
131 if ( m_running
.IsEmpty() )
133 // we want to start getting the timer events to ensure that a
134 // steady stream of idle events comes in -- otherwise we
135 // wouldn't be able to poll the child process input
136 m_timerIdleWakeUp
.Start(100);
138 //else: the timer is already running
140 m_running
.Add(process
);
143 void RemoveAsyncProcess(MyPipedProcess
*process
)
145 m_running
.Remove(process
);
147 if ( m_running
.IsEmpty() )
149 // we don't need to get idle events all the time any more
150 m_timerIdleWakeUp
.Stop();
154 // the PID of the last process we launched asynchronously
157 // last command we executed
161 void OnDDEExec(wxCommandEvent
& event
);
162 void OnDDERequest(wxCommandEvent
& event
);
166 // last params of a DDE transaction
170 #endif // __WINDOWS__
174 MyProcessesArray m_running
;
176 // the idle event wake up timer
177 wxTimer m_timerIdleWakeUp
;
179 // any class wishing to process wxWidgets events must use this macro
180 DECLARE_EVENT_TABLE()
183 // ----------------------------------------------------------------------------
184 // MyPipeFrame: allows the user to communicate with the child process
185 // ----------------------------------------------------------------------------
187 class MyPipeFrame
: public wxFrame
190 MyPipeFrame(wxFrame
*parent
,
195 void OnTextEnter(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
196 void OnBtnSend(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
197 void OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
));
198 void OnBtnGet(wxCommandEvent
& WXUNUSED(event
)) { DoGet(); }
199 void OnBtnClose(wxCommandEvent
& WXUNUSED(event
)) { DoClose(); }
201 void OnClose(wxCloseEvent
& event
);
203 void OnProcessTerm(wxProcessEvent
& event
);
207 wxString
s(m_textOut
->GetValue());
209 m_out
.Write(s
.c_str(), s
.length());
219 void DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
);
221 void DisableOutput();
224 wxProcess
*m_process
;
226 wxOutputStream
&m_out
;
230 wxTextCtrl
*m_textOut
,
234 DECLARE_EVENT_TABLE()
237 // ----------------------------------------------------------------------------
238 // wxProcess-derived classes
239 // ----------------------------------------------------------------------------
241 // This is the handler for process termination events
242 class MyProcess
: public wxProcess
245 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
246 : wxProcess(parent
), m_cmd(cmd
)
251 // instead of overriding this virtual function we might as well process the
252 // event from it in the frame class - this might be more convenient in some
254 virtual void OnTerminate(int pid
, int status
);
261 // A specialization of MyProcess for redirecting the output
262 class MyPipedProcess
: public MyProcess
265 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
266 : MyProcess(parent
, cmd
)
271 virtual void OnTerminate(int pid
, int status
);
273 virtual bool HasInput();
276 // A version of MyPipedProcess which also sends input to the stdin of the
278 class MyPipedProcess2
: public MyPipedProcess
281 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
282 : MyPipedProcess(parent
, cmd
), m_input(input
)
286 virtual bool HasInput();
292 // ----------------------------------------------------------------------------
294 // ----------------------------------------------------------------------------
296 // IDs for the controls and the menu commands
304 Exec_SyncNoEventsExec
,
317 Exec_Btn_Send
= 1000,
323 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
325 // ----------------------------------------------------------------------------
326 // event tables and other macros for wxWidgets
327 // ----------------------------------------------------------------------------
329 // the event tables connect the wxWidgets events with the functions (event
330 // handlers) which process them. It can be also done at run-time, but for the
331 // simple menu events like this the static method is much simpler.
332 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
333 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
334 EVT_MENU(Exec_Kill
, MyFrame::OnKill
)
335 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
337 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
338 EVT_MENU(Exec_SyncNoEventsExec
, MyFrame::OnSyncNoEventsExec
)
339 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
340 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
341 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
342 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
344 EVT_MENU(Exec_POpen
, MyFrame::OnPOpen
)
346 EVT_MENU(Exec_OpenFile
, MyFrame::OnFileExec
)
347 EVT_MENU(Exec_OpenURL
, MyFrame::OnOpenURL
)
350 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
351 EVT_MENU(Exec_DDERequest
, MyFrame::OnDDERequest
)
352 #endif // __WINDOWS__
354 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
356 EVT_IDLE(MyFrame::OnIdle
)
358 EVT_TIMER(wxID_ANY
, MyFrame::OnTimer
)
361 BEGIN_EVENT_TABLE(MyPipeFrame
, wxFrame
)
362 EVT_BUTTON(Exec_Btn_Send
, MyPipeFrame::OnBtnSend
)
363 EVT_BUTTON(Exec_Btn_SendFile
, MyPipeFrame::OnBtnSendFile
)
364 EVT_BUTTON(Exec_Btn_Get
, MyPipeFrame::OnBtnGet
)
365 EVT_BUTTON(Exec_Btn_Close
, MyPipeFrame::OnBtnClose
)
367 EVT_TEXT_ENTER(wxID_ANY
, MyPipeFrame::OnTextEnter
)
369 EVT_CLOSE(MyPipeFrame::OnClose
)
371 EVT_END_PROCESS(wxID_ANY
, MyPipeFrame::OnProcessTerm
)
374 // Create a new application object: this macro will allow wxWidgets to create
375 // the application object during program execution (it's better than using a
376 // static object for many reasons) and also declares the accessor function
377 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
381 // ============================================================================
383 // ============================================================================
385 // ----------------------------------------------------------------------------
386 // the application class
387 // ----------------------------------------------------------------------------
389 // `Main program' equivalent: the program execution "starts" here
392 if ( !wxApp::OnInit() )
395 // Create the main application window
396 MyFrame
*frame
= new MyFrame(_T("Exec wxWidgets sample"),
397 wxDefaultPosition
, wxSize(500, 140));
399 // Show it and tell the application that it's our main window
403 // success: wxApp::OnRun() will be called which will enter the main message
404 // loop and the application will run. If we returned false here, the
405 // application would exit immediately.
409 // ----------------------------------------------------------------------------
411 // ----------------------------------------------------------------------------
414 #pragma warning(disable: 4355) // this used in base member initializer list
418 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
419 : wxFrame((wxFrame
*)NULL
, wxID_ANY
, title
, pos
, size
),
420 m_timerIdleWakeUp(this)
425 // we need this in order to allow the about menu relocation, since ABOUT is
426 // not the default id of the about menu
427 wxApp::s_macAboutMenuItemId
= Exec_About
;
431 wxMenu
*menuFile
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
432 menuFile
->Append(Exec_Kill
, _T("&Kill process...\tCtrl-K"),
433 _T("Kill a process by PID"));
434 menuFile
->AppendSeparator();
435 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-C"),
436 _T("Clear the log window"));
437 menuFile
->AppendSeparator();
438 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
440 wxMenu
*execMenu
= new wxMenu
;
441 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
442 _T("Launch a program and return when it terminates"));
443 execMenu
->Append(Exec_SyncNoEventsExec
, _T("Sync execution and &block...\tCtrl-B"),
444 _T("Launch a program and block until it terminates"));
445 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
446 _T("Launch a program and return immediately"));
447 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
448 _T("Launch a shell and execute a command in it"));
449 execMenu
->AppendSeparator();
450 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
451 _T("Launch a program and capture its output"));
452 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command..."),
453 _T("Pipe a string through a filter"));
454 execMenu
->Append(Exec_POpen
, _T("&Open a pipe to a command...\tCtrl-P"),
455 _T("Open a pipe to and from another program"));
457 execMenu
->AppendSeparator();
458 execMenu
->Append(Exec_OpenFile
, _T("Open &file...\tCtrl-F"),
459 _T("Launch the command to open this kind of files"));
460 execMenu
->Append(Exec_OpenURL
, _T("Open &URL...\tCtrl-U"),
461 _T("Launch the default browser with the given URL"));
463 execMenu
->AppendSeparator();
464 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
465 execMenu
->Append(Exec_DDERequest
, _T("Send DDE &request...\tCtrl-R"));
468 wxMenu
*helpMenu
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
469 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
471 // now append the freshly created menu to the menu bar...
472 wxMenuBar
*menuBar
= new wxMenuBar();
473 menuBar
->Append(menuFile
, _T("&File"));
474 menuBar
->Append(execMenu
, _T("&Exec"));
475 menuBar
->Append(helpMenu
, _T("&Help"));
477 // ... and attach this menu bar to the frame
480 // create the listbox in which we will show misc messages as they come
481 m_lbox
= new wxListBox(this, wxID_ANY
);
482 wxFont
font(12, wxFONTFAMILY_TELETYPE
, wxFONTSTYLE_NORMAL
,
483 wxFONTWEIGHT_NORMAL
);
485 m_lbox
->SetFont(font
);
488 // create a status bar just for fun (by default with 1 pane only)
490 SetStatusText(_T("Welcome to wxWidgets exec sample!"));
491 #endif // wxUSE_STATUSBAR
494 // ----------------------------------------------------------------------------
495 // event handlers: file and help menu
496 // ----------------------------------------------------------------------------
498 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
500 // true is to force the frame to close
504 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
509 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
511 wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"),
512 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
515 void MyFrame::OnKill(wxCommandEvent
& WXUNUSED(event
))
517 long pid
= wxGetNumberFromUser(_T("Please specify the process to kill"),
521 // we need the full unsigned int range
530 static const wxString signalNames
[] =
532 _T("Just test (SIGNONE)"),
533 _T("Hangup (SIGHUP)"),
534 _T("Interrupt (SIGINT)"),
535 _T("Quit (SIGQUIT)"),
536 _T("Illegal instruction (SIGILL)"),
537 _T("Trap (SIGTRAP)"),
538 _T("Abort (SIGABRT)"),
539 _T("Emulated trap (SIGEMT)"),
540 _T("FP exception (SIGFPE)"),
541 _T("Kill (SIGKILL)"),
543 _T("Segment violation (SIGSEGV)"),
544 _T("System (SIGSYS)"),
545 _T("Broken pipe (SIGPIPE)"),
546 _T("Alarm (SIGALRM)"),
547 _T("Terminate (SIGTERM)"),
550 int sig
= wxGetSingleChoiceIndex(_T("How to kill the process?"),
552 WXSIZEOF(signalNames
), signalNames
,
557 wxFAIL_MSG( _T("unexpected return value") );
585 if ( wxProcess::Exists(pid
) )
586 wxLogStatus(_T("Process %ld is running."), pid
);
588 wxLogStatus(_T("No process with pid = %ld."), pid
);
592 wxKillError rc
= wxProcess::Kill(pid
, (wxSignal
)sig
);
593 if ( rc
== wxKILL_OK
)
595 wxLogStatus(_T("Process %ld killed with signal %d."), pid
, sig
);
599 static const wxChar
*errorText
[] =
602 _T("signal not supported"),
603 _T("permission denied"),
604 _T("no such process"),
605 _T("unspecified error"),
608 wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
609 pid
, sig
, errorText
[rc
]);
614 // ----------------------------------------------------------------------------
615 // event handlers: exec menu
616 // ----------------------------------------------------------------------------
618 void MyFrame::DoAsyncExec(const wxString
& cmd
)
620 wxProcess
*process
= new MyProcess(this, cmd
);
621 m_pidLast
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
624 wxLogError( _T("Execution of '%s' failed."), cmd
.c_str() );
630 wxLogStatus( _T("Process %ld (%s) launched."),
631 m_pidLast
, cmd
.c_str() );
637 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
639 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
646 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
648 int code
= wxExecute(cmd
, wxEXEC_SYNC
);
650 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
656 void MyFrame::OnSyncNoEventsExec(wxCommandEvent
& WXUNUSED(event
))
658 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
665 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
667 int code
= wxExecute(cmd
, wxEXEC_BLOCK
);
669 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
675 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
677 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
687 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
689 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
696 int code
= wxShell(cmd
);
697 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
702 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
704 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
712 switch ( wxMessageBox(_T("Execute it synchronously?"),
714 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
730 wxArrayString output
, errors
;
731 int code
= wxExecute(cmd
, output
, errors
);
732 wxLogStatus(_T("command '%s' terminated with exit code %d."),
737 ShowOutput(cmd
, output
, _T("Output"));
738 ShowOutput(cmd
, errors
, _T("Errors"));
743 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
744 if ( !wxExecute(cmd
, wxEXEC_ASYNC
, process
) )
746 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
752 AddAsyncProcess(process
);
759 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
762 m_cmdLast
= _T("tr [a-z] [A-Z]");
764 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
771 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
776 // always execute the filter asynchronously
777 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
778 long pid
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
781 wxLogStatus( _T("Process %ld (%s) launched."), pid
, cmd
.c_str() );
783 AddAsyncProcess(process
);
787 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
795 void MyFrame::OnPOpen(wxCommandEvent
& WXUNUSED(event
))
797 wxString cmd
= wxGetTextFromUser(_T("Enter the command to launch: "),
803 wxProcess
*process
= wxProcess::Open(cmd
);
806 wxLogError(_T("Failed to launch the command."));
810 wxLogVerbose(_T("PID of the new process: %ld"), process
->GetPid());
812 wxOutputStream
*out
= process
->GetOutputStream();
815 wxLogError(_T("Failed to connect to child stdin"));
819 wxInputStream
*in
= process
->GetInputStream();
822 wxLogError(_T("Failed to connect to child stdout"));
826 new MyPipeFrame(this, cmd
, process
);
829 void MyFrame::OnFileExec(wxCommandEvent
& WXUNUSED(event
))
831 static wxString s_filename
;
836 filename
= wxLoadFileSelector(_T("any file"), NULL
, s_filename
, this);
837 #else // !wxUSE_FILEDLG
838 filename
= wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
840 #endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
842 if ( filename
.empty() )
845 s_filename
= filename
;
847 wxString ext
= filename
.AfterFirst(_T('.'));
848 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
851 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
857 bool ok
= ft
->GetOpenCommand(&cmd
,
858 wxFileType::MessageParameters(filename
));
862 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
870 void MyFrame::OnOpenURL(wxCommandEvent
& WXUNUSED(event
))
872 static wxString
s_filename(_T("http://www.wxwidgets.org/"));
874 wxString filename
= wxGetTextFromUser
882 if ( filename
.empty() )
885 s_filename
= filename
;
887 if ( !wxLaunchDefaultBrowser(s_filename
) )
888 wxLogError(_T("Failed to open URL \"%s\""), s_filename
.c_str());
891 // ----------------------------------------------------------------------------
893 // ----------------------------------------------------------------------------
897 bool MyFrame::GetDDEServer()
899 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
900 DIALOG_TITLE
, m_server
);
906 wxString topic
= wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE
, m_topic
);
912 wxString cmd
= wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE
, m_cmdDde
);
921 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
923 if ( !GetDDEServer() )
927 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
930 wxLogError(_T("Failed to connect to the DDE server '%s'."),
935 if ( !conn
->Execute(m_cmdDde
) )
937 wxLogError(_T("Failed to execute command '%s' via DDE."),
942 wxLogStatus(_T("Successfully executed DDE command"));
947 void MyFrame::OnDDERequest(wxCommandEvent
& WXUNUSED(event
))
949 if ( !GetDDEServer() )
953 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
956 wxLogError(_T("Failed to connect to the DDE server '%s'."),
961 if ( !conn
->Request(m_cmdDde
) )
963 wxLogError(_T("Failed to send request '%s' via DDE."),
968 wxLogStatus(_T("Successfully sent DDE request."));
973 #endif // __WINDOWS__
975 // ----------------------------------------------------------------------------
977 // ----------------------------------------------------------------------------
980 void MyFrame::OnIdle(wxIdleEvent
& event
)
982 size_t count
= m_running
.GetCount();
983 for ( size_t n
= 0; n
< count
; n
++ )
985 if ( m_running
[n
]->HasInput() )
992 void MyFrame::OnTimer(wxTimerEvent
& WXUNUSED(event
))
997 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
999 RemoveAsyncProcess(process
);
1003 void MyFrame::ShowOutput(const wxString
& cmd
,
1004 const wxArrayString
& output
,
1005 const wxString
& title
)
1007 size_t count
= output
.GetCount();
1011 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
1012 title
.c_str(), cmd
.c_str()));
1014 for ( size_t n
= 0; n
< count
; n
++ )
1016 m_lbox
->Append(output
[n
]);
1019 m_lbox
->Append(wxString::Format(_T("--- End of %s ---"),
1020 title
.Lower().c_str()));
1023 // ----------------------------------------------------------------------------
1025 // ----------------------------------------------------------------------------
1027 void MyProcess::OnTerminate(int pid
, int status
)
1029 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
1030 pid
, m_cmd
.c_str(), status
);
1032 // we're not needed any more
1036 // ----------------------------------------------------------------------------
1038 // ----------------------------------------------------------------------------
1040 bool MyPipedProcess::HasInput()
1042 bool hasInput
= false;
1044 if ( IsInputAvailable() )
1046 wxTextInputStream
tis(*GetInputStream());
1048 // this assumes that the output is always line buffered
1050 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
1052 m_parent
->GetLogListBox()->Append(msg
);
1057 if ( IsErrorAvailable() )
1059 wxTextInputStream
tis(*GetErrorStream());
1061 // this assumes that the output is always line buffered
1063 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
1065 m_parent
->GetLogListBox()->Append(msg
);
1073 void MyPipedProcess::OnTerminate(int pid
, int status
)
1075 // show the rest of the output
1076 while ( HasInput() )
1079 m_parent
->OnProcessTerminated(this);
1081 MyProcess::OnTerminate(pid
, status
);
1084 // ----------------------------------------------------------------------------
1086 // ----------------------------------------------------------------------------
1088 bool MyPipedProcess2::HasInput()
1090 if ( !m_input
.empty() )
1092 wxTextOutputStream
os(*GetOutputStream());
1093 os
.WriteString(m_input
);
1098 // call us once again - may be we'll have output
1102 return MyPipedProcess::HasInput();
1105 // ============================================================================
1106 // MyPipeFrame implementation
1107 // ============================================================================
1109 MyPipeFrame::MyPipeFrame(wxFrame
*parent
,
1110 const wxString
& cmd
,
1112 : wxFrame(parent
, wxID_ANY
, cmd
),
1114 // in a real program we'd check that the streams are !NULL here
1115 m_out(*process
->GetOutputStream()),
1116 m_in(*process
->GetInputStream()),
1117 m_err(*process
->GetErrorStream())
1119 m_process
->SetNextHandler(this);
1121 wxPanel
*panel
= new wxPanel(this, wxID_ANY
);
1123 m_textOut
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1124 wxDefaultPosition
, wxDefaultSize
,
1125 wxTE_PROCESS_ENTER
);
1126 m_textIn
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1127 wxDefaultPosition
, wxDefaultSize
,
1128 wxTE_MULTILINE
| wxTE_RICH
);
1129 m_textIn
->SetEditable(false);
1130 m_textErr
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1131 wxDefaultPosition
, wxDefaultSize
,
1132 wxTE_MULTILINE
| wxTE_RICH
);
1133 m_textErr
->SetEditable(false);
1135 wxSizer
*sizerTop
= new wxBoxSizer(wxVERTICAL
);
1136 sizerTop
->Add(m_textOut
, 0, wxGROW
| wxALL
, 5);
1138 wxSizer
*sizerBtns
= new wxBoxSizer(wxHORIZONTAL
);
1140 Add(new wxButton(panel
, Exec_Btn_Send
, _T("&Send")), 0, wxALL
, 5);
1142 Add(new wxButton(panel
, Exec_Btn_SendFile
, _T("&File...")), 0, wxALL
, 5);
1144 Add(new wxButton(panel
, Exec_Btn_Get
, _T("&Get")), 0, wxALL
, 5);
1146 Add(new wxButton(panel
, Exec_Btn_Close
, _T("&Close")), 0, wxALL
, 5);
1148 sizerTop
->Add(sizerBtns
, 0, wxCENTRE
| wxALL
, 5);
1149 sizerTop
->Add(m_textIn
, 1, wxGROW
| wxALL
, 5);
1150 sizerTop
->Add(m_textErr
, 1, wxGROW
| wxALL
, 5);
1152 panel
->SetSizer(sizerTop
);
1153 sizerTop
->Fit(this);
1158 void MyPipeFrame::OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
))
1161 wxFileDialog
filedlg(this, _T("Select file to send"));
1162 if ( filedlg
.ShowModal() != wxID_OK
)
1165 wxFFile
file(filedlg
.GetFilename(), _T("r"));
1167 if ( !file
.IsOpened() || !file
.ReadAll(&data
) )
1170 // can't write the entire string at once, this risk overflowing the pipe
1171 // and we would dead lock
1172 size_t len
= data
.length();
1173 const wxChar
*pc
= data
.c_str();
1176 const size_t CHUNK_SIZE
= 4096;
1177 m_out
.Write(pc
, len
> CHUNK_SIZE
? CHUNK_SIZE
: len
);
1179 // note that not all data could have been written as we don't block on
1180 // the write end of the pipe
1181 const size_t lenChunk
= m_out
.LastWrite();
1188 #endif // wxUSE_FILEDLG
1191 void MyPipeFrame::DoGet()
1193 // we don't have any way to be notified when any input appears on the
1194 // stream so we have to poll it :-(
1195 DoGetFromStream(m_textIn
, m_in
);
1196 DoGetFromStream(m_textErr
, m_err
);
1199 void MyPipeFrame::DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
)
1201 while ( in
.CanRead() )
1203 wxChar buffer
[4096];
1204 buffer
[in
.Read(buffer
, WXSIZEOF(buffer
) - 1).LastRead()] = _T('\0');
1206 text
->AppendText(buffer
);
1210 void MyPipeFrame::DoClose()
1212 m_process
->CloseOutput();
1217 void MyPipeFrame::DisableInput()
1219 m_textOut
->SetEditable(false);
1220 FindWindow(Exec_Btn_Send
)->Disable();
1221 FindWindow(Exec_Btn_SendFile
)->Disable();
1222 FindWindow(Exec_Btn_Close
)->Disable();
1225 void MyPipeFrame::DisableOutput()
1227 FindWindow(Exec_Btn_Get
)->Disable();
1230 void MyPipeFrame::OnClose(wxCloseEvent
& event
)
1234 // we're not interested in getting the process termination notification
1235 // if we are closing it ourselves
1236 wxProcess
*process
= m_process
;
1238 process
->SetNextHandler(NULL
);
1240 process
->CloseOutput();
1246 void MyPipeFrame::OnProcessTerm(wxProcessEvent
& WXUNUSED(event
))
1253 wxLogWarning(_T("The other process has terminated, closing"));