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 #if defined(__GNUG__) && !defined(__APPLE__)
21 #pragma implementation
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
32 // for all others, include the necessary headers (this file is usually all you
33 // need because it includes almost all "standard" wxWidgets headers
45 #include "wx/msgdlg.h"
46 #include "wx/textdlg.h"
47 #include "wx/filedlg.h"
48 #include "wx/choicdlg.h"
50 #include "wx/button.h"
51 #include "wx/textctrl.h"
52 #include "wx/listbox.h"
57 #include "wx/txtstrm.h"
58 #include "wx/numdlg.h"
61 #include "wx/process.h"
63 #include "wx/mimetype.h"
69 // ----------------------------------------------------------------------------
70 // the usual application and main frame classes
71 // ----------------------------------------------------------------------------
73 // Define a new application type, each program should derive a class from wxApp
74 class MyApp
: public wxApp
77 // override base class virtuals
78 // ----------------------------
80 // this one is called on application startup and is a good place for the app
81 // initialization (doing it here and not in the ctor allows to have an error
82 // return: if OnInit() returns false, the application terminates)
83 virtual bool OnInit();
86 // Define an array of process pointers used by MyFrame
88 WX_DEFINE_ARRAY_PTR(MyPipedProcess
*, MyProcessesArray
);
90 // Define a new frame type: this is going to be our main frame
91 class MyFrame
: public wxFrame
95 MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
);
97 // event handlers (these functions should _not_ be virtual)
98 void OnQuit(wxCommandEvent
& event
);
100 void OnKill(wxCommandEvent
& event
);
102 void OnClear(wxCommandEvent
& event
);
104 void OnSyncExec(wxCommandEvent
& event
);
105 void OnAsyncExec(wxCommandEvent
& event
);
106 void OnShell(wxCommandEvent
& event
);
107 void OnExecWithRedirect(wxCommandEvent
& event
);
108 void OnExecWithPipe(wxCommandEvent
& event
);
110 void OnPOpen(wxCommandEvent
& event
);
112 void OnFileExec(wxCommandEvent
& event
);
114 void OnAbout(wxCommandEvent
& event
);
116 // polling output of async processes
117 void OnTimer(wxTimerEvent
& event
);
118 void OnIdle(wxIdleEvent
& event
);
120 // for MyPipedProcess
121 void OnProcessTerminated(MyPipedProcess
*process
);
122 wxListBox
*GetLogListBox() const { return m_lbox
; }
125 void ShowOutput(const wxString
& cmd
,
126 const wxArrayString
& output
,
127 const wxString
& title
);
129 void DoAsyncExec(const wxString
& cmd
);
131 void AddAsyncProcess(MyPipedProcess
*process
)
133 if ( m_running
.IsEmpty() )
135 // we want to start getting the timer events to ensure that a
136 // steady stream of idle events comes in -- otherwise we
137 // wouldn't be able to poll the child process input
138 m_timerIdleWakeUp
.Start(100);
140 //else: the timer is already running
142 m_running
.Add(process
);
145 void RemoveAsyncProcess(MyPipedProcess
*process
)
147 m_running
.Remove(process
);
149 if ( m_running
.IsEmpty() )
151 // we don't need to get idle events all the time any more
152 m_timerIdleWakeUp
.Stop();
156 // the PID of the last process we launched asynchronously
159 // last command we executed
163 void OnDDEExec(wxCommandEvent
& event
);
164 void OnDDERequest(wxCommandEvent
& event
);
168 // last params of a DDE transaction
172 #endif // __WINDOWS__
176 MyProcessesArray m_running
;
178 // the idle event wake up timer
179 wxTimer m_timerIdleWakeUp
;
181 // any class wishing to process wxWidgets events must use this macro
182 DECLARE_EVENT_TABLE()
185 // ----------------------------------------------------------------------------
186 // MyPipeFrame: allows the user to communicate with the child process
187 // ----------------------------------------------------------------------------
189 class MyPipeFrame
: public wxFrame
192 MyPipeFrame(wxFrame
*parent
,
197 void OnTextEnter(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
198 void OnBtnSend(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
199 void OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
));
200 void OnBtnGet(wxCommandEvent
& WXUNUSED(event
)) { DoGet(); }
201 void OnBtnClose(wxCommandEvent
& WXUNUSED(event
)) { DoClose(); }
203 void OnClose(wxCloseEvent
& event
);
205 void OnProcessTerm(wxProcessEvent
& event
);
209 wxString
s(m_textOut
->GetValue());
211 m_out
.Write(s
.c_str(), s
.length());
221 void DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
);
223 void DisableOutput();
226 wxProcess
*m_process
;
228 wxOutputStream
&m_out
;
232 wxTextCtrl
*m_textOut
,
236 DECLARE_EVENT_TABLE()
239 // ----------------------------------------------------------------------------
240 // wxProcess-derived classes
241 // ----------------------------------------------------------------------------
243 // This is the handler for process termination events
244 class MyProcess
: public wxProcess
247 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
248 : wxProcess(parent
), m_cmd(cmd
)
253 // instead of overriding this virtual function we might as well process the
254 // event from it in the frame class - this might be more convenient in some
256 virtual void OnTerminate(int pid
, int status
);
263 // A specialization of MyProcess for redirecting the output
264 class MyPipedProcess
: public MyProcess
267 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
268 : MyProcess(parent
, cmd
)
273 virtual void OnTerminate(int pid
, int status
);
275 virtual bool HasInput();
278 // A version of MyPipedProcess which also sends input to the stdin of the
280 class MyPipedProcess2
: public MyPipedProcess
283 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
284 : MyPipedProcess(parent
, cmd
), m_input(input
)
288 virtual bool HasInput();
294 // ----------------------------------------------------------------------------
296 // ----------------------------------------------------------------------------
298 // IDs for the controls and the menu commands
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_AsyncExec
, MyFrame::OnAsyncExec
)
339 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
340 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
341 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
343 EVT_MENU(Exec_POpen
, MyFrame::OnPOpen
)
345 EVT_MENU(Exec_OpenFile
, MyFrame::OnFileExec
)
348 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
349 EVT_MENU(Exec_DDERequest
, MyFrame::OnDDERequest
)
350 #endif // __WINDOWS__
352 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
354 EVT_IDLE(MyFrame::OnIdle
)
356 EVT_TIMER(wxID_ANY
, MyFrame::OnTimer
)
359 BEGIN_EVENT_TABLE(MyPipeFrame
, wxFrame
)
360 EVT_BUTTON(Exec_Btn_Send
, MyPipeFrame::OnBtnSend
)
361 EVT_BUTTON(Exec_Btn_SendFile
, MyPipeFrame::OnBtnSendFile
)
362 EVT_BUTTON(Exec_Btn_Get
, MyPipeFrame::OnBtnGet
)
363 EVT_BUTTON(Exec_Btn_Close
, MyPipeFrame::OnBtnClose
)
365 EVT_TEXT_ENTER(wxID_ANY
, MyPipeFrame::OnTextEnter
)
367 EVT_CLOSE(MyPipeFrame::OnClose
)
369 EVT_END_PROCESS(wxID_ANY
, MyPipeFrame::OnProcessTerm
)
372 // Create a new application object: this macro will allow wxWidgets to create
373 // the application object during program execution (it's better than using a
374 // static object for many reasons) and also declares the accessor function
375 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
379 // ============================================================================
381 // ============================================================================
383 // ----------------------------------------------------------------------------
384 // the application class
385 // ----------------------------------------------------------------------------
387 // `Main program' equivalent: the program execution "starts" here
390 // Create the main application window
391 MyFrame
*frame
= new MyFrame(_T("Exec wxWidgets sample"),
392 wxDefaultPosition
, wxSize(500, 140));
394 // Show it and tell the application that it's our main window
398 // success: wxApp::OnRun() will be called which will enter the main message
399 // loop and the application will run. If we returned false here, the
400 // application would exit immediately.
404 // ----------------------------------------------------------------------------
406 // ----------------------------------------------------------------------------
409 #pragma warning(disable: 4355) // this used in base member initializer list
413 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
414 : wxFrame((wxFrame
*)NULL
, wxID_ANY
, title
, pos
, size
),
415 m_timerIdleWakeUp(this)
420 // we need this in order to allow the about menu relocation, since ABOUT is
421 // not the default id of the about menu
422 wxApp::s_macAboutMenuItemId
= Exec_About
;
426 wxMenu
*menuFile
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
427 menuFile
->Append(Exec_Kill
, _T("&Kill process...\tCtrl-K"),
428 _T("Kill a process by PID"));
429 menuFile
->AppendSeparator();
430 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-C"),
431 _T("Clear the log window"));
432 menuFile
->AppendSeparator();
433 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
435 wxMenu
*execMenu
= new wxMenu
;
436 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
437 _T("Launch a program and return when it terminates"));
438 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
439 _T("Launch a program and return immediately"));
440 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
441 _T("Launch a shell and execute a command in it"));
442 execMenu
->AppendSeparator();
443 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
444 _T("Launch a program and capture its output"));
445 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command..."),
446 _T("Pipe a string through a filter"));
447 execMenu
->Append(Exec_POpen
, _T("&Open a pipe to a command...\tCtrl-P"),
448 _T("Open a pipe to and from another program"));
450 execMenu
->AppendSeparator();
451 execMenu
->Append(Exec_OpenFile
, _T("Open &file...\tCtrl-F"),
452 _T("Launch the command to open this kind of files"));
454 execMenu
->AppendSeparator();
455 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
456 execMenu
->Append(Exec_DDERequest
, _T("Send DDE &request...\tCtrl-R"));
459 wxMenu
*helpMenu
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
460 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
462 // now append the freshly created menu to the menu bar...
463 wxMenuBar
*menuBar
= new wxMenuBar();
464 menuBar
->Append(menuFile
, _T("&File"));
465 menuBar
->Append(execMenu
, _T("&Exec"));
466 menuBar
->Append(helpMenu
, _T("&Help"));
468 // ... and attach this menu bar to the frame
471 // create the listbox in which we will show misc messages as they come
472 m_lbox
= new wxListBox(this, wxID_ANY
);
473 wxFont
font(12, wxFONTFAMILY_TELETYPE
, wxFONTSTYLE_NORMAL
,
474 wxFONTWEIGHT_NORMAL
);
476 m_lbox
->SetFont(font
);
479 // create a status bar just for fun (by default with 1 pane only)
481 SetStatusText(_T("Welcome to wxWidgets exec sample!"));
482 #endif // wxUSE_STATUSBAR
485 // ----------------------------------------------------------------------------
486 // event handlers: file and help menu
487 // ----------------------------------------------------------------------------
489 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
491 // true is to force the frame to close
495 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
500 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
502 wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"),
503 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
506 void MyFrame::OnKill(wxCommandEvent
& WXUNUSED(event
))
508 long pid
= wxGetNumberFromUser(_T("Please specify the process to kill"),
512 // we need the full unsigned int range
521 static const wxString signalNames
[] =
523 _T("Just test (SIGNONE)"),
524 _T("Hangup (SIGHUP)"),
525 _T("Interrupt (SIGINT)"),
526 _T("Quit (SIGQUIT)"),
527 _T("Illegal instruction (SIGILL)"),
528 _T("Trap (SIGTRAP)"),
529 _T("Abort (SIGABRT)"),
530 _T("Emulated trap (SIGEMT)"),
531 _T("FP exception (SIGFPE)"),
532 _T("Kill (SIGKILL)"),
534 _T("Segment violation (SIGSEGV)"),
535 _T("System (SIGSYS)"),
536 _T("Broken pipe (SIGPIPE)"),
537 _T("Alarm (SIGALRM)"),
538 _T("Terminate (SIGTERM)"),
541 int sig
= wxGetSingleChoiceIndex(_T("How to kill the process?"),
543 WXSIZEOF(signalNames
), signalNames
,
548 wxFAIL_MSG( _T("unexpected return value") );
576 if ( wxProcess::Exists(pid
) )
577 wxLogStatus(_T("Process %ld is running."), pid
);
579 wxLogStatus(_T("No process with pid = %ld."), pid
);
583 wxKillError rc
= wxProcess::Kill(pid
, (wxSignal
)sig
);
584 if ( rc
== wxKILL_OK
)
586 wxLogStatus(_T("Process %ld killed with signal %d."), pid
, sig
);
590 static const wxChar
*errorText
[] =
593 _T("signal not supported"),
594 _T("permission denied"),
595 _T("no such process"),
596 _T("unspecified error"),
599 wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
600 pid
, sig
, errorText
[rc
]);
605 // ----------------------------------------------------------------------------
606 // event handlers: exec menu
607 // ----------------------------------------------------------------------------
609 void MyFrame::DoAsyncExec(const wxString
& cmd
)
611 wxProcess
*process
= new MyProcess(this, cmd
);
612 m_pidLast
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
615 wxLogError( _T("Execution of '%s' failed."), cmd
.c_str() );
621 wxLogStatus( _T("Process %ld (%s) launched."),
622 m_pidLast
, cmd
.c_str() );
628 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
630 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
637 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
639 int code
= wxExecute(cmd
, wxEXEC_SYNC
);
641 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
647 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
649 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
659 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
661 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
668 int code
= wxShell(cmd
);
669 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
674 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
676 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
684 switch ( wxMessageBox(_T("Execute it synchronously?"),
686 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
702 wxArrayString output
, errors
;
703 int code
= wxExecute(cmd
, output
, errors
);
704 wxLogStatus(_T("command '%s' terminated with exit code %d."),
709 ShowOutput(cmd
, output
, _T("Output"));
710 ShowOutput(cmd
, errors
, _T("Errors"));
715 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
716 if ( !wxExecute(cmd
, wxEXEC_ASYNC
, process
) )
718 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
724 AddAsyncProcess(process
);
731 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
734 m_cmdLast
= _T("tr [a-z] [A-Z]");
736 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
743 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
748 // always execute the filter asynchronously
749 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
750 long pid
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
753 wxLogStatus( _T("Process %ld (%s) launched."), pid
, cmd
.c_str() );
755 AddAsyncProcess(process
);
759 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
767 void MyFrame::OnPOpen(wxCommandEvent
& WXUNUSED(event
))
769 wxString cmd
= wxGetTextFromUser(_T("Enter the command to launch: "),
775 wxProcess
*process
= wxProcess::Open(cmd
);
778 wxLogError(_T("Failed to launch the command."));
782 wxOutputStream
*out
= process
->GetOutputStream();
785 wxLogError(_T("Failed to connect to child stdin"));
789 wxInputStream
*in
= process
->GetInputStream();
792 wxLogError(_T("Failed to connect to child stdout"));
796 new MyPipeFrame(this, cmd
, process
);
799 void MyFrame::OnFileExec(wxCommandEvent
& WXUNUSED(event
))
801 static wxString s_filename
;
806 filename
= wxLoadFileSelector(wxEmptyString
, wxEmptyString
, s_filename
);
807 #endif // wxUSE_FILEDLG
809 if ( filename
.empty() )
812 s_filename
= filename
;
814 wxString ext
= filename
.AfterFirst(_T('.'));
815 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
818 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
824 bool ok
= ft
->GetOpenCommand(&cmd
,
825 wxFileType::MessageParameters(filename
));
829 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
837 // ----------------------------------------------------------------------------
839 // ----------------------------------------------------------------------------
843 bool MyFrame::GetDDEServer()
845 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
846 DIALOG_TITLE
, m_server
);
852 wxString topic
= wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE
, m_topic
);
858 wxString cmd
= wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE
, m_cmdDde
);
867 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
869 if ( !GetDDEServer() )
873 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
876 wxLogError(_T("Failed to connect to the DDE server '%s'."),
881 if ( !conn
->Execute(m_cmdDde
) )
883 wxLogError(_T("Failed to execute command '%s' via DDE."),
888 wxLogStatus(_T("Successfully executed DDE command"));
893 void MyFrame::OnDDERequest(wxCommandEvent
& WXUNUSED(event
))
895 if ( !GetDDEServer() )
899 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
902 wxLogError(_T("Failed to connect to the DDE server '%s'."),
907 if ( !conn
->Request(m_cmdDde
) )
909 wxLogError(_T("Failed to send request '%s' via DDE."),
914 wxLogStatus(_T("Successfully sent DDE request."));
919 #endif // __WINDOWS__
921 // ----------------------------------------------------------------------------
923 // ----------------------------------------------------------------------------
926 void MyFrame::OnIdle(wxIdleEvent
& event
)
928 size_t count
= m_running
.GetCount();
929 for ( size_t n
= 0; n
< count
; n
++ )
931 if ( m_running
[n
]->HasInput() )
938 void MyFrame::OnTimer(wxTimerEvent
& WXUNUSED(event
))
943 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
945 RemoveAsyncProcess(process
);
949 void MyFrame::ShowOutput(const wxString
& cmd
,
950 const wxArrayString
& output
,
951 const wxString
& title
)
953 size_t count
= output
.GetCount();
957 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
958 title
.c_str(), cmd
.c_str()));
960 for ( size_t n
= 0; n
< count
; n
++ )
962 m_lbox
->Append(output
[n
]);
965 m_lbox
->Append(wxString::Format(_T("--- End of %s ---"),
966 title
.Lower().c_str()));
969 // ----------------------------------------------------------------------------
971 // ----------------------------------------------------------------------------
973 void MyProcess::OnTerminate(int pid
, int status
)
975 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
976 pid
, m_cmd
.c_str(), status
);
978 // we're not needed any more
982 // ----------------------------------------------------------------------------
984 // ----------------------------------------------------------------------------
986 bool MyPipedProcess::HasInput()
988 bool hasInput
= false;
990 if ( IsInputAvailable() )
992 wxTextInputStream
tis(*GetInputStream());
994 // this assumes that the output is always line buffered
996 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
998 m_parent
->GetLogListBox()->Append(msg
);
1003 if ( IsErrorAvailable() )
1005 wxTextInputStream
tis(*GetErrorStream());
1007 // this assumes that the output is always line buffered
1009 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
1011 m_parent
->GetLogListBox()->Append(msg
);
1019 void MyPipedProcess::OnTerminate(int pid
, int status
)
1021 // show the rest of the output
1022 while ( HasInput() )
1025 m_parent
->OnProcessTerminated(this);
1027 MyProcess::OnTerminate(pid
, status
);
1030 // ----------------------------------------------------------------------------
1032 // ----------------------------------------------------------------------------
1034 bool MyPipedProcess2::HasInput()
1036 if ( !m_input
.empty() )
1038 wxTextOutputStream
os(*GetOutputStream());
1039 os
.WriteString(m_input
);
1044 // call us once again - may be we'll have output
1048 return MyPipedProcess::HasInput();
1051 // ============================================================================
1052 // MyPipeFrame implementation
1053 // ============================================================================
1055 MyPipeFrame::MyPipeFrame(wxFrame
*parent
,
1056 const wxString
& cmd
,
1058 : wxFrame(parent
, wxID_ANY
, cmd
),
1060 // in a real program we'd check that the streams are !NULL here
1061 m_out(*process
->GetOutputStream()),
1062 m_in(*process
->GetInputStream()),
1063 m_err(*process
->GetErrorStream())
1065 m_process
->SetNextHandler(this);
1067 wxPanel
*panel
= new wxPanel(this, wxID_ANY
);
1069 m_textOut
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1070 wxDefaultPosition
, wxDefaultSize
,
1071 wxTE_PROCESS_ENTER
);
1072 m_textIn
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1073 wxDefaultPosition
, wxDefaultSize
,
1074 wxTE_MULTILINE
| wxTE_RICH
);
1075 m_textIn
->SetEditable(false);
1076 m_textErr
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1077 wxDefaultPosition
, wxDefaultSize
,
1078 wxTE_MULTILINE
| wxTE_RICH
);
1079 m_textErr
->SetEditable(false);
1081 wxSizer
*sizerTop
= new wxBoxSizer(wxVERTICAL
);
1082 sizerTop
->Add(m_textOut
, 0, wxGROW
| wxALL
, 5);
1084 wxSizer
*sizerBtns
= new wxBoxSizer(wxHORIZONTAL
);
1086 Add(new wxButton(panel
, Exec_Btn_Send
, _T("&Send")), 0, wxALL
, 5);
1088 Add(new wxButton(panel
, Exec_Btn_SendFile
, _T("&File...")), 0, wxALL
, 5);
1090 Add(new wxButton(panel
, Exec_Btn_Get
, _T("&Get")), 0, wxALL
, 5);
1092 Add(new wxButton(panel
, Exec_Btn_Close
, _T("&Close")), 0, wxALL
, 5);
1094 sizerTop
->Add(sizerBtns
, 0, wxCENTRE
| wxALL
, 5);
1095 sizerTop
->Add(m_textIn
, 1, wxGROW
| wxALL
, 5);
1096 sizerTop
->Add(m_textErr
, 1, wxGROW
| wxALL
, 5);
1098 panel
->SetSizer(sizerTop
);
1099 sizerTop
->Fit(this);
1104 void MyPipeFrame::OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
))
1107 wxFileDialog
filedlg(this, _T("Select file to send"));
1108 if ( filedlg
.ShowModal() != wxID_OK
)
1111 wxFFile
file(filedlg
.GetFilename(), _T("r"));
1113 if ( !file
.IsOpened() || !file
.ReadAll(&data
) )
1116 // can't write the entire string at once, this risk overflowing the pipe
1117 // and we would dead lock
1118 size_t len
= data
.length();
1119 const wxChar
*pc
= data
.c_str();
1122 const size_t CHUNK_SIZE
= 4096;
1123 m_out
.Write(pc
, len
> CHUNK_SIZE
? CHUNK_SIZE
: len
);
1125 // note that not all data could have been written as we don't block on
1126 // the write end of the pipe
1127 const size_t lenChunk
= m_out
.LastWrite();
1134 #endif // wxUSE_FILEDLG
1137 void MyPipeFrame::DoGet()
1139 // we don't have any way to be notified when any input appears on the
1140 // stream so we have to poll it :-(
1141 DoGetFromStream(m_textIn
, m_in
);
1142 DoGetFromStream(m_textErr
, m_err
);
1145 void MyPipeFrame::DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
)
1147 while ( in
.CanRead() )
1149 wxChar buffer
[4096];
1150 buffer
[in
.Read(buffer
, WXSIZEOF(buffer
) - 1).LastRead()] = _T('\0');
1152 text
->AppendText(buffer
);
1156 void MyPipeFrame::DoClose()
1158 m_process
->CloseOutput();
1163 void MyPipeFrame::DisableInput()
1165 m_textOut
->SetEditable(false);
1166 FindWindow(Exec_Btn_Send
)->Disable();
1167 FindWindow(Exec_Btn_SendFile
)->Disable();
1168 FindWindow(Exec_Btn_Close
)->Disable();
1171 void MyPipeFrame::DisableOutput()
1173 FindWindow(Exec_Btn_Get
)->Disable();
1176 void MyPipeFrame::OnClose(wxCloseEvent
& event
)
1180 // we're not interested in getting the process termination notification
1181 // if we are closing it ourselves
1182 wxProcess
*process
= m_process
;
1184 process
->SetNextHandler(NULL
);
1186 process
->CloseOutput();
1192 void MyPipeFrame::OnProcessTerm(wxProcessEvent
& WXUNUSED(event
))
1199 wxLogWarning(_T("The other process has terminated, closing"));