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 OnAsyncExec(wxCommandEvent
& event
);
102 void OnShell(wxCommandEvent
& event
);
103 void OnExecWithRedirect(wxCommandEvent
& event
);
104 void OnExecWithPipe(wxCommandEvent
& event
);
106 void OnPOpen(wxCommandEvent
& event
);
108 void OnFileExec(wxCommandEvent
& event
);
109 void OnOpenURL(wxCommandEvent
& event
);
111 void OnAbout(wxCommandEvent
& event
);
113 // polling output of async processes
114 void OnTimer(wxTimerEvent
& event
);
115 void OnIdle(wxIdleEvent
& event
);
117 // for MyPipedProcess
118 void OnProcessTerminated(MyPipedProcess
*process
);
119 wxListBox
*GetLogListBox() const { return m_lbox
; }
122 void ShowOutput(const wxString
& cmd
,
123 const wxArrayString
& output
,
124 const wxString
& title
);
126 void DoAsyncExec(const wxString
& cmd
);
128 void AddAsyncProcess(MyPipedProcess
*process
)
130 if ( m_running
.IsEmpty() )
132 // we want to start getting the timer events to ensure that a
133 // steady stream of idle events comes in -- otherwise we
134 // wouldn't be able to poll the child process input
135 m_timerIdleWakeUp
.Start(100);
137 //else: the timer is already running
139 m_running
.Add(process
);
142 void RemoveAsyncProcess(MyPipedProcess
*process
)
144 m_running
.Remove(process
);
146 if ( m_running
.IsEmpty() )
148 // we don't need to get idle events all the time any more
149 m_timerIdleWakeUp
.Stop();
153 // the PID of the last process we launched asynchronously
156 // last command we executed
160 void OnDDEExec(wxCommandEvent
& event
);
161 void OnDDERequest(wxCommandEvent
& event
);
165 // last params of a DDE transaction
169 #endif // __WINDOWS__
173 MyProcessesArray m_running
;
175 // the idle event wake up timer
176 wxTimer m_timerIdleWakeUp
;
178 // any class wishing to process wxWidgets events must use this macro
179 DECLARE_EVENT_TABLE()
182 // ----------------------------------------------------------------------------
183 // MyPipeFrame: allows the user to communicate with the child process
184 // ----------------------------------------------------------------------------
186 class MyPipeFrame
: public wxFrame
189 MyPipeFrame(wxFrame
*parent
,
194 void OnTextEnter(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
195 void OnBtnSend(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
196 void OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
));
197 void OnBtnGet(wxCommandEvent
& WXUNUSED(event
)) { DoGet(); }
198 void OnBtnClose(wxCommandEvent
& WXUNUSED(event
)) { DoClose(); }
200 void OnClose(wxCloseEvent
& event
);
202 void OnProcessTerm(wxProcessEvent
& event
);
206 wxString
s(m_textOut
->GetValue());
208 m_out
.Write(s
.c_str(), s
.length());
218 void DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
);
220 void DisableOutput();
223 wxProcess
*m_process
;
225 wxOutputStream
&m_out
;
229 wxTextCtrl
*m_textOut
,
233 DECLARE_EVENT_TABLE()
236 // ----------------------------------------------------------------------------
237 // wxProcess-derived classes
238 // ----------------------------------------------------------------------------
240 // This is the handler for process termination events
241 class MyProcess
: public wxProcess
244 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
245 : wxProcess(parent
), m_cmd(cmd
)
250 // instead of overriding this virtual function we might as well process the
251 // event from it in the frame class - this might be more convenient in some
253 virtual void OnTerminate(int pid
, int status
);
260 // A specialization of MyProcess for redirecting the output
261 class MyPipedProcess
: public MyProcess
264 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
265 : MyProcess(parent
, cmd
)
270 virtual void OnTerminate(int pid
, int status
);
272 virtual bool HasInput();
275 // A version of MyPipedProcess which also sends input to the stdin of the
277 class MyPipedProcess2
: public MyPipedProcess
280 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
281 : MyPipedProcess(parent
, cmd
), m_input(input
)
285 virtual bool HasInput();
291 // ----------------------------------------------------------------------------
293 // ----------------------------------------------------------------------------
295 // IDs for the controls and the menu commands
315 Exec_Btn_Send
= 1000,
321 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
323 // ----------------------------------------------------------------------------
324 // event tables and other macros for wxWidgets
325 // ----------------------------------------------------------------------------
327 // the event tables connect the wxWidgets events with the functions (event
328 // handlers) which process them. It can be also done at run-time, but for the
329 // simple menu events like this the static method is much simpler.
330 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
331 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
332 EVT_MENU(Exec_Kill
, MyFrame::OnKill
)
333 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
335 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
336 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
337 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
338 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
339 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
341 EVT_MENU(Exec_POpen
, MyFrame::OnPOpen
)
343 EVT_MENU(Exec_OpenFile
, MyFrame::OnFileExec
)
344 EVT_MENU(Exec_OpenURL
, MyFrame::OnOpenURL
)
347 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
348 EVT_MENU(Exec_DDERequest
, MyFrame::OnDDERequest
)
349 #endif // __WINDOWS__
351 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
353 EVT_IDLE(MyFrame::OnIdle
)
355 EVT_TIMER(wxID_ANY
, MyFrame::OnTimer
)
358 BEGIN_EVENT_TABLE(MyPipeFrame
, wxFrame
)
359 EVT_BUTTON(Exec_Btn_Send
, MyPipeFrame::OnBtnSend
)
360 EVT_BUTTON(Exec_Btn_SendFile
, MyPipeFrame::OnBtnSendFile
)
361 EVT_BUTTON(Exec_Btn_Get
, MyPipeFrame::OnBtnGet
)
362 EVT_BUTTON(Exec_Btn_Close
, MyPipeFrame::OnBtnClose
)
364 EVT_TEXT_ENTER(wxID_ANY
, MyPipeFrame::OnTextEnter
)
366 EVT_CLOSE(MyPipeFrame::OnClose
)
368 EVT_END_PROCESS(wxID_ANY
, MyPipeFrame::OnProcessTerm
)
371 // Create a new application object: this macro will allow wxWidgets to create
372 // the application object during program execution (it's better than using a
373 // static object for many reasons) and also declares the accessor function
374 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
378 // ============================================================================
380 // ============================================================================
382 // ----------------------------------------------------------------------------
383 // the application class
384 // ----------------------------------------------------------------------------
386 // `Main program' equivalent: the program execution "starts" here
389 if ( !wxApp::OnInit() )
392 // Create the main application window
393 MyFrame
*frame
= new MyFrame(_T("Exec wxWidgets sample"),
394 wxDefaultPosition
, wxSize(500, 140));
396 // Show it and tell the application that it's our main window
400 // success: wxApp::OnRun() will be called which will enter the main message
401 // loop and the application will run. If we returned false here, the
402 // application would exit immediately.
406 // ----------------------------------------------------------------------------
408 // ----------------------------------------------------------------------------
411 #pragma warning(disable: 4355) // this used in base member initializer list
415 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
416 : wxFrame((wxFrame
*)NULL
, wxID_ANY
, title
, pos
, size
),
417 m_timerIdleWakeUp(this)
422 // we need this in order to allow the about menu relocation, since ABOUT is
423 // not the default id of the about menu
424 wxApp::s_macAboutMenuItemId
= Exec_About
;
428 wxMenu
*menuFile
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
429 menuFile
->Append(Exec_Kill
, _T("&Kill process...\tCtrl-K"),
430 _T("Kill a process by PID"));
431 menuFile
->AppendSeparator();
432 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-C"),
433 _T("Clear the log window"));
434 menuFile
->AppendSeparator();
435 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
437 wxMenu
*execMenu
= new wxMenu
;
438 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
439 _T("Launch a program and return when it terminates"));
440 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
441 _T("Launch a program and return immediately"));
442 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
443 _T("Launch a shell and execute a command in it"));
444 execMenu
->AppendSeparator();
445 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
446 _T("Launch a program and capture its output"));
447 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command..."),
448 _T("Pipe a string through a filter"));
449 execMenu
->Append(Exec_POpen
, _T("&Open a pipe to a command...\tCtrl-P"),
450 _T("Open a pipe to and from another program"));
452 execMenu
->AppendSeparator();
453 execMenu
->Append(Exec_OpenFile
, _T("Open &file...\tCtrl-F"),
454 _T("Launch the command to open this kind of files"));
455 execMenu
->Append(Exec_OpenURL
, _T("Open &URL...\tCtrl-U"),
456 _T("Launch the default browser with the given URL"));
458 execMenu
->AppendSeparator();
459 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
460 execMenu
->Append(Exec_DDERequest
, _T("Send DDE &request...\tCtrl-R"));
463 wxMenu
*helpMenu
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
464 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
466 // now append the freshly created menu to the menu bar...
467 wxMenuBar
*menuBar
= new wxMenuBar();
468 menuBar
->Append(menuFile
, _T("&File"));
469 menuBar
->Append(execMenu
, _T("&Exec"));
470 menuBar
->Append(helpMenu
, _T("&Help"));
472 // ... and attach this menu bar to the frame
475 // create the listbox in which we will show misc messages as they come
476 m_lbox
= new wxListBox(this, wxID_ANY
);
477 wxFont
font(12, wxFONTFAMILY_TELETYPE
, wxFONTSTYLE_NORMAL
,
478 wxFONTWEIGHT_NORMAL
);
480 m_lbox
->SetFont(font
);
483 // create a status bar just for fun (by default with 1 pane only)
485 SetStatusText(_T("Welcome to wxWidgets exec sample!"));
486 #endif // wxUSE_STATUSBAR
489 // ----------------------------------------------------------------------------
490 // event handlers: file and help menu
491 // ----------------------------------------------------------------------------
493 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
495 // true is to force the frame to close
499 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
504 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
506 wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"),
507 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
510 void MyFrame::OnKill(wxCommandEvent
& WXUNUSED(event
))
512 long pid
= wxGetNumberFromUser(_T("Please specify the process to kill"),
516 // we need the full unsigned int range
525 static const wxString signalNames
[] =
527 _T("Just test (SIGNONE)"),
528 _T("Hangup (SIGHUP)"),
529 _T("Interrupt (SIGINT)"),
530 _T("Quit (SIGQUIT)"),
531 _T("Illegal instruction (SIGILL)"),
532 _T("Trap (SIGTRAP)"),
533 _T("Abort (SIGABRT)"),
534 _T("Emulated trap (SIGEMT)"),
535 _T("FP exception (SIGFPE)"),
536 _T("Kill (SIGKILL)"),
538 _T("Segment violation (SIGSEGV)"),
539 _T("System (SIGSYS)"),
540 _T("Broken pipe (SIGPIPE)"),
541 _T("Alarm (SIGALRM)"),
542 _T("Terminate (SIGTERM)"),
545 int sig
= wxGetSingleChoiceIndex(_T("How to kill the process?"),
547 WXSIZEOF(signalNames
), signalNames
,
552 wxFAIL_MSG( _T("unexpected return value") );
580 if ( wxProcess::Exists(pid
) )
581 wxLogStatus(_T("Process %ld is running."), pid
);
583 wxLogStatus(_T("No process with pid = %ld."), pid
);
587 wxKillError rc
= wxProcess::Kill(pid
, (wxSignal
)sig
);
588 if ( rc
== wxKILL_OK
)
590 wxLogStatus(_T("Process %ld killed with signal %d."), pid
, sig
);
594 static const wxChar
*errorText
[] =
597 _T("signal not supported"),
598 _T("permission denied"),
599 _T("no such process"),
600 _T("unspecified error"),
603 wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
604 pid
, sig
, errorText
[rc
]);
609 // ----------------------------------------------------------------------------
610 // event handlers: exec menu
611 // ----------------------------------------------------------------------------
613 void MyFrame::DoAsyncExec(const wxString
& cmd
)
615 wxProcess
*process
= new MyProcess(this, cmd
);
616 m_pidLast
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
619 wxLogError( _T("Execution of '%s' failed."), cmd
.c_str() );
625 wxLogStatus( _T("Process %ld (%s) launched."),
626 m_pidLast
, cmd
.c_str() );
632 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
634 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
641 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
643 int code
= wxExecute(cmd
, wxEXEC_SYNC
);
645 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
651 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
653 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
663 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
665 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
672 int code
= wxShell(cmd
);
673 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
678 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
680 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
688 switch ( wxMessageBox(_T("Execute it synchronously?"),
690 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
706 wxArrayString output
, errors
;
707 int code
= wxExecute(cmd
, output
, errors
);
708 wxLogStatus(_T("command '%s' terminated with exit code %d."),
713 ShowOutput(cmd
, output
, _T("Output"));
714 ShowOutput(cmd
, errors
, _T("Errors"));
719 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
720 if ( !wxExecute(cmd
, wxEXEC_ASYNC
, process
) )
722 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
728 AddAsyncProcess(process
);
735 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
738 m_cmdLast
= _T("tr [a-z] [A-Z]");
740 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
747 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
752 // always execute the filter asynchronously
753 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
754 long pid
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
757 wxLogStatus( _T("Process %ld (%s) launched."), pid
, cmd
.c_str() );
759 AddAsyncProcess(process
);
763 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
771 void MyFrame::OnPOpen(wxCommandEvent
& WXUNUSED(event
))
773 wxString cmd
= wxGetTextFromUser(_T("Enter the command to launch: "),
779 wxProcess
*process
= wxProcess::Open(cmd
);
782 wxLogError(_T("Failed to launch the command."));
786 wxLogVerbose(_T("PID of the new process: %ld"), process
->GetPid());
788 wxOutputStream
*out
= process
->GetOutputStream();
791 wxLogError(_T("Failed to connect to child stdin"));
795 wxInputStream
*in
= process
->GetInputStream();
798 wxLogError(_T("Failed to connect to child stdout"));
802 new MyPipeFrame(this, cmd
, process
);
805 void MyFrame::OnFileExec(wxCommandEvent
& WXUNUSED(event
))
807 static wxString s_filename
;
812 filename
= wxLoadFileSelector(_T("any file"), NULL
, s_filename
, this);
813 #else // !wxUSE_FILEDLG
814 filename
= wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
816 #endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
818 if ( filename
.empty() )
821 s_filename
= filename
;
823 wxString ext
= filename
.AfterFirst(_T('.'));
824 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
827 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
833 bool ok
= ft
->GetOpenCommand(&cmd
,
834 wxFileType::MessageParameters(filename
));
838 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
846 void MyFrame::OnOpenURL(wxCommandEvent
& WXUNUSED(event
))
848 static wxString s_filename
;
850 wxString filename
= wxGetTextFromUser
858 if ( filename
.empty() )
861 s_filename
= filename
;
863 if ( !wxLaunchDefaultBrowser(s_filename
) )
864 wxLogError(_T("Failed to open URL \"%s\""), s_filename
.c_str());
867 // ----------------------------------------------------------------------------
869 // ----------------------------------------------------------------------------
873 bool MyFrame::GetDDEServer()
875 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
876 DIALOG_TITLE
, m_server
);
882 wxString topic
= wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE
, m_topic
);
888 wxString cmd
= wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE
, m_cmdDde
);
897 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
899 if ( !GetDDEServer() )
903 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
906 wxLogError(_T("Failed to connect to the DDE server '%s'."),
911 if ( !conn
->Execute(m_cmdDde
) )
913 wxLogError(_T("Failed to execute command '%s' via DDE."),
918 wxLogStatus(_T("Successfully executed DDE command"));
923 void MyFrame::OnDDERequest(wxCommandEvent
& WXUNUSED(event
))
925 if ( !GetDDEServer() )
929 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
932 wxLogError(_T("Failed to connect to the DDE server '%s'."),
937 if ( !conn
->Request(m_cmdDde
) )
939 wxLogError(_T("Failed to send request '%s' via DDE."),
944 wxLogStatus(_T("Successfully sent DDE request."));
949 #endif // __WINDOWS__
951 // ----------------------------------------------------------------------------
953 // ----------------------------------------------------------------------------
956 void MyFrame::OnIdle(wxIdleEvent
& event
)
958 size_t count
= m_running
.GetCount();
959 for ( size_t n
= 0; n
< count
; n
++ )
961 if ( m_running
[n
]->HasInput() )
968 void MyFrame::OnTimer(wxTimerEvent
& WXUNUSED(event
))
973 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
975 RemoveAsyncProcess(process
);
979 void MyFrame::ShowOutput(const wxString
& cmd
,
980 const wxArrayString
& output
,
981 const wxString
& title
)
983 size_t count
= output
.GetCount();
987 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
988 title
.c_str(), cmd
.c_str()));
990 for ( size_t n
= 0; n
< count
; n
++ )
992 m_lbox
->Append(output
[n
]);
995 m_lbox
->Append(wxString::Format(_T("--- End of %s ---"),
996 title
.Lower().c_str()));
999 // ----------------------------------------------------------------------------
1001 // ----------------------------------------------------------------------------
1003 void MyProcess::OnTerminate(int pid
, int status
)
1005 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
1006 pid
, m_cmd
.c_str(), status
);
1008 // we're not needed any more
1012 // ----------------------------------------------------------------------------
1014 // ----------------------------------------------------------------------------
1016 bool MyPipedProcess::HasInput()
1018 bool hasInput
= false;
1020 if ( IsInputAvailable() )
1022 wxTextInputStream
tis(*GetInputStream());
1024 // this assumes that the output is always line buffered
1026 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
1028 m_parent
->GetLogListBox()->Append(msg
);
1033 if ( IsErrorAvailable() )
1035 wxTextInputStream
tis(*GetErrorStream());
1037 // this assumes that the output is always line buffered
1039 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
1041 m_parent
->GetLogListBox()->Append(msg
);
1049 void MyPipedProcess::OnTerminate(int pid
, int status
)
1051 // show the rest of the output
1052 while ( HasInput() )
1055 m_parent
->OnProcessTerminated(this);
1057 MyProcess::OnTerminate(pid
, status
);
1060 // ----------------------------------------------------------------------------
1062 // ----------------------------------------------------------------------------
1064 bool MyPipedProcess2::HasInput()
1066 if ( !m_input
.empty() )
1068 wxTextOutputStream
os(*GetOutputStream());
1069 os
.WriteString(m_input
);
1074 // call us once again - may be we'll have output
1078 return MyPipedProcess::HasInput();
1081 // ============================================================================
1082 // MyPipeFrame implementation
1083 // ============================================================================
1085 MyPipeFrame::MyPipeFrame(wxFrame
*parent
,
1086 const wxString
& cmd
,
1088 : wxFrame(parent
, wxID_ANY
, cmd
),
1090 // in a real program we'd check that the streams are !NULL here
1091 m_out(*process
->GetOutputStream()),
1092 m_in(*process
->GetInputStream()),
1093 m_err(*process
->GetErrorStream())
1095 m_process
->SetNextHandler(this);
1097 wxPanel
*panel
= new wxPanel(this, wxID_ANY
);
1099 m_textOut
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1100 wxDefaultPosition
, wxDefaultSize
,
1101 wxTE_PROCESS_ENTER
);
1102 m_textIn
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1103 wxDefaultPosition
, wxDefaultSize
,
1104 wxTE_MULTILINE
| wxTE_RICH
);
1105 m_textIn
->SetEditable(false);
1106 m_textErr
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1107 wxDefaultPosition
, wxDefaultSize
,
1108 wxTE_MULTILINE
| wxTE_RICH
);
1109 m_textErr
->SetEditable(false);
1111 wxSizer
*sizerTop
= new wxBoxSizer(wxVERTICAL
);
1112 sizerTop
->Add(m_textOut
, 0, wxGROW
| wxALL
, 5);
1114 wxSizer
*sizerBtns
= new wxBoxSizer(wxHORIZONTAL
);
1116 Add(new wxButton(panel
, Exec_Btn_Send
, _T("&Send")), 0, wxALL
, 5);
1118 Add(new wxButton(panel
, Exec_Btn_SendFile
, _T("&File...")), 0, wxALL
, 5);
1120 Add(new wxButton(panel
, Exec_Btn_Get
, _T("&Get")), 0, wxALL
, 5);
1122 Add(new wxButton(panel
, Exec_Btn_Close
, _T("&Close")), 0, wxALL
, 5);
1124 sizerTop
->Add(sizerBtns
, 0, wxCENTRE
| wxALL
, 5);
1125 sizerTop
->Add(m_textIn
, 1, wxGROW
| wxALL
, 5);
1126 sizerTop
->Add(m_textErr
, 1, wxGROW
| wxALL
, 5);
1128 panel
->SetSizer(sizerTop
);
1129 sizerTop
->Fit(this);
1134 void MyPipeFrame::OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
))
1137 wxFileDialog
filedlg(this, _T("Select file to send"));
1138 if ( filedlg
.ShowModal() != wxID_OK
)
1141 wxFFile
file(filedlg
.GetFilename(), _T("r"));
1143 if ( !file
.IsOpened() || !file
.ReadAll(&data
) )
1146 // can't write the entire string at once, this risk overflowing the pipe
1147 // and we would dead lock
1148 size_t len
= data
.length();
1149 const wxChar
*pc
= data
.c_str();
1152 const size_t CHUNK_SIZE
= 4096;
1153 m_out
.Write(pc
, len
> CHUNK_SIZE
? CHUNK_SIZE
: len
);
1155 // note that not all data could have been written as we don't block on
1156 // the write end of the pipe
1157 const size_t lenChunk
= m_out
.LastWrite();
1164 #endif // wxUSE_FILEDLG
1167 void MyPipeFrame::DoGet()
1169 // we don't have any way to be notified when any input appears on the
1170 // stream so we have to poll it :-(
1171 DoGetFromStream(m_textIn
, m_in
);
1172 DoGetFromStream(m_textErr
, m_err
);
1175 void MyPipeFrame::DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
)
1177 while ( in
.CanRead() )
1179 wxChar buffer
[4096];
1180 buffer
[in
.Read(buffer
, WXSIZEOF(buffer
) - 1).LastRead()] = _T('\0');
1182 text
->AppendText(buffer
);
1186 void MyPipeFrame::DoClose()
1188 m_process
->CloseOutput();
1193 void MyPipeFrame::DisableInput()
1195 m_textOut
->SetEditable(false);
1196 FindWindow(Exec_Btn_Send
)->Disable();
1197 FindWindow(Exec_Btn_SendFile
)->Disable();
1198 FindWindow(Exec_Btn_Close
)->Disable();
1201 void MyPipeFrame::DisableOutput()
1203 FindWindow(Exec_Btn_Get
)->Disable();
1206 void MyPipeFrame::OnClose(wxCloseEvent
& event
)
1210 // we're not interested in getting the process termination notification
1211 // if we are closing it ourselves
1212 wxProcess
*process
= m_process
;
1214 process
->SetNextHandler(NULL
);
1216 process
->CloseOutput();
1222 void MyPipeFrame::OnProcessTerm(wxProcessEvent
& WXUNUSED(event
))
1229 wxLogWarning(_T("The other process has terminated, closing"));