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"
56 #include "wx/stopwatch.h"
58 #include "wx/process.h"
60 #include "wx/mimetype.h"
66 // ----------------------------------------------------------------------------
67 // the usual application and main frame classes
68 // ----------------------------------------------------------------------------
70 // Define a new application type, each program should derive a class from wxApp
71 class MyApp
: public wxApp
74 // override base class virtuals
75 // ----------------------------
77 // this one is called on application startup and is a good place for the app
78 // initialization (doing it here and not in the ctor allows to have an error
79 // return: if OnInit() returns false, the application terminates)
80 virtual bool OnInit();
83 // Define an array of process pointers used by MyFrame
85 WX_DEFINE_ARRAY_PTR(MyPipedProcess
*, MyPipedProcessesArray
);
88 WX_DEFINE_ARRAY_PTR(MyProcess
*, 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
);
98 // event handlers (these functions should _not_ be virtual)
99 void OnQuit(wxCommandEvent
& event
);
101 void OnKill(wxCommandEvent
& event
);
103 void OnClear(wxCommandEvent
& event
);
105 void OnBeginBusyCursor(wxCommandEvent
& event
);
106 void OnEndBusyCursor(wxCommandEvent
& event
);
108 void OnSyncExec(wxCommandEvent
& event
);
109 void OnSyncNoEventsExec(wxCommandEvent
& event
);
110 void OnAsyncExec(wxCommandEvent
& event
);
111 void OnShell(wxCommandEvent
& event
);
112 void OnExecWithRedirect(wxCommandEvent
& event
);
113 void OnExecWithPipe(wxCommandEvent
& event
);
115 void OnPOpen(wxCommandEvent
& event
);
117 void OnFileExec(wxCommandEvent
& event
);
118 void OnFileLaunch(wxCommandEvent
& event
);
119 void OnOpenURL(wxCommandEvent
& event
);
121 void OnAbout(wxCommandEvent
& event
);
123 // polling output of async processes
124 void OnTimer(wxTimerEvent
& event
);
125 void OnIdle(wxIdleEvent
& event
);
127 // for MyPipedProcess
128 void OnProcessTerminated(MyPipedProcess
*process
);
129 wxListBox
*GetLogListBox() const { return m_lbox
; }
132 void OnAsyncTermination(MyProcess
*process
);
135 void ShowOutput(const wxString
& cmd
,
136 const wxArrayString
& output
,
137 const wxString
& title
);
139 void DoAsyncExec(const wxString
& cmd
);
141 void AddAsyncProcess(MyProcess
*process
) { m_allAsync
.push_back(process
); }
143 void AddPipedProcess(MyPipedProcess
*process
);
144 void RemovePipedProcess(MyPipedProcess
*process
);
147 // the PID of the last process we launched asynchronously
150 // last command we executed
154 void OnDDEExec(wxCommandEvent
& event
);
155 void OnDDERequest(wxCommandEvent
& event
);
159 // last params of a DDE transaction
163 #endif // __WINDOWS__
167 // array of running processes with redirected IO
168 MyPipedProcessesArray m_running
;
170 // array of all asynchrously running processes
171 MyProcessesArray m_allAsync
;
173 // the idle event wake up timer
174 wxTimer m_timerIdleWakeUp
;
176 // any class wishing to process wxWidgets events must use this macro
177 DECLARE_EVENT_TABLE()
180 // ----------------------------------------------------------------------------
181 // MyPipeFrame: allows the user to communicate with the child process
182 // ----------------------------------------------------------------------------
184 class MyPipeFrame
: public wxFrame
187 MyPipeFrame(wxFrame
*parent
,
192 void OnTextEnter(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
193 void OnBtnSend(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
194 void OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
));
195 void OnBtnGet(wxCommandEvent
& WXUNUSED(event
)) { DoGet(); }
196 void OnBtnClose(wxCommandEvent
& WXUNUSED(event
)) { DoClose(); }
198 void OnClose(wxCloseEvent
& event
);
200 void OnProcessTerm(wxProcessEvent
& event
);
204 wxString
s(m_textOut
->GetValue());
206 m_out
.Write(s
.c_str(), s
.length());
216 void DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
);
218 void DisableOutput();
221 wxProcess
*m_process
;
223 wxOutputStream
&m_out
;
227 wxTextCtrl
*m_textOut
,
231 DECLARE_EVENT_TABLE()
234 // ----------------------------------------------------------------------------
235 // wxProcess-derived classes
236 // ----------------------------------------------------------------------------
238 // This is the handler for process termination events
239 class MyProcess
: public wxProcess
242 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
243 : wxProcess(parent
), m_cmd(cmd
)
248 // instead of overriding this virtual function we might as well process the
249 // event from it in the frame class - this might be more convenient in some
251 virtual void OnTerminate(int pid
, int status
);
258 // A specialization of MyProcess for redirecting the output
259 class MyPipedProcess
: public MyProcess
262 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
263 : MyProcess(parent
, cmd
)
268 virtual void OnTerminate(int pid
, int status
);
270 virtual bool HasInput();
273 // A version of MyPipedProcess which also sends input to the stdin of the
275 class MyPipedProcess2
: public MyPipedProcess
278 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
279 : MyPipedProcess(parent
, cmd
), m_input(input
)
283 virtual bool HasInput();
289 // ----------------------------------------------------------------------------
291 // ----------------------------------------------------------------------------
293 // IDs for the controls and the menu commands
300 Exec_BeginBusyCursor
,
303 Exec_SyncNoEventsExec
,
317 Exec_Btn_Send
= 1000,
323 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
325 // ----------------------------------------------------------------------------
326 // event tables and other macros for wxWidgets
327 // ----------------------------------------------------------------------------
329 // the event tables connect the wxWidgets events with the functions (event
330 // handlers) which process them. It can be also done at run-time, but for the
331 // simple menu events like this the static method is much simpler.
332 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
333 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
334 EVT_MENU(Exec_Kill
, MyFrame::OnKill
)
335 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
336 EVT_MENU(Exec_BeginBusyCursor
, MyFrame::OnBeginBusyCursor
)
337 EVT_MENU(Exec_EndBusyCursor
, MyFrame::OnEndBusyCursor
)
339 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
340 EVT_MENU(Exec_SyncNoEventsExec
, MyFrame::OnSyncNoEventsExec
)
341 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
342 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
343 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
344 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
346 EVT_MENU(Exec_POpen
, MyFrame::OnPOpen
)
348 EVT_MENU(Exec_OpenFile
, MyFrame::OnFileExec
)
349 EVT_MENU(Exec_LaunchFile
, MyFrame::OnFileLaunch
)
350 EVT_MENU(Exec_OpenURL
, MyFrame::OnOpenURL
)
353 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
354 EVT_MENU(Exec_DDERequest
, MyFrame::OnDDERequest
)
355 #endif // __WINDOWS__
357 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
359 EVT_IDLE(MyFrame::OnIdle
)
361 EVT_TIMER(wxID_ANY
, MyFrame::OnTimer
)
364 BEGIN_EVENT_TABLE(MyPipeFrame
, wxFrame
)
365 EVT_BUTTON(Exec_Btn_Send
, MyPipeFrame::OnBtnSend
)
366 EVT_BUTTON(Exec_Btn_SendFile
, MyPipeFrame::OnBtnSendFile
)
367 EVT_BUTTON(Exec_Btn_Get
, MyPipeFrame::OnBtnGet
)
368 EVT_BUTTON(Exec_Btn_Close
, MyPipeFrame::OnBtnClose
)
370 EVT_TEXT_ENTER(wxID_ANY
, MyPipeFrame::OnTextEnter
)
372 EVT_CLOSE(MyPipeFrame::OnClose
)
374 EVT_END_PROCESS(wxID_ANY
, MyPipeFrame::OnProcessTerm
)
377 // Create a new application object: this macro will allow wxWidgets to create
378 // the application object during program execution (it's better than using a
379 // static object for many reasons) and also declares the accessor function
380 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
384 // ============================================================================
386 // ============================================================================
388 // ----------------------------------------------------------------------------
389 // the application class
390 // ----------------------------------------------------------------------------
392 // `Main program' equivalent: the program execution "starts" here
395 if ( !wxApp::OnInit() )
398 // Create the main application window
399 MyFrame
*frame
= new MyFrame(_T("Exec wxWidgets sample"),
400 wxDefaultPosition
, wxSize(500, 140));
402 // Show it and tell the application that it's our main window
406 // success: wxApp::OnRun() will be called which will enter the main message
407 // loop and the application will run. If we returned false here, the
408 // application would exit immediately.
412 // ----------------------------------------------------------------------------
414 // ----------------------------------------------------------------------------
417 #pragma warning(disable: 4355) // this used in base member initializer list
421 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
422 : wxFrame((wxFrame
*)NULL
, wxID_ANY
, title
, pos
, size
),
423 m_timerIdleWakeUp(this)
428 // we need this in order to allow the about menu relocation, since ABOUT is
429 // not the default id of the about menu
430 wxApp::s_macAboutMenuItemId
= Exec_About
;
434 wxMenu
*menuFile
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
435 menuFile
->Append(Exec_Kill
, _T("&Kill process...\tCtrl-K"),
436 _T("Kill a process by PID"));
437 menuFile
->AppendSeparator();
438 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-L"),
439 _T("Clear the log window"));
440 menuFile
->AppendSeparator();
441 menuFile
->Append(Exec_BeginBusyCursor
, _T("Show &busy cursor\tCtrl-C"));
442 menuFile
->Append(Exec_EndBusyCursor
, _T("Show &normal cursor\tShift-Ctrl-C"));
443 menuFile
->AppendSeparator();
444 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
446 wxMenu
*execMenu
= new wxMenu
;
447 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
448 _T("Launch a program and return when it terminates"));
449 execMenu
->Append(Exec_SyncNoEventsExec
, _T("Sync execution and &block...\tCtrl-B"),
450 _T("Launch a program and block until it terminates"));
451 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
452 _T("Launch a program and return immediately"));
453 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
454 _T("Launch a shell and execute a command in it"));
455 execMenu
->AppendSeparator();
456 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
457 _T("Launch a program and capture its output"));
458 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command..."),
459 _T("Pipe a string through a filter"));
460 execMenu
->Append(Exec_POpen
, _T("&Open a pipe to a command...\tCtrl-P"),
461 _T("Open a pipe to and from another program"));
463 execMenu
->AppendSeparator();
464 execMenu
->Append(Exec_OpenFile
, _T("Open &file...\tCtrl-F"),
465 _T("Launch the command to open this kind of files"));
466 execMenu
->Append(Exec_LaunchFile
, _T("La&unch file...\tShift-Ctrl-F"),
467 _T("Launch the default application associated with the file"));
468 execMenu
->Append(Exec_OpenURL
, _T("Open &URL...\tCtrl-U"),
469 _T("Launch the default browser with the given URL"));
471 execMenu
->AppendSeparator();
472 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
473 execMenu
->Append(Exec_DDERequest
, _T("Send DDE &request...\tCtrl-R"));
476 wxMenu
*helpMenu
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
477 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
479 // now append the freshly created menu to the menu bar...
480 wxMenuBar
*menuBar
= new wxMenuBar();
481 menuBar
->Append(menuFile
, _T("&File"));
482 menuBar
->Append(execMenu
, _T("&Exec"));
483 menuBar
->Append(helpMenu
, _T("&Help"));
485 // ... and attach this menu bar to the frame
488 // create the listbox in which we will show misc messages as they come
489 m_lbox
= new wxListBox(this, wxID_ANY
);
490 wxFont
font(12, wxFONTFAMILY_TELETYPE
, wxFONTSTYLE_NORMAL
,
491 wxFONTWEIGHT_NORMAL
);
493 m_lbox
->SetFont(font
);
496 // create a status bar just for fun (by default with 1 pane only)
498 SetStatusText(_T("Welcome to wxWidgets exec sample!"));
499 #endif // wxUSE_STATUSBAR
504 // any processes left until now must be deleted manually: normally this is
505 // done when the associated process terminates but it must be still running
506 // if this didn't happen until now
507 for ( size_t n
= 0; n
< m_allAsync
.size(); n
++ )
509 delete m_allAsync
[n
];
513 // ----------------------------------------------------------------------------
514 // event handlers: file and help menu
515 // ----------------------------------------------------------------------------
517 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
519 // true is to force the frame to close
523 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
528 void MyFrame::OnBeginBusyCursor(wxCommandEvent
& WXUNUSED(event
))
533 void MyFrame::OnEndBusyCursor(wxCommandEvent
& WXUNUSED(event
))
538 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
540 wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"),
541 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
544 void MyFrame::OnKill(wxCommandEvent
& WXUNUSED(event
))
546 long pid
= wxGetNumberFromUser(_T("Please specify the process to kill"),
550 // we need the full unsigned int range
559 static const wxString signalNames
[] =
561 _T("Just test (SIGNONE)"),
562 _T("Hangup (SIGHUP)"),
563 _T("Interrupt (SIGINT)"),
564 _T("Quit (SIGQUIT)"),
565 _T("Illegal instruction (SIGILL)"),
566 _T("Trap (SIGTRAP)"),
567 _T("Abort (SIGABRT)"),
568 _T("Emulated trap (SIGEMT)"),
569 _T("FP exception (SIGFPE)"),
570 _T("Kill (SIGKILL)"),
572 _T("Segment violation (SIGSEGV)"),
573 _T("System (SIGSYS)"),
574 _T("Broken pipe (SIGPIPE)"),
575 _T("Alarm (SIGALRM)"),
576 _T("Terminate (SIGTERM)"),
579 int sig
= wxGetSingleChoiceIndex(_T("How to kill the process?"),
581 WXSIZEOF(signalNames
), signalNames
,
586 wxFAIL_MSG( _T("unexpected return value") );
614 if ( wxProcess::Exists(pid
) )
615 wxLogStatus(_T("Process %ld is running."), pid
);
617 wxLogStatus(_T("No process with pid = %ld."), pid
);
621 wxKillError rc
= wxProcess::Kill(pid
, (wxSignal
)sig
);
622 if ( rc
== wxKILL_OK
)
624 wxLogStatus(_T("Process %ld killed with signal %d."), pid
, sig
);
628 static const wxChar
*errorText
[] =
631 _T("signal not supported"),
632 _T("permission denied"),
633 _T("no such process"),
634 _T("unspecified error"),
637 wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
638 pid
, sig
, errorText
[rc
]);
643 // ----------------------------------------------------------------------------
644 // event handlers: exec menu
645 // ----------------------------------------------------------------------------
647 void MyFrame::DoAsyncExec(const wxString
& cmd
)
649 MyProcess
* const process
= new MyProcess(this, cmd
);
650 m_pidLast
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
653 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
659 wxLogStatus(_T("Process %ld (%s) launched."), m_pidLast
, cmd
.c_str());
663 // the parent frame keeps track of all async processes as it needs to
664 // free them if we exit before the child process terminates
665 AddAsyncProcess(process
);
669 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
671 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
678 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
680 int code
= wxExecute(cmd
, wxEXEC_SYNC
);
682 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
688 void MyFrame::OnSyncNoEventsExec(wxCommandEvent
& WXUNUSED(event
))
690 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
697 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
699 int code
= wxExecute(cmd
, wxEXEC_BLOCK
);
701 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
707 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
709 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
719 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
721 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
728 int code
= wxShell(cmd
);
729 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
734 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
739 m_cmdLast
= "type Makefile.in";
741 m_cmdLast
= "cat -n Makefile";
745 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
753 switch ( wxMessageBox(_T("Execute it synchronously?"),
755 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
771 wxLogStatus("\"%s\" is running please wait...", cmd
);
775 wxArrayString output
, errors
;
776 int code
= wxExecute(cmd
, output
, errors
);
778 wxLogStatus("Command \"%s\" terminated after %ldms; exit code %d.",
779 cmd
, sw
.Time(), code
);
783 ShowOutput(cmd
, output
, _T("Output"));
784 ShowOutput(cmd
, errors
, _T("Errors"));
789 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
790 if ( !wxExecute(cmd
, wxEXEC_ASYNC
, process
) )
792 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
798 AddPipedProcess(process
);
805 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
808 m_cmdLast
= _T("tr [a-z] [A-Z]");
810 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
817 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
822 // always execute the filter asynchronously
823 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
824 long pid
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
827 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
829 AddPipedProcess(process
);
833 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
841 void MyFrame::OnPOpen(wxCommandEvent
& WXUNUSED(event
))
843 wxString cmd
= wxGetTextFromUser(_T("Enter the command to launch: "),
849 wxProcess
*process
= wxProcess::Open(cmd
);
852 wxLogError(_T("Failed to launch the command."));
856 wxLogVerbose(_T("PID of the new process: %ld"), process
->GetPid());
858 wxOutputStream
*out
= process
->GetOutputStream();
861 wxLogError(_T("Failed to connect to child stdin"));
865 wxInputStream
*in
= process
->GetInputStream();
868 wxLogError(_T("Failed to connect to child stdout"));
872 new MyPipeFrame(this, cmd
, process
);
875 static wxString gs_lastFile
;
877 static bool AskUserForFileName()
882 filename
= wxLoadFileSelector(_T("any"), wxEmptyString
, gs_lastFile
);
883 #else // !wxUSE_FILEDLG
884 filename
= wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
886 #endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
888 if ( filename
.empty() )
891 gs_lastFile
= filename
;
896 void MyFrame::OnFileExec(wxCommandEvent
& WXUNUSED(event
))
898 if ( !AskUserForFileName() )
901 wxString ext
= gs_lastFile
.AfterLast(_T('.'));
902 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
905 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
911 bool ok
= ft
->GetOpenCommand(&cmd
,
912 wxFileType::MessageParameters(gs_lastFile
));
916 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
924 void MyFrame::OnFileLaunch(wxCommandEvent
& WXUNUSED(event
))
926 if ( !AskUserForFileName() )
929 if ( !wxLaunchDefaultApplication(gs_lastFile
) )
931 wxLogError("Opening \"%s\" in default application failed.", gs_lastFile
);
935 void MyFrame::OnOpenURL(wxCommandEvent
& WXUNUSED(event
))
937 static wxString
s_url(_T("http://www.wxwidgets.org/"));
939 wxString filename
= wxGetTextFromUser
947 if ( filename
.empty() )
952 if ( !wxLaunchDefaultBrowser(s_url
) )
953 wxLogError(_T("Failed to open URL \"%s\""), s_url
.c_str());
956 // ----------------------------------------------------------------------------
958 // ----------------------------------------------------------------------------
962 bool MyFrame::GetDDEServer()
964 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
965 DIALOG_TITLE
, m_server
);
971 wxString topic
= wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE
, m_topic
);
977 wxString cmd
= wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE
, m_cmdDde
);
986 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
988 if ( !GetDDEServer() )
992 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
995 wxLogError(_T("Failed to connect to the DDE server '%s'."),
1000 if ( !conn
->Execute(m_cmdDde
) )
1002 wxLogError(_T("Failed to execute command '%s' via DDE."),
1007 wxLogStatus(_T("Successfully executed DDE command"));
1012 void MyFrame::OnDDERequest(wxCommandEvent
& WXUNUSED(event
))
1014 if ( !GetDDEServer() )
1018 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
1021 wxLogError(_T("Failed to connect to the DDE server '%s'."),
1026 if ( !conn
->Request(m_cmdDde
) )
1028 wxLogError(_T("Failed to send request '%s' via DDE."),
1033 wxLogStatus(_T("Successfully sent DDE request."));
1038 #endif // __WINDOWS__
1040 // ----------------------------------------------------------------------------
1042 // ----------------------------------------------------------------------------
1045 void MyFrame::OnIdle(wxIdleEvent
& event
)
1047 size_t count
= m_running
.GetCount();
1048 for ( size_t n
= 0; n
< count
; n
++ )
1050 if ( m_running
[n
]->HasInput() )
1052 event
.RequestMore();
1057 void MyFrame::OnTimer(wxTimerEvent
& WXUNUSED(event
))
1062 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
1064 RemovePipedProcess(process
);
1067 void MyFrame::OnAsyncTermination(MyProcess
*process
)
1069 m_allAsync
.Remove(process
);
1074 void MyFrame::AddPipedProcess(MyPipedProcess
*process
)
1076 if ( m_running
.IsEmpty() )
1078 // we want to start getting the timer events to ensure that a
1079 // steady stream of idle events comes in -- otherwise we
1080 // wouldn't be able to poll the child process input
1081 m_timerIdleWakeUp
.Start(100);
1083 //else: the timer is already running
1085 m_running
.Add(process
);
1086 m_allAsync
.Add(process
);
1089 void MyFrame::RemovePipedProcess(MyPipedProcess
*process
)
1091 m_running
.Remove(process
);
1093 if ( m_running
.IsEmpty() )
1095 // we don't need to get idle events all the time any more
1096 m_timerIdleWakeUp
.Stop();
1100 void MyFrame::ShowOutput(const wxString
& cmd
,
1101 const wxArrayString
& output
,
1102 const wxString
& title
)
1104 size_t count
= output
.GetCount();
1108 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
1109 title
.c_str(), cmd
.c_str()));
1111 for ( size_t n
= 0; n
< count
; n
++ )
1113 m_lbox
->Append(output
[n
]);
1116 m_lbox
->Append(wxString::Format(_T("--- End of %s ---"),
1117 title
.Lower().c_str()));
1120 // ----------------------------------------------------------------------------
1122 // ----------------------------------------------------------------------------
1124 void MyProcess::OnTerminate(int pid
, int status
)
1126 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
1127 pid
, m_cmd
.c_str(), status
);
1129 m_parent
->OnAsyncTermination(this);
1132 // ----------------------------------------------------------------------------
1134 // ----------------------------------------------------------------------------
1136 bool MyPipedProcess::HasInput()
1138 bool hasInput
= false;
1140 if ( IsInputAvailable() )
1142 wxTextInputStream
tis(*GetInputStream());
1144 // this assumes that the output is always line buffered
1146 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
1148 m_parent
->GetLogListBox()->Append(msg
);
1153 if ( IsErrorAvailable() )
1155 wxTextInputStream
tis(*GetErrorStream());
1157 // this assumes that the output is always line buffered
1159 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
1161 m_parent
->GetLogListBox()->Append(msg
);
1169 void MyPipedProcess::OnTerminate(int pid
, int status
)
1171 // show the rest of the output
1172 while ( HasInput() )
1175 m_parent
->OnProcessTerminated(this);
1177 MyProcess::OnTerminate(pid
, status
);
1180 // ----------------------------------------------------------------------------
1182 // ----------------------------------------------------------------------------
1184 bool MyPipedProcess2::HasInput()
1186 if ( !m_input
.empty() )
1188 wxTextOutputStream
os(*GetOutputStream());
1189 os
.WriteString(m_input
);
1194 // call us once again - may be we'll have output
1198 return MyPipedProcess::HasInput();
1201 // ============================================================================
1202 // MyPipeFrame implementation
1203 // ============================================================================
1205 MyPipeFrame::MyPipeFrame(wxFrame
*parent
,
1206 const wxString
& cmd
,
1208 : wxFrame(parent
, wxID_ANY
, cmd
),
1210 // in a real program we'd check that the streams are !NULL here
1211 m_out(*process
->GetOutputStream()),
1212 m_in(*process
->GetInputStream()),
1213 m_err(*process
->GetErrorStream())
1215 m_process
->SetNextHandler(this);
1217 wxPanel
*panel
= new wxPanel(this, wxID_ANY
);
1219 m_textOut
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1220 wxDefaultPosition
, wxDefaultSize
,
1221 wxTE_PROCESS_ENTER
);
1222 m_textIn
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1223 wxDefaultPosition
, wxDefaultSize
,
1224 wxTE_MULTILINE
| wxTE_RICH
);
1225 m_textIn
->SetEditable(false);
1226 m_textErr
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1227 wxDefaultPosition
, wxDefaultSize
,
1228 wxTE_MULTILINE
| wxTE_RICH
);
1229 m_textErr
->SetEditable(false);
1231 wxSizer
*sizerTop
= new wxBoxSizer(wxVERTICAL
);
1232 sizerTop
->Add(m_textOut
, 0, wxGROW
| wxALL
, 5);
1234 wxSizer
*sizerBtns
= new wxBoxSizer(wxHORIZONTAL
);
1236 Add(new wxButton(panel
, Exec_Btn_Send
, _T("&Send")), 0, wxALL
, 5);
1238 Add(new wxButton(panel
, Exec_Btn_SendFile
, _T("&File...")), 0, wxALL
, 5);
1240 Add(new wxButton(panel
, Exec_Btn_Get
, _T("&Get")), 0, wxALL
, 5);
1242 Add(new wxButton(panel
, Exec_Btn_Close
, _T("&Close")), 0, wxALL
, 5);
1244 sizerTop
->Add(sizerBtns
, 0, wxCENTRE
| wxALL
, 5);
1245 sizerTop
->Add(m_textIn
, 1, wxGROW
| wxALL
, 5);
1246 sizerTop
->Add(m_textErr
, 1, wxGROW
| wxALL
, 5);
1248 panel
->SetSizer(sizerTop
);
1249 sizerTop
->Fit(this);
1254 void MyPipeFrame::OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
))
1257 wxFileDialog
filedlg(this, _T("Select file to send"));
1258 if ( filedlg
.ShowModal() != wxID_OK
)
1261 wxFFile
file(filedlg
.GetFilename(), _T("r"));
1263 if ( !file
.IsOpened() || !file
.ReadAll(&data
) )
1266 // can't write the entire string at once, this risk overflowing the pipe
1267 // and we would dead lock
1268 size_t len
= data
.length();
1269 const wxChar
*pc
= data
.c_str();
1272 const size_t CHUNK_SIZE
= 4096;
1273 m_out
.Write(pc
, len
> CHUNK_SIZE
? CHUNK_SIZE
: len
);
1275 // note that not all data could have been written as we don't block on
1276 // the write end of the pipe
1277 const size_t lenChunk
= m_out
.LastWrite();
1284 #endif // wxUSE_FILEDLG
1287 void MyPipeFrame::DoGet()
1289 // we don't have any way to be notified when any input appears on the
1290 // stream so we have to poll it :-(
1291 DoGetFromStream(m_textIn
, m_in
);
1292 DoGetFromStream(m_textErr
, m_err
);
1295 void MyPipeFrame::DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
)
1297 while ( in
.CanRead() )
1299 wxChar buffer
[4096];
1300 buffer
[in
.Read(buffer
, WXSIZEOF(buffer
) - 1).LastRead()] = _T('\0');
1302 text
->AppendText(buffer
);
1306 void MyPipeFrame::DoClose()
1308 m_process
->CloseOutput();
1313 void MyPipeFrame::DisableInput()
1315 m_textOut
->SetEditable(false);
1316 FindWindow(Exec_Btn_Send
)->Disable();
1317 FindWindow(Exec_Btn_SendFile
)->Disable();
1318 FindWindow(Exec_Btn_Close
)->Disable();
1321 void MyPipeFrame::DisableOutput()
1323 FindWindow(Exec_Btn_Get
)->Disable();
1326 void MyPipeFrame::OnClose(wxCloseEvent
& event
)
1330 // we're not interested in getting the process termination notification
1331 // if we are closing it ourselves
1332 wxProcess
*process
= m_process
;
1334 process
->SetNextHandler(NULL
);
1336 process
->CloseOutput();
1342 void MyPipeFrame::OnProcessTerm(wxProcessEvent
& WXUNUSED(event
))
1349 wxLogWarning(_T("The other process has terminated, closing"));