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 OnBeginBusyCursor(wxCommandEvent
& event
);
101 void OnEndBusyCursor(wxCommandEvent
& event
);
103 void OnSyncExec(wxCommandEvent
& event
);
104 void OnSyncNoEventsExec(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
);
113 void OnOpenURL(wxCommandEvent
& event
);
115 void OnAbout(wxCommandEvent
& event
);
117 // polling output of async processes
118 void OnTimer(wxTimerEvent
& event
);
119 void OnIdle(wxIdleEvent
& event
);
121 // for MyPipedProcess
122 void OnProcessTerminated(MyPipedProcess
*process
);
123 wxListBox
*GetLogListBox() const { return m_lbox
; }
126 void ShowOutput(const wxString
& cmd
,
127 const wxArrayString
& output
,
128 const wxString
& title
);
130 void DoAsyncExec(const wxString
& cmd
);
132 void AddAsyncProcess(MyPipedProcess
*process
)
134 if ( m_running
.IsEmpty() )
136 // we want to start getting the timer events to ensure that a
137 // steady stream of idle events comes in -- otherwise we
138 // wouldn't be able to poll the child process input
139 m_timerIdleWakeUp
.Start(100);
141 //else: the timer is already running
143 m_running
.Add(process
);
146 void RemoveAsyncProcess(MyPipedProcess
*process
)
148 m_running
.Remove(process
);
150 if ( m_running
.IsEmpty() )
152 // we don't need to get idle events all the time any more
153 m_timerIdleWakeUp
.Stop();
157 // the PID of the last process we launched asynchronously
160 // last command we executed
164 void OnDDEExec(wxCommandEvent
& event
);
165 void OnDDERequest(wxCommandEvent
& event
);
169 // last params of a DDE transaction
173 #endif // __WINDOWS__
177 MyProcessesArray m_running
;
179 // the idle event wake up timer
180 wxTimer m_timerIdleWakeUp
;
182 // any class wishing to process wxWidgets events must use this macro
183 DECLARE_EVENT_TABLE()
186 // ----------------------------------------------------------------------------
187 // MyPipeFrame: allows the user to communicate with the child process
188 // ----------------------------------------------------------------------------
190 class MyPipeFrame
: public wxFrame
193 MyPipeFrame(wxFrame
*parent
,
198 void OnTextEnter(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
199 void OnBtnSend(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
200 void OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
));
201 void OnBtnGet(wxCommandEvent
& WXUNUSED(event
)) { DoGet(); }
202 void OnBtnClose(wxCommandEvent
& WXUNUSED(event
)) { DoClose(); }
204 void OnClose(wxCloseEvent
& event
);
206 void OnProcessTerm(wxProcessEvent
& event
);
210 wxString
s(m_textOut
->GetValue());
212 m_out
.Write(s
.c_str(), s
.length());
222 void DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
);
224 void DisableOutput();
227 wxProcess
*m_process
;
229 wxOutputStream
&m_out
;
233 wxTextCtrl
*m_textOut
,
237 DECLARE_EVENT_TABLE()
240 // ----------------------------------------------------------------------------
241 // wxProcess-derived classes
242 // ----------------------------------------------------------------------------
244 // This is the handler for process termination events
245 class MyProcess
: public wxProcess
248 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
249 : wxProcess(parent
), m_cmd(cmd
)
254 // instead of overriding this virtual function we might as well process the
255 // event from it in the frame class - this might be more convenient in some
257 virtual void OnTerminate(int pid
, int status
);
264 // A specialization of MyProcess for redirecting the output
265 class MyPipedProcess
: public MyProcess
268 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
269 : MyProcess(parent
, cmd
)
274 virtual void OnTerminate(int pid
, int status
);
276 virtual bool HasInput();
279 // A version of MyPipedProcess which also sends input to the stdin of the
281 class MyPipedProcess2
: public MyPipedProcess
284 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
285 : MyPipedProcess(parent
, cmd
), m_input(input
)
289 virtual bool HasInput();
295 // ----------------------------------------------------------------------------
297 // ----------------------------------------------------------------------------
299 // IDs for the controls and the menu commands
306 Exec_BeginBusyCursor
,
309 Exec_SyncNoEventsExec
,
322 Exec_Btn_Send
= 1000,
328 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
330 // ----------------------------------------------------------------------------
331 // event tables and other macros for wxWidgets
332 // ----------------------------------------------------------------------------
334 // the event tables connect the wxWidgets events with the functions (event
335 // handlers) which process them. It can be also done at run-time, but for the
336 // simple menu events like this the static method is much simpler.
337 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
338 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
339 EVT_MENU(Exec_Kill
, MyFrame::OnKill
)
340 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
341 EVT_MENU(Exec_BeginBusyCursor
, MyFrame::OnBeginBusyCursor
)
342 EVT_MENU(Exec_EndBusyCursor
, MyFrame::OnEndBusyCursor
)
344 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
345 EVT_MENU(Exec_SyncNoEventsExec
, MyFrame::OnSyncNoEventsExec
)
346 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
347 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
348 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
349 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
351 EVT_MENU(Exec_POpen
, MyFrame::OnPOpen
)
353 EVT_MENU(Exec_OpenFile
, MyFrame::OnFileExec
)
354 EVT_MENU(Exec_OpenURL
, MyFrame::OnOpenURL
)
357 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
358 EVT_MENU(Exec_DDERequest
, MyFrame::OnDDERequest
)
359 #endif // __WINDOWS__
361 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
363 EVT_IDLE(MyFrame::OnIdle
)
365 EVT_TIMER(wxID_ANY
, MyFrame::OnTimer
)
368 BEGIN_EVENT_TABLE(MyPipeFrame
, wxFrame
)
369 EVT_BUTTON(Exec_Btn_Send
, MyPipeFrame::OnBtnSend
)
370 EVT_BUTTON(Exec_Btn_SendFile
, MyPipeFrame::OnBtnSendFile
)
371 EVT_BUTTON(Exec_Btn_Get
, MyPipeFrame::OnBtnGet
)
372 EVT_BUTTON(Exec_Btn_Close
, MyPipeFrame::OnBtnClose
)
374 EVT_TEXT_ENTER(wxID_ANY
, MyPipeFrame::OnTextEnter
)
376 EVT_CLOSE(MyPipeFrame::OnClose
)
378 EVT_END_PROCESS(wxID_ANY
, MyPipeFrame::OnProcessTerm
)
381 // Create a new application object: this macro will allow wxWidgets to create
382 // the application object during program execution (it's better than using a
383 // static object for many reasons) and also declares the accessor function
384 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
388 // ============================================================================
390 // ============================================================================
392 // ----------------------------------------------------------------------------
393 // the application class
394 // ----------------------------------------------------------------------------
396 // `Main program' equivalent: the program execution "starts" here
399 if ( !wxApp::OnInit() )
402 // Create the main application window
403 MyFrame
*frame
= new MyFrame(_T("Exec wxWidgets sample"),
404 wxDefaultPosition
, wxSize(500, 140));
406 // Show it and tell the application that it's our main window
410 // success: wxApp::OnRun() will be called which will enter the main message
411 // loop and the application will run. If we returned false here, the
412 // application would exit immediately.
416 // ----------------------------------------------------------------------------
418 // ----------------------------------------------------------------------------
421 #pragma warning(disable: 4355) // this used in base member initializer list
425 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
426 : wxFrame((wxFrame
*)NULL
, wxID_ANY
, title
, pos
, size
),
427 m_timerIdleWakeUp(this)
432 // we need this in order to allow the about menu relocation, since ABOUT is
433 // not the default id of the about menu
434 wxApp::s_macAboutMenuItemId
= Exec_About
;
438 wxMenu
*menuFile
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
439 menuFile
->Append(Exec_Kill
, _T("&Kill process...\tCtrl-K"),
440 _T("Kill a process by PID"));
441 menuFile
->AppendSeparator();
442 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-L"),
443 _T("Clear the log window"));
444 menuFile
->AppendSeparator();
445 menuFile
->Append(Exec_BeginBusyCursor
, _T("Show &busy cursor\tCtrl-C"));
446 menuFile
->Append(Exec_EndBusyCursor
, _T("Show &normal cursor\tShift-Ctrl-C"));
447 menuFile
->AppendSeparator();
448 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
450 wxMenu
*execMenu
= new wxMenu
;
451 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
452 _T("Launch a program and return when it terminates"));
453 execMenu
->Append(Exec_SyncNoEventsExec
, _T("Sync execution and &block...\tCtrl-B"),
454 _T("Launch a program and block until it terminates"));
455 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
456 _T("Launch a program and return immediately"));
457 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
458 _T("Launch a shell and execute a command in it"));
459 execMenu
->AppendSeparator();
460 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
461 _T("Launch a program and capture its output"));
462 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command..."),
463 _T("Pipe a string through a filter"));
464 execMenu
->Append(Exec_POpen
, _T("&Open a pipe to a command...\tCtrl-P"),
465 _T("Open a pipe to and from another program"));
467 execMenu
->AppendSeparator();
468 execMenu
->Append(Exec_OpenFile
, _T("Open &file...\tCtrl-F"),
469 _T("Launch the command to open this kind of files"));
470 execMenu
->Append(Exec_OpenURL
, _T("Open &URL...\tCtrl-U"),
471 _T("Launch the default browser with the given URL"));
473 execMenu
->AppendSeparator();
474 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
475 execMenu
->Append(Exec_DDERequest
, _T("Send DDE &request...\tCtrl-R"));
478 wxMenu
*helpMenu
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
479 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
481 // now append the freshly created menu to the menu bar...
482 wxMenuBar
*menuBar
= new wxMenuBar();
483 menuBar
->Append(menuFile
, _T("&File"));
484 menuBar
->Append(execMenu
, _T("&Exec"));
485 menuBar
->Append(helpMenu
, _T("&Help"));
487 // ... and attach this menu bar to the frame
490 // create the listbox in which we will show misc messages as they come
491 m_lbox
= new wxListBox(this, wxID_ANY
);
492 wxFont
font(12, wxFONTFAMILY_TELETYPE
, wxFONTSTYLE_NORMAL
,
493 wxFONTWEIGHT_NORMAL
);
495 m_lbox
->SetFont(font
);
498 // create a status bar just for fun (by default with 1 pane only)
500 SetStatusText(_T("Welcome to wxWidgets exec sample!"));
501 #endif // wxUSE_STATUSBAR
504 // ----------------------------------------------------------------------------
505 // event handlers: file and help menu
506 // ----------------------------------------------------------------------------
508 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
510 // true is to force the frame to close
514 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
519 void MyFrame::OnBeginBusyCursor(wxCommandEvent
& WXUNUSED(event
))
524 void MyFrame::OnEndBusyCursor(wxCommandEvent
& WXUNUSED(event
))
529 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
531 wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"),
532 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
535 void MyFrame::OnKill(wxCommandEvent
& WXUNUSED(event
))
537 long pid
= wxGetNumberFromUser(_T("Please specify the process to kill"),
541 // we need the full unsigned int range
550 static const wxString signalNames
[] =
552 _T("Just test (SIGNONE)"),
553 _T("Hangup (SIGHUP)"),
554 _T("Interrupt (SIGINT)"),
555 _T("Quit (SIGQUIT)"),
556 _T("Illegal instruction (SIGILL)"),
557 _T("Trap (SIGTRAP)"),
558 _T("Abort (SIGABRT)"),
559 _T("Emulated trap (SIGEMT)"),
560 _T("FP exception (SIGFPE)"),
561 _T("Kill (SIGKILL)"),
563 _T("Segment violation (SIGSEGV)"),
564 _T("System (SIGSYS)"),
565 _T("Broken pipe (SIGPIPE)"),
566 _T("Alarm (SIGALRM)"),
567 _T("Terminate (SIGTERM)"),
570 int sig
= wxGetSingleChoiceIndex(_T("How to kill the process?"),
572 WXSIZEOF(signalNames
), signalNames
,
577 wxFAIL_MSG( _T("unexpected return value") );
605 if ( wxProcess::Exists(pid
) )
606 wxLogStatus(_T("Process %ld is running."), pid
);
608 wxLogStatus(_T("No process with pid = %ld."), pid
);
612 wxKillError rc
= wxProcess::Kill(pid
, (wxSignal
)sig
);
613 if ( rc
== wxKILL_OK
)
615 wxLogStatus(_T("Process %ld killed with signal %d."), pid
, sig
);
619 static const wxChar
*errorText
[] =
622 _T("signal not supported"),
623 _T("permission denied"),
624 _T("no such process"),
625 _T("unspecified error"),
628 wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
629 pid
, sig
, errorText
[rc
]);
634 // ----------------------------------------------------------------------------
635 // event handlers: exec menu
636 // ----------------------------------------------------------------------------
638 void MyFrame::DoAsyncExec(const wxString
& cmd
)
640 wxProcess
*process
= new MyProcess(this, cmd
);
641 m_pidLast
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
644 wxLogError( _T("Execution of '%s' failed."), cmd
.c_str() );
650 wxLogStatus( _T("Process %ld (%s) launched."),
651 m_pidLast
, cmd
.c_str() );
657 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
659 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
666 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
668 int code
= wxExecute(cmd
, wxEXEC_SYNC
);
670 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
676 void MyFrame::OnSyncNoEventsExec(wxCommandEvent
& WXUNUSED(event
))
678 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
685 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
687 int code
= wxExecute(cmd
, wxEXEC_BLOCK
);
689 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
695 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
697 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
707 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
709 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
716 int code
= wxShell(cmd
);
717 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
722 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
724 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
732 switch ( wxMessageBox(_T("Execute it synchronously?"),
734 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
750 wxArrayString output
, errors
;
751 int code
= wxExecute(cmd
, output
, errors
);
752 wxLogStatus(_T("command '%s' terminated with exit code %d."),
757 ShowOutput(cmd
, output
, _T("Output"));
758 ShowOutput(cmd
, errors
, _T("Errors"));
763 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
764 if ( !wxExecute(cmd
, wxEXEC_ASYNC
, process
) )
766 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
772 AddAsyncProcess(process
);
779 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
782 m_cmdLast
= _T("tr [a-z] [A-Z]");
784 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
791 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
796 // always execute the filter asynchronously
797 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
798 long pid
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
801 wxLogStatus( _T("Process %ld (%s) launched."), pid
, cmd
.c_str() );
803 AddAsyncProcess(process
);
807 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
815 void MyFrame::OnPOpen(wxCommandEvent
& WXUNUSED(event
))
817 wxString cmd
= wxGetTextFromUser(_T("Enter the command to launch: "),
823 wxProcess
*process
= wxProcess::Open(cmd
);
826 wxLogError(_T("Failed to launch the command."));
830 wxLogVerbose(_T("PID of the new process: %ld"), process
->GetPid());
832 wxOutputStream
*out
= process
->GetOutputStream();
835 wxLogError(_T("Failed to connect to child stdin"));
839 wxInputStream
*in
= process
->GetInputStream();
842 wxLogError(_T("Failed to connect to child stdout"));
846 new MyPipeFrame(this, cmd
, process
);
849 void MyFrame::OnFileExec(wxCommandEvent
& WXUNUSED(event
))
851 static wxString s_filename
;
856 filename
= wxLoadFileSelector(_T("any file"), wxEmptyString
, s_filename
, this);
857 #else // !wxUSE_FILEDLG
858 filename
= wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
860 #endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
862 if ( filename
.empty() )
865 s_filename
= filename
;
867 wxString ext
= filename
.AfterFirst(_T('.'));
868 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
871 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
877 bool ok
= ft
->GetOpenCommand(&cmd
,
878 wxFileType::MessageParameters(filename
));
882 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
890 void MyFrame::OnOpenURL(wxCommandEvent
& WXUNUSED(event
))
892 static wxString
s_filename(_T("http://www.wxwidgets.org/"));
894 wxString filename
= wxGetTextFromUser
902 if ( filename
.empty() )
905 s_filename
= filename
;
907 if ( !wxLaunchDefaultBrowser(s_filename
) )
908 wxLogError(_T("Failed to open URL \"%s\""), s_filename
.c_str());
911 // ----------------------------------------------------------------------------
913 // ----------------------------------------------------------------------------
917 bool MyFrame::GetDDEServer()
919 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
920 DIALOG_TITLE
, m_server
);
926 wxString topic
= wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE
, m_topic
);
932 wxString cmd
= wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE
, m_cmdDde
);
941 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
943 if ( !GetDDEServer() )
947 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
950 wxLogError(_T("Failed to connect to the DDE server '%s'."),
955 if ( !conn
->Execute(m_cmdDde
) )
957 wxLogError(_T("Failed to execute command '%s' via DDE."),
962 wxLogStatus(_T("Successfully executed DDE command"));
967 void MyFrame::OnDDERequest(wxCommandEvent
& WXUNUSED(event
))
969 if ( !GetDDEServer() )
973 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
976 wxLogError(_T("Failed to connect to the DDE server '%s'."),
981 if ( !conn
->Request(m_cmdDde
) )
983 wxLogError(_T("Failed to send request '%s' via DDE."),
988 wxLogStatus(_T("Successfully sent DDE request."));
993 #endif // __WINDOWS__
995 // ----------------------------------------------------------------------------
997 // ----------------------------------------------------------------------------
1000 void MyFrame::OnIdle(wxIdleEvent
& event
)
1002 size_t count
= m_running
.GetCount();
1003 for ( size_t n
= 0; n
< count
; n
++ )
1005 if ( m_running
[n
]->HasInput() )
1007 event
.RequestMore();
1012 void MyFrame::OnTimer(wxTimerEvent
& WXUNUSED(event
))
1017 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
1019 RemoveAsyncProcess(process
);
1023 void MyFrame::ShowOutput(const wxString
& cmd
,
1024 const wxArrayString
& output
,
1025 const wxString
& title
)
1027 size_t count
= output
.GetCount();
1031 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
1032 title
.c_str(), cmd
.c_str()));
1034 for ( size_t n
= 0; n
< count
; n
++ )
1036 m_lbox
->Append(output
[n
]);
1039 m_lbox
->Append(wxString::Format(_T("--- End of %s ---"),
1040 title
.Lower().c_str()));
1043 // ----------------------------------------------------------------------------
1045 // ----------------------------------------------------------------------------
1047 void MyProcess::OnTerminate(int pid
, int status
)
1049 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
1050 pid
, m_cmd
.c_str(), status
);
1052 // we're not needed any more
1056 // ----------------------------------------------------------------------------
1058 // ----------------------------------------------------------------------------
1060 bool MyPipedProcess::HasInput()
1062 bool hasInput
= false;
1064 if ( IsInputAvailable() )
1066 wxTextInputStream
tis(*GetInputStream());
1068 // this assumes that the output is always line buffered
1070 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
1072 m_parent
->GetLogListBox()->Append(msg
);
1077 if ( IsErrorAvailable() )
1079 wxTextInputStream
tis(*GetErrorStream());
1081 // this assumes that the output is always line buffered
1083 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
1085 m_parent
->GetLogListBox()->Append(msg
);
1093 void MyPipedProcess::OnTerminate(int pid
, int status
)
1095 // show the rest of the output
1096 while ( HasInput() )
1099 m_parent
->OnProcessTerminated(this);
1101 MyProcess::OnTerminate(pid
, status
);
1104 // ----------------------------------------------------------------------------
1106 // ----------------------------------------------------------------------------
1108 bool MyPipedProcess2::HasInput()
1110 if ( !m_input
.empty() )
1112 wxTextOutputStream
os(*GetOutputStream());
1113 os
.WriteString(m_input
);
1118 // call us once again - may be we'll have output
1122 return MyPipedProcess::HasInput();
1125 // ============================================================================
1126 // MyPipeFrame implementation
1127 // ============================================================================
1129 MyPipeFrame::MyPipeFrame(wxFrame
*parent
,
1130 const wxString
& cmd
,
1132 : wxFrame(parent
, wxID_ANY
, cmd
),
1134 // in a real program we'd check that the streams are !NULL here
1135 m_out(*process
->GetOutputStream()),
1136 m_in(*process
->GetInputStream()),
1137 m_err(*process
->GetErrorStream())
1139 m_process
->SetNextHandler(this);
1141 wxPanel
*panel
= new wxPanel(this, wxID_ANY
);
1143 m_textOut
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1144 wxDefaultPosition
, wxDefaultSize
,
1145 wxTE_PROCESS_ENTER
);
1146 m_textIn
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1147 wxDefaultPosition
, wxDefaultSize
,
1148 wxTE_MULTILINE
| wxTE_RICH
);
1149 m_textIn
->SetEditable(false);
1150 m_textErr
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1151 wxDefaultPosition
, wxDefaultSize
,
1152 wxTE_MULTILINE
| wxTE_RICH
);
1153 m_textErr
->SetEditable(false);
1155 wxSizer
*sizerTop
= new wxBoxSizer(wxVERTICAL
);
1156 sizerTop
->Add(m_textOut
, 0, wxGROW
| wxALL
, 5);
1158 wxSizer
*sizerBtns
= new wxBoxSizer(wxHORIZONTAL
);
1160 Add(new wxButton(panel
, Exec_Btn_Send
, _T("&Send")), 0, wxALL
, 5);
1162 Add(new wxButton(panel
, Exec_Btn_SendFile
, _T("&File...")), 0, wxALL
, 5);
1164 Add(new wxButton(panel
, Exec_Btn_Get
, _T("&Get")), 0, wxALL
, 5);
1166 Add(new wxButton(panel
, Exec_Btn_Close
, _T("&Close")), 0, wxALL
, 5);
1168 sizerTop
->Add(sizerBtns
, 0, wxCENTRE
| wxALL
, 5);
1169 sizerTop
->Add(m_textIn
, 1, wxGROW
| wxALL
, 5);
1170 sizerTop
->Add(m_textErr
, 1, wxGROW
| wxALL
, 5);
1172 panel
->SetSizer(sizerTop
);
1173 sizerTop
->Fit(this);
1178 void MyPipeFrame::OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
))
1181 wxFileDialog
filedlg(this, _T("Select file to send"));
1182 if ( filedlg
.ShowModal() != wxID_OK
)
1185 wxFFile
file(filedlg
.GetFilename(), _T("r"));
1187 if ( !file
.IsOpened() || !file
.ReadAll(&data
) )
1190 // can't write the entire string at once, this risk overflowing the pipe
1191 // and we would dead lock
1192 size_t len
= data
.length();
1193 const wxChar
*pc
= data
.c_str();
1196 const size_t CHUNK_SIZE
= 4096;
1197 m_out
.Write(pc
, len
> CHUNK_SIZE
? CHUNK_SIZE
: len
);
1199 // note that not all data could have been written as we don't block on
1200 // the write end of the pipe
1201 const size_t lenChunk
= m_out
.LastWrite();
1208 #endif // wxUSE_FILEDLG
1211 void MyPipeFrame::DoGet()
1213 // we don't have any way to be notified when any input appears on the
1214 // stream so we have to poll it :-(
1215 DoGetFromStream(m_textIn
, m_in
);
1216 DoGetFromStream(m_textErr
, m_err
);
1219 void MyPipeFrame::DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
)
1221 while ( in
.CanRead() )
1223 wxChar buffer
[4096];
1224 buffer
[in
.Read(buffer
, WXSIZEOF(buffer
) - 1).LastRead()] = _T('\0');
1226 text
->AppendText(buffer
);
1230 void MyPipeFrame::DoClose()
1232 m_process
->CloseOutput();
1237 void MyPipeFrame::DisableInput()
1239 m_textOut
->SetEditable(false);
1240 FindWindow(Exec_Btn_Send
)->Disable();
1241 FindWindow(Exec_Btn_SendFile
)->Disable();
1242 FindWindow(Exec_Btn_Close
)->Disable();
1245 void MyPipeFrame::DisableOutput()
1247 FindWindow(Exec_Btn_Get
)->Disable();
1250 void MyPipeFrame::OnClose(wxCloseEvent
& event
)
1254 // we're not interested in getting the process termination notification
1255 // if we are closing it ourselves
1256 wxProcess
*process
= m_process
;
1258 process
->SetNextHandler(NULL
);
1260 process
->CloseOutput();
1266 void MyPipeFrame::OnProcessTerm(wxProcessEvent
& WXUNUSED(event
))
1273 wxLogWarning(_T("The other process has terminated, closing"));