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 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
752 wxArrayString output
, errors
;
753 int code
= wxExecute(cmd
, output
, errors
);
755 wxLogStatus(_T("Command '%s' terminated with exit code %d."),
760 ShowOutput(cmd
, output
, _T("Output"));
761 ShowOutput(cmd
, errors
, _T("Errors"));
766 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
767 if ( !wxExecute(cmd
, wxEXEC_ASYNC
, process
) )
769 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
775 AddAsyncProcess(process
);
782 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
785 m_cmdLast
= _T("tr [a-z] [A-Z]");
787 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
794 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
799 // always execute the filter asynchronously
800 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
801 long pid
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
804 wxLogStatus( _T("Process %ld (%s) launched."), pid
, cmd
.c_str() );
806 AddAsyncProcess(process
);
810 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
818 void MyFrame::OnPOpen(wxCommandEvent
& WXUNUSED(event
))
820 wxString cmd
= wxGetTextFromUser(_T("Enter the command to launch: "),
826 wxProcess
*process
= wxProcess::Open(cmd
);
829 wxLogError(_T("Failed to launch the command."));
833 wxLogVerbose(_T("PID of the new process: %ld"), process
->GetPid());
835 wxOutputStream
*out
= process
->GetOutputStream();
838 wxLogError(_T("Failed to connect to child stdin"));
842 wxInputStream
*in
= process
->GetInputStream();
845 wxLogError(_T("Failed to connect to child stdout"));
849 new MyPipeFrame(this, cmd
, process
);
852 void MyFrame::OnFileExec(wxCommandEvent
& WXUNUSED(event
))
854 static wxString s_filename
;
859 filename
= wxLoadFileSelector(_T("any file"), wxEmptyString
, s_filename
, this);
860 #else // !wxUSE_FILEDLG
861 filename
= wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
863 #endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
865 if ( filename
.empty() )
868 s_filename
= filename
;
870 wxString ext
= filename
.AfterFirst(_T('.'));
871 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
874 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
880 bool ok
= ft
->GetOpenCommand(&cmd
,
881 wxFileType::MessageParameters(filename
));
885 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
893 void MyFrame::OnOpenURL(wxCommandEvent
& WXUNUSED(event
))
895 static wxString
s_filename(_T("http://www.wxwidgets.org/"));
897 wxString filename
= wxGetTextFromUser
905 if ( filename
.empty() )
908 s_filename
= filename
;
910 if ( !wxLaunchDefaultBrowser(s_filename
) )
911 wxLogError(_T("Failed to open URL \"%s\""), s_filename
.c_str());
914 // ----------------------------------------------------------------------------
916 // ----------------------------------------------------------------------------
920 bool MyFrame::GetDDEServer()
922 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
923 DIALOG_TITLE
, m_server
);
929 wxString topic
= wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE
, m_topic
);
935 wxString cmd
= wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE
, m_cmdDde
);
944 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
946 if ( !GetDDEServer() )
950 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
953 wxLogError(_T("Failed to connect to the DDE server '%s'."),
958 if ( !conn
->Execute(m_cmdDde
) )
960 wxLogError(_T("Failed to execute command '%s' via DDE."),
965 wxLogStatus(_T("Successfully executed DDE command"));
970 void MyFrame::OnDDERequest(wxCommandEvent
& WXUNUSED(event
))
972 if ( !GetDDEServer() )
976 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
979 wxLogError(_T("Failed to connect to the DDE server '%s'."),
984 if ( !conn
->Request(m_cmdDde
) )
986 wxLogError(_T("Failed to send request '%s' via DDE."),
991 wxLogStatus(_T("Successfully sent DDE request."));
996 #endif // __WINDOWS__
998 // ----------------------------------------------------------------------------
1000 // ----------------------------------------------------------------------------
1003 void MyFrame::OnIdle(wxIdleEvent
& event
)
1005 size_t count
= m_running
.GetCount();
1006 for ( size_t n
= 0; n
< count
; n
++ )
1008 if ( m_running
[n
]->HasInput() )
1010 event
.RequestMore();
1015 void MyFrame::OnTimer(wxTimerEvent
& WXUNUSED(event
))
1020 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
1022 RemoveAsyncProcess(process
);
1026 void MyFrame::ShowOutput(const wxString
& cmd
,
1027 const wxArrayString
& output
,
1028 const wxString
& title
)
1030 size_t count
= output
.GetCount();
1034 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
1035 title
.c_str(), cmd
.c_str()));
1037 for ( size_t n
= 0; n
< count
; n
++ )
1039 m_lbox
->Append(output
[n
]);
1042 m_lbox
->Append(wxString::Format(_T("--- End of %s ---"),
1043 title
.Lower().c_str()));
1046 // ----------------------------------------------------------------------------
1048 // ----------------------------------------------------------------------------
1050 void MyProcess::OnTerminate(int pid
, int status
)
1052 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
1053 pid
, m_cmd
.c_str(), status
);
1055 // we're not needed any more
1059 // ----------------------------------------------------------------------------
1061 // ----------------------------------------------------------------------------
1063 bool MyPipedProcess::HasInput()
1065 bool hasInput
= false;
1067 if ( IsInputAvailable() )
1069 wxTextInputStream
tis(*GetInputStream());
1071 // this assumes that the output is always line buffered
1073 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
1075 m_parent
->GetLogListBox()->Append(msg
);
1080 if ( IsErrorAvailable() )
1082 wxTextInputStream
tis(*GetErrorStream());
1084 // this assumes that the output is always line buffered
1086 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
1088 m_parent
->GetLogListBox()->Append(msg
);
1096 void MyPipedProcess::OnTerminate(int pid
, int status
)
1098 // show the rest of the output
1099 while ( HasInput() )
1102 m_parent
->OnProcessTerminated(this);
1104 MyProcess::OnTerminate(pid
, status
);
1107 // ----------------------------------------------------------------------------
1109 // ----------------------------------------------------------------------------
1111 bool MyPipedProcess2::HasInput()
1113 if ( !m_input
.empty() )
1115 wxTextOutputStream
os(*GetOutputStream());
1116 os
.WriteString(m_input
);
1121 // call us once again - may be we'll have output
1125 return MyPipedProcess::HasInput();
1128 // ============================================================================
1129 // MyPipeFrame implementation
1130 // ============================================================================
1132 MyPipeFrame::MyPipeFrame(wxFrame
*parent
,
1133 const wxString
& cmd
,
1135 : wxFrame(parent
, wxID_ANY
, cmd
),
1137 // in a real program we'd check that the streams are !NULL here
1138 m_out(*process
->GetOutputStream()),
1139 m_in(*process
->GetInputStream()),
1140 m_err(*process
->GetErrorStream())
1142 m_process
->SetNextHandler(this);
1144 wxPanel
*panel
= new wxPanel(this, wxID_ANY
);
1146 m_textOut
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1147 wxDefaultPosition
, wxDefaultSize
,
1148 wxTE_PROCESS_ENTER
);
1149 m_textIn
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1150 wxDefaultPosition
, wxDefaultSize
,
1151 wxTE_MULTILINE
| wxTE_RICH
);
1152 m_textIn
->SetEditable(false);
1153 m_textErr
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1154 wxDefaultPosition
, wxDefaultSize
,
1155 wxTE_MULTILINE
| wxTE_RICH
);
1156 m_textErr
->SetEditable(false);
1158 wxSizer
*sizerTop
= new wxBoxSizer(wxVERTICAL
);
1159 sizerTop
->Add(m_textOut
, 0, wxGROW
| wxALL
, 5);
1161 wxSizer
*sizerBtns
= new wxBoxSizer(wxHORIZONTAL
);
1163 Add(new wxButton(panel
, Exec_Btn_Send
, _T("&Send")), 0, wxALL
, 5);
1165 Add(new wxButton(panel
, Exec_Btn_SendFile
, _T("&File...")), 0, wxALL
, 5);
1167 Add(new wxButton(panel
, Exec_Btn_Get
, _T("&Get")), 0, wxALL
, 5);
1169 Add(new wxButton(panel
, Exec_Btn_Close
, _T("&Close")), 0, wxALL
, 5);
1171 sizerTop
->Add(sizerBtns
, 0, wxCENTRE
| wxALL
, 5);
1172 sizerTop
->Add(m_textIn
, 1, wxGROW
| wxALL
, 5);
1173 sizerTop
->Add(m_textErr
, 1, wxGROW
| wxALL
, 5);
1175 panel
->SetSizer(sizerTop
);
1176 sizerTop
->Fit(this);
1181 void MyPipeFrame::OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
))
1184 wxFileDialog
filedlg(this, _T("Select file to send"));
1185 if ( filedlg
.ShowModal() != wxID_OK
)
1188 wxFFile
file(filedlg
.GetFilename(), _T("r"));
1190 if ( !file
.IsOpened() || !file
.ReadAll(&data
) )
1193 // can't write the entire string at once, this risk overflowing the pipe
1194 // and we would dead lock
1195 size_t len
= data
.length();
1196 const wxChar
*pc
= data
.c_str();
1199 const size_t CHUNK_SIZE
= 4096;
1200 m_out
.Write(pc
, len
> CHUNK_SIZE
? CHUNK_SIZE
: len
);
1202 // note that not all data could have been written as we don't block on
1203 // the write end of the pipe
1204 const size_t lenChunk
= m_out
.LastWrite();
1211 #endif // wxUSE_FILEDLG
1214 void MyPipeFrame::DoGet()
1216 // we don't have any way to be notified when any input appears on the
1217 // stream so we have to poll it :-(
1218 DoGetFromStream(m_textIn
, m_in
);
1219 DoGetFromStream(m_textErr
, m_err
);
1222 void MyPipeFrame::DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
)
1224 while ( in
.CanRead() )
1226 wxChar buffer
[4096];
1227 buffer
[in
.Read(buffer
, WXSIZEOF(buffer
) - 1).LastRead()] = _T('\0');
1229 text
->AppendText(buffer
);
1233 void MyPipeFrame::DoClose()
1235 m_process
->CloseOutput();
1240 void MyPipeFrame::DisableInput()
1242 m_textOut
->SetEditable(false);
1243 FindWindow(Exec_Btn_Send
)->Disable();
1244 FindWindow(Exec_Btn_SendFile
)->Disable();
1245 FindWindow(Exec_Btn_Close
)->Disable();
1248 void MyPipeFrame::DisableOutput()
1250 FindWindow(Exec_Btn_Get
)->Disable();
1253 void MyPipeFrame::OnClose(wxCloseEvent
& event
)
1257 // we're not interested in getting the process termination notification
1258 // if we are closing it ourselves
1259 wxProcess
*process
= m_process
;
1261 process
->SetNextHandler(NULL
);
1263 process
->CloseOutput();
1269 void MyPipeFrame::OnProcessTerm(wxProcessEvent
& WXUNUSED(event
))
1276 wxLogWarning(_T("The other process has terminated, closing"));