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 OnIdleTimer(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
);
134 // timer updating a counter in the background
135 void OnBgTimer(wxTimerEvent
& event
);
138 void ShowOutput(const wxString
& cmd
,
139 const wxArrayString
& output
,
140 const wxString
& title
);
142 void DoAsyncExec(const wxString
& cmd
);
144 void AddAsyncProcess(MyProcess
*process
) { m_allAsync
.push_back(process
); }
146 void AddPipedProcess(MyPipedProcess
*process
);
147 void RemovePipedProcess(MyPipedProcess
*process
);
150 // the PID of the last process we launched asynchronously
153 // last command we executed
157 void OnDDEExec(wxCommandEvent
& event
);
158 void OnDDERequest(wxCommandEvent
& event
);
162 // last params of a DDE transaction
166 #endif // __WINDOWS__
170 // array of running processes with redirected IO
171 MyPipedProcessesArray m_running
;
173 // array of all asynchrously running processes
174 MyProcessesArray m_allAsync
;
176 // the idle event wake up timer
177 wxTimer m_timerIdleWakeUp
;
179 // a background timer allowing to easily check visually whether the
180 // messages are processed or not
183 // any class wishing to process wxWidgets events must use this macro
184 DECLARE_EVENT_TABLE()
187 // ----------------------------------------------------------------------------
188 // MyPipeFrame: allows the user to communicate with the child process
189 // ----------------------------------------------------------------------------
191 class MyPipeFrame
: public wxFrame
194 MyPipeFrame(wxFrame
*parent
,
199 void OnTextEnter(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
200 void OnBtnSend(wxCommandEvent
& WXUNUSED(event
)) { DoSend(); }
201 void OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
));
202 void OnBtnGet(wxCommandEvent
& WXUNUSED(event
)) { DoGet(); }
203 void OnBtnClose(wxCommandEvent
& WXUNUSED(event
)) { DoClose(); }
205 void OnClose(wxCloseEvent
& event
);
207 void OnProcessTerm(wxProcessEvent
& event
);
211 wxString
s(m_textOut
->GetValue());
213 m_out
.Write(s
.c_str(), s
.length());
223 void DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
);
225 void DisableOutput();
228 wxProcess
*m_process
;
230 wxOutputStream
&m_out
;
234 wxTextCtrl
*m_textOut
,
238 DECLARE_EVENT_TABLE()
241 // ----------------------------------------------------------------------------
242 // wxProcess-derived classes
243 // ----------------------------------------------------------------------------
245 // This is the handler for process termination events
246 class MyProcess
: public wxProcess
249 MyProcess(MyFrame
*parent
, const wxString
& cmd
)
250 : wxProcess(parent
), m_cmd(cmd
)
255 // instead of overriding this virtual function we might as well process the
256 // event from it in the frame class - this might be more convenient in some
258 virtual void OnTerminate(int pid
, int status
);
265 // A specialization of MyProcess for redirecting the output
266 class MyPipedProcess
: public MyProcess
269 MyPipedProcess(MyFrame
*parent
, const wxString
& cmd
)
270 : MyProcess(parent
, cmd
)
275 virtual void OnTerminate(int pid
, int status
);
277 virtual bool HasInput();
280 // A version of MyPipedProcess which also sends input to the stdin of the
282 class MyPipedProcess2
: public MyPipedProcess
285 MyPipedProcess2(MyFrame
*parent
, const wxString
& cmd
, const wxString
& input
)
286 : MyPipedProcess(parent
, cmd
), m_input(input
)
290 virtual bool HasInput();
296 // ----------------------------------------------------------------------------
298 // ----------------------------------------------------------------------------
300 // IDs for the controls and the menu commands
311 Exec_BeginBusyCursor
,
314 Exec_SyncNoEventsExec
,
325 Exec_About
= wxID_ABOUT
,
328 Exec_Btn_Send
= 1000,
334 static const wxChar
*DIALOG_TITLE
= _T("Exec sample");
336 // ----------------------------------------------------------------------------
337 // event tables and other macros for wxWidgets
338 // ----------------------------------------------------------------------------
340 // the event tables connect the wxWidgets events with the functions (event
341 // handlers) which process them. It can be also done at run-time, but for the
342 // simple menu events like this the static method is much simpler.
343 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
344 EVT_MENU(Exec_Quit
, MyFrame::OnQuit
)
345 EVT_MENU(Exec_Kill
, MyFrame::OnKill
)
346 EVT_MENU(Exec_ClearLog
, MyFrame::OnClear
)
347 EVT_MENU(Exec_BeginBusyCursor
, MyFrame::OnBeginBusyCursor
)
348 EVT_MENU(Exec_EndBusyCursor
, MyFrame::OnEndBusyCursor
)
350 EVT_MENU(Exec_SyncExec
, MyFrame::OnSyncExec
)
351 EVT_MENU(Exec_SyncNoEventsExec
, MyFrame::OnSyncNoEventsExec
)
352 EVT_MENU(Exec_AsyncExec
, MyFrame::OnAsyncExec
)
353 EVT_MENU(Exec_Shell
, MyFrame::OnShell
)
354 EVT_MENU(Exec_Redirect
, MyFrame::OnExecWithRedirect
)
355 EVT_MENU(Exec_Pipe
, MyFrame::OnExecWithPipe
)
357 EVT_MENU(Exec_POpen
, MyFrame::OnPOpen
)
359 EVT_MENU(Exec_OpenFile
, MyFrame::OnFileExec
)
360 EVT_MENU(Exec_LaunchFile
, MyFrame::OnFileLaunch
)
361 EVT_MENU(Exec_OpenURL
, MyFrame::OnOpenURL
)
364 EVT_MENU(Exec_DDEExec
, MyFrame::OnDDEExec
)
365 EVT_MENU(Exec_DDERequest
, MyFrame::OnDDERequest
)
366 #endif // __WINDOWS__
368 EVT_MENU(Exec_About
, MyFrame::OnAbout
)
370 EVT_IDLE(MyFrame::OnIdle
)
372 EVT_TIMER(Exec_TimerIdle
, MyFrame::OnIdleTimer
)
373 EVT_TIMER(Exec_TimerBg
, MyFrame::OnBgTimer
)
376 BEGIN_EVENT_TABLE(MyPipeFrame
, wxFrame
)
377 EVT_BUTTON(Exec_Btn_Send
, MyPipeFrame::OnBtnSend
)
378 EVT_BUTTON(Exec_Btn_SendFile
, MyPipeFrame::OnBtnSendFile
)
379 EVT_BUTTON(Exec_Btn_Get
, MyPipeFrame::OnBtnGet
)
380 EVT_BUTTON(Exec_Btn_Close
, MyPipeFrame::OnBtnClose
)
382 EVT_TEXT_ENTER(wxID_ANY
, MyPipeFrame::OnTextEnter
)
384 EVT_CLOSE(MyPipeFrame::OnClose
)
386 EVT_END_PROCESS(wxID_ANY
, MyPipeFrame::OnProcessTerm
)
389 // Create a new application object: this macro will allow wxWidgets to create
390 // the application object during program execution (it's better than using a
391 // static object for many reasons) and also declares the accessor function
392 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
396 // ============================================================================
398 // ============================================================================
400 // ----------------------------------------------------------------------------
401 // the application class
402 // ----------------------------------------------------------------------------
404 // `Main program' equivalent: the program execution "starts" here
407 if ( !wxApp::OnInit() )
410 // Create the main application window
411 MyFrame
*frame
= new MyFrame(_T("Exec wxWidgets sample"),
412 wxDefaultPosition
, wxSize(500, 140));
414 // Show it and tell the application that it's our main window
418 // success: wxApp::OnRun() will be called which will enter the main message
419 // loop and the application will run. If we returned false here, the
420 // application would exit immediately.
424 // ----------------------------------------------------------------------------
426 // ----------------------------------------------------------------------------
429 #pragma warning(disable: 4355) // this used in base member initializer list
433 MyFrame::MyFrame(const wxString
& title
, const wxPoint
& pos
, const wxSize
& size
)
434 : wxFrame((wxFrame
*)NULL
, wxID_ANY
, title
, pos
, size
),
435 m_timerIdleWakeUp(this, Exec_TimerIdle
),
436 m_timerBg(this, Exec_TimerBg
)
441 // we need this in order to allow the about menu relocation, since ABOUT is
442 // not the default id of the about menu
443 wxApp::s_macAboutMenuItemId
= Exec_About
;
447 wxMenu
*menuFile
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
448 menuFile
->Append(Exec_Kill
, _T("&Kill process...\tCtrl-K"),
449 _T("Kill a process by PID"));
450 menuFile
->AppendSeparator();
451 menuFile
->Append(Exec_ClearLog
, _T("&Clear log\tCtrl-L"),
452 _T("Clear the log window"));
453 menuFile
->AppendSeparator();
454 menuFile
->Append(Exec_BeginBusyCursor
, _T("Show &busy cursor\tCtrl-C"));
455 menuFile
->Append(Exec_EndBusyCursor
, _T("Show &normal cursor\tShift-Ctrl-C"));
456 menuFile
->AppendSeparator();
457 menuFile
->Append(Exec_Quit
, _T("E&xit\tAlt-X"), _T("Quit this program"));
459 wxMenu
*execMenu
= new wxMenu
;
460 execMenu
->Append(Exec_SyncExec
, _T("Sync &execution...\tCtrl-E"),
461 _T("Launch a program and return when it terminates"));
462 execMenu
->Append(Exec_SyncNoEventsExec
, _T("Sync execution and &block...\tCtrl-B"),
463 _T("Launch a program and block until it terminates"));
464 execMenu
->Append(Exec_AsyncExec
, _T("&Async execution...\tCtrl-A"),
465 _T("Launch a program and return immediately"));
466 execMenu
->Append(Exec_Shell
, _T("Execute &shell command...\tCtrl-S"),
467 _T("Launch a shell and execute a command in it"));
468 execMenu
->AppendSeparator();
469 execMenu
->Append(Exec_Redirect
, _T("Capture command &output...\tCtrl-O"),
470 _T("Launch a program and capture its output"));
471 execMenu
->Append(Exec_Pipe
, _T("&Pipe through command..."),
472 _T("Pipe a string through a filter"));
473 execMenu
->Append(Exec_POpen
, _T("&Open a pipe to a command...\tCtrl-P"),
474 _T("Open a pipe to and from another program"));
476 execMenu
->AppendSeparator();
477 execMenu
->Append(Exec_OpenFile
, _T("Open &file...\tCtrl-F"),
478 _T("Launch the command to open this kind of files"));
479 execMenu
->Append(Exec_LaunchFile
, _T("La&unch file...\tShift-Ctrl-F"),
480 _T("Launch the default application associated with the file"));
481 execMenu
->Append(Exec_OpenURL
, _T("Open &URL...\tCtrl-U"),
482 _T("Launch the default browser with the given URL"));
484 execMenu
->AppendSeparator();
485 execMenu
->Append(Exec_DDEExec
, _T("Execute command via &DDE...\tCtrl-D"));
486 execMenu
->Append(Exec_DDERequest
, _T("Send DDE &request...\tCtrl-R"));
489 wxMenu
*helpMenu
= new wxMenu(wxEmptyString
, wxMENU_TEAROFF
);
490 helpMenu
->Append(Exec_About
, _T("&About...\tF1"), _T("Show about dialog"));
492 // now append the freshly created menu to the menu bar...
493 wxMenuBar
*menuBar
= new wxMenuBar();
494 menuBar
->Append(menuFile
, _T("&File"));
495 menuBar
->Append(execMenu
, _T("&Exec"));
496 menuBar
->Append(helpMenu
, _T("&Help"));
498 // ... and attach this menu bar to the frame
501 // create the listbox in which we will show misc messages as they come
502 m_lbox
= new wxListBox(this, wxID_ANY
);
503 wxFont
font(12, wxFONTFAMILY_TELETYPE
, wxFONTSTYLE_NORMAL
,
504 wxFONTWEIGHT_NORMAL
);
506 m_lbox
->SetFont(font
);
509 // create a status bar just for fun (by default with 1 pane only)
511 SetStatusText(_T("Welcome to wxWidgets exec sample!"));
512 #endif // wxUSE_STATUSBAR
514 m_timerBg
.Start(1000);
519 // any processes left until now must be deleted manually: normally this is
520 // done when the associated process terminates but it must be still running
521 // if this didn't happen until now
522 for ( size_t n
= 0; n
< m_allAsync
.size(); n
++ )
524 delete m_allAsync
[n
];
528 // ----------------------------------------------------------------------------
529 // event handlers: file and help menu
530 // ----------------------------------------------------------------------------
532 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
534 // true is to force the frame to close
538 void MyFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
543 void MyFrame::OnBeginBusyCursor(wxCommandEvent
& WXUNUSED(event
))
548 void MyFrame::OnEndBusyCursor(wxCommandEvent
& WXUNUSED(event
))
553 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
555 wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"),
556 _T("About Exec"), wxOK
| wxICON_INFORMATION
, this);
559 void MyFrame::OnKill(wxCommandEvent
& WXUNUSED(event
))
561 long pid
= wxGetNumberFromUser(_T("Please specify the process to kill"),
565 // we need the full unsigned int range
574 static const wxString signalNames
[] =
576 _T("Just test (SIGNONE)"),
577 _T("Hangup (SIGHUP)"),
578 _T("Interrupt (SIGINT)"),
579 _T("Quit (SIGQUIT)"),
580 _T("Illegal instruction (SIGILL)"),
581 _T("Trap (SIGTRAP)"),
582 _T("Abort (SIGABRT)"),
583 _T("Emulated trap (SIGEMT)"),
584 _T("FP exception (SIGFPE)"),
585 _T("Kill (SIGKILL)"),
587 _T("Segment violation (SIGSEGV)"),
588 _T("System (SIGSYS)"),
589 _T("Broken pipe (SIGPIPE)"),
590 _T("Alarm (SIGALRM)"),
591 _T("Terminate (SIGTERM)"),
594 int sig
= wxGetSingleChoiceIndex(_T("How to kill the process?"),
596 WXSIZEOF(signalNames
), signalNames
,
601 wxFAIL_MSG( _T("unexpected return value") );
629 if ( wxProcess::Exists(pid
) )
630 wxLogStatus(_T("Process %ld is running."), pid
);
632 wxLogStatus(_T("No process with pid = %ld."), pid
);
636 wxKillError rc
= wxProcess::Kill(pid
, (wxSignal
)sig
);
637 if ( rc
== wxKILL_OK
)
639 wxLogStatus(_T("Process %ld killed with signal %d."), pid
, sig
);
643 static const wxChar
*errorText
[] =
646 _T("signal not supported"),
647 _T("permission denied"),
648 _T("no such process"),
649 _T("unspecified error"),
652 wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"),
653 pid
, sig
, errorText
[rc
]);
658 // ----------------------------------------------------------------------------
659 // event handlers: exec menu
660 // ----------------------------------------------------------------------------
662 void MyFrame::DoAsyncExec(const wxString
& cmd
)
664 MyProcess
* const process
= new MyProcess(this, cmd
);
665 m_pidLast
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
668 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
674 wxLogStatus(_T("Process %ld (%s) launched."), m_pidLast
, cmd
.c_str());
678 // the parent frame keeps track of all async processes as it needs to
679 // free them if we exit before the child process terminates
680 AddAsyncProcess(process
);
684 void MyFrame::OnSyncExec(wxCommandEvent
& WXUNUSED(event
))
686 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
693 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
695 int code
= wxExecute(cmd
, wxEXEC_SYNC
);
697 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
703 void MyFrame::OnSyncNoEventsExec(wxCommandEvent
& WXUNUSED(event
))
705 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
712 wxLogStatus( _T("'%s' is running please wait..."), cmd
.c_str() );
714 int code
= wxExecute(cmd
, wxEXEC_BLOCK
);
716 wxLogStatus(_T("Process '%s' terminated with exit code %d."),
722 void MyFrame::OnAsyncExec(wxCommandEvent
& WXUNUSED(event
))
724 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
734 void MyFrame::OnShell(wxCommandEvent
& WXUNUSED(event
))
736 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
743 int code
= wxShell(cmd
);
744 wxLogStatus(_T("Shell command '%s' terminated with exit code %d."),
749 void MyFrame::OnExecWithRedirect(wxCommandEvent
& WXUNUSED(event
))
754 m_cmdLast
= "type Makefile.in";
756 m_cmdLast
= "cat -n Makefile";
760 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
768 switch ( wxMessageBox(_T("Execute it synchronously?"),
770 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
, this) )
786 wxLogStatus("\"%s\" is running please wait...", cmd
);
790 wxArrayString output
, errors
;
791 int code
= wxExecute(cmd
, output
, errors
);
793 wxLogStatus("Command \"%s\" terminated after %ldms; exit code %d.",
794 cmd
, sw
.Time(), code
);
798 ShowOutput(cmd
, output
, _T("Output"));
799 ShowOutput(cmd
, errors
, _T("Errors"));
804 MyPipedProcess
*process
= new MyPipedProcess(this, cmd
);
805 if ( !wxExecute(cmd
, wxEXEC_ASYNC
, process
) )
807 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
813 AddPipedProcess(process
);
820 void MyFrame::OnExecWithPipe(wxCommandEvent
& WXUNUSED(event
))
823 m_cmdLast
= _T("tr [a-z] [A-Z]");
825 wxString cmd
= wxGetTextFromUser(_T("Enter the command: "),
832 wxString input
= wxGetTextFromUser(_T("Enter the string to send to it: "),
837 // always execute the filter asynchronously
838 MyPipedProcess2
*process
= new MyPipedProcess2(this, cmd
, input
);
839 long pid
= wxExecute(cmd
, wxEXEC_ASYNC
, process
);
842 wxLogStatus(_T("Process %ld (%s) launched."), pid
, cmd
.c_str());
844 AddPipedProcess(process
);
848 wxLogError(_T("Execution of '%s' failed."), cmd
.c_str());
856 void MyFrame::OnPOpen(wxCommandEvent
& WXUNUSED(event
))
858 wxString cmd
= wxGetTextFromUser(_T("Enter the command to launch: "),
864 wxProcess
*process
= wxProcess::Open(cmd
);
867 wxLogError(_T("Failed to launch the command."));
871 wxLogVerbose(_T("PID of the new process: %ld"), process
->GetPid());
873 wxOutputStream
*out
= process
->GetOutputStream();
876 wxLogError(_T("Failed to connect to child stdin"));
880 wxInputStream
*in
= process
->GetInputStream();
883 wxLogError(_T("Failed to connect to child stdout"));
887 new MyPipeFrame(this, cmd
, process
);
890 static wxString gs_lastFile
;
892 static bool AskUserForFileName()
897 filename
= wxLoadFileSelector(_T("any"), wxEmptyString
, gs_lastFile
);
898 #else // !wxUSE_FILEDLG
899 filename
= wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"),
901 #endif // wxUSE_FILEDLG/!wxUSE_FILEDLG
903 if ( filename
.empty() )
906 gs_lastFile
= filename
;
911 void MyFrame::OnFileExec(wxCommandEvent
& WXUNUSED(event
))
913 if ( !AskUserForFileName() )
916 wxString ext
= gs_lastFile
.AfterLast(_T('.'));
917 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
920 wxLogError(_T("Impossible to determine the file type for extension '%s'"),
926 bool ok
= ft
->GetOpenCommand(&cmd
,
927 wxFileType::MessageParameters(gs_lastFile
));
931 wxLogError(_T("Impossible to find out how to open files of extension '%s'"),
939 void MyFrame::OnFileLaunch(wxCommandEvent
& WXUNUSED(event
))
941 if ( !AskUserForFileName() )
944 if ( !wxLaunchDefaultApplication(gs_lastFile
) )
946 wxLogError("Opening \"%s\" in default application failed.", gs_lastFile
);
950 void MyFrame::OnOpenURL(wxCommandEvent
& WXUNUSED(event
))
952 static wxString
s_url(_T("http://www.wxwidgets.org/"));
954 wxString filename
= wxGetTextFromUser
962 if ( filename
.empty() )
967 if ( !wxLaunchDefaultBrowser(s_url
) )
968 wxLogError(_T("Failed to open URL \"%s\""), s_url
.c_str());
971 // ----------------------------------------------------------------------------
973 // ----------------------------------------------------------------------------
977 bool MyFrame::GetDDEServer()
979 wxString server
= wxGetTextFromUser(_T("Server to connect to:"),
980 DIALOG_TITLE
, m_server
);
986 wxString topic
= wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE
, m_topic
);
992 wxString cmd
= wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE
, m_cmdDde
);
1001 void MyFrame::OnDDEExec(wxCommandEvent
& WXUNUSED(event
))
1003 if ( !GetDDEServer() )
1007 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
1010 wxLogError(_T("Failed to connect to the DDE server '%s'."),
1015 if ( !conn
->Execute(m_cmdDde
) )
1017 wxLogError(_T("Failed to execute command '%s' via DDE."),
1022 wxLogStatus(_T("Successfully executed DDE command"));
1027 void MyFrame::OnDDERequest(wxCommandEvent
& WXUNUSED(event
))
1029 if ( !GetDDEServer() )
1033 wxConnectionBase
*conn
= client
.MakeConnection(wxEmptyString
, m_server
, m_topic
);
1036 wxLogError(_T("Failed to connect to the DDE server '%s'."),
1041 if ( !conn
->Request(m_cmdDde
) )
1043 wxLogError(_T("Failed to send request '%s' via DDE."),
1048 wxLogStatus(_T("Successfully sent DDE request."));
1053 #endif // __WINDOWS__
1055 // ----------------------------------------------------------------------------
1057 // ----------------------------------------------------------------------------
1060 void MyFrame::OnIdle(wxIdleEvent
& event
)
1062 size_t count
= m_running
.GetCount();
1063 for ( size_t n
= 0; n
< count
; n
++ )
1065 if ( m_running
[n
]->HasInput() )
1067 event
.RequestMore();
1072 void MyFrame::OnIdleTimer(wxTimerEvent
& WXUNUSED(event
))
1077 void MyFrame::OnBgTimer(wxTimerEvent
& WXUNUSED(event
))
1079 static unsigned long s_ticks
= 0;
1080 SetStatusText(wxString::Format("%lu ticks", s_ticks
++), 1);
1083 void MyFrame::OnProcessTerminated(MyPipedProcess
*process
)
1085 RemovePipedProcess(process
);
1088 void MyFrame::OnAsyncTermination(MyProcess
*process
)
1090 m_allAsync
.Remove(process
);
1095 void MyFrame::AddPipedProcess(MyPipedProcess
*process
)
1097 if ( m_running
.IsEmpty() )
1099 // we want to start getting the timer events to ensure that a
1100 // steady stream of idle events comes in -- otherwise we
1101 // wouldn't be able to poll the child process input
1102 m_timerIdleWakeUp
.Start(100);
1104 //else: the timer is already running
1106 m_running
.Add(process
);
1107 m_allAsync
.Add(process
);
1110 void MyFrame::RemovePipedProcess(MyPipedProcess
*process
)
1112 m_running
.Remove(process
);
1114 if ( m_running
.IsEmpty() )
1116 // we don't need to get idle events all the time any more
1117 m_timerIdleWakeUp
.Stop();
1121 void MyFrame::ShowOutput(const wxString
& cmd
,
1122 const wxArrayString
& output
,
1123 const wxString
& title
)
1125 size_t count
= output
.GetCount();
1129 m_lbox
->Append(wxString::Format(_T("--- %s of '%s' ---"),
1130 title
.c_str(), cmd
.c_str()));
1132 for ( size_t n
= 0; n
< count
; n
++ )
1134 m_lbox
->Append(output
[n
]);
1137 m_lbox
->Append(wxString::Format(_T("--- End of %s ---"),
1138 title
.Lower().c_str()));
1141 // ----------------------------------------------------------------------------
1143 // ----------------------------------------------------------------------------
1145 void MyProcess::OnTerminate(int pid
, int status
)
1147 wxLogStatus(m_parent
, _T("Process %u ('%s') terminated with exit code %d."),
1148 pid
, m_cmd
.c_str(), status
);
1150 m_parent
->OnAsyncTermination(this);
1153 // ----------------------------------------------------------------------------
1155 // ----------------------------------------------------------------------------
1157 bool MyPipedProcess::HasInput()
1159 bool hasInput
= false;
1161 if ( IsInputAvailable() )
1163 wxTextInputStream
tis(*GetInputStream());
1165 // this assumes that the output is always line buffered
1167 msg
<< m_cmd
<< _T(" (stdout): ") << tis
.ReadLine();
1169 m_parent
->GetLogListBox()->Append(msg
);
1174 if ( IsErrorAvailable() )
1176 wxTextInputStream
tis(*GetErrorStream());
1178 // this assumes that the output is always line buffered
1180 msg
<< m_cmd
<< _T(" (stderr): ") << tis
.ReadLine();
1182 m_parent
->GetLogListBox()->Append(msg
);
1190 void MyPipedProcess::OnTerminate(int pid
, int status
)
1192 // show the rest of the output
1193 while ( HasInput() )
1196 m_parent
->OnProcessTerminated(this);
1198 MyProcess::OnTerminate(pid
, status
);
1201 // ----------------------------------------------------------------------------
1203 // ----------------------------------------------------------------------------
1205 bool MyPipedProcess2::HasInput()
1207 if ( !m_input
.empty() )
1209 wxTextOutputStream
os(*GetOutputStream());
1210 os
.WriteString(m_input
);
1215 // call us once again - may be we'll have output
1219 return MyPipedProcess::HasInput();
1222 // ============================================================================
1223 // MyPipeFrame implementation
1224 // ============================================================================
1226 MyPipeFrame::MyPipeFrame(wxFrame
*parent
,
1227 const wxString
& cmd
,
1229 : wxFrame(parent
, wxID_ANY
, cmd
),
1231 // in a real program we'd check that the streams are !NULL here
1232 m_out(*process
->GetOutputStream()),
1233 m_in(*process
->GetInputStream()),
1234 m_err(*process
->GetErrorStream())
1236 m_process
->SetNextHandler(this);
1238 wxPanel
*panel
= new wxPanel(this, wxID_ANY
);
1240 m_textOut
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1241 wxDefaultPosition
, wxDefaultSize
,
1242 wxTE_PROCESS_ENTER
);
1243 m_textIn
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1244 wxDefaultPosition
, wxDefaultSize
,
1245 wxTE_MULTILINE
| wxTE_RICH
);
1246 m_textIn
->SetEditable(false);
1247 m_textErr
= new wxTextCtrl(panel
, wxID_ANY
, wxEmptyString
,
1248 wxDefaultPosition
, wxDefaultSize
,
1249 wxTE_MULTILINE
| wxTE_RICH
);
1250 m_textErr
->SetEditable(false);
1252 wxSizer
*sizerTop
= new wxBoxSizer(wxVERTICAL
);
1253 sizerTop
->Add(m_textOut
, 0, wxGROW
| wxALL
, 5);
1255 wxSizer
*sizerBtns
= new wxBoxSizer(wxHORIZONTAL
);
1257 Add(new wxButton(panel
, Exec_Btn_Send
, _T("&Send")), 0, wxALL
, 5);
1259 Add(new wxButton(panel
, Exec_Btn_SendFile
, _T("&File...")), 0, wxALL
, 5);
1261 Add(new wxButton(panel
, Exec_Btn_Get
, _T("&Get")), 0, wxALL
, 5);
1263 Add(new wxButton(panel
, Exec_Btn_Close
, _T("&Close")), 0, wxALL
, 5);
1265 sizerTop
->Add(sizerBtns
, 0, wxCENTRE
| wxALL
, 5);
1266 sizerTop
->Add(m_textIn
, 1, wxGROW
| wxALL
, 5);
1267 sizerTop
->Add(m_textErr
, 1, wxGROW
| wxALL
, 5);
1269 panel
->SetSizer(sizerTop
);
1270 sizerTop
->Fit(this);
1275 void MyPipeFrame::OnBtnSendFile(wxCommandEvent
& WXUNUSED(event
))
1278 wxFileDialog
filedlg(this, _T("Select file to send"));
1279 if ( filedlg
.ShowModal() != wxID_OK
)
1282 wxFFile
file(filedlg
.GetFilename(), _T("r"));
1284 if ( !file
.IsOpened() || !file
.ReadAll(&data
) )
1287 // can't write the entire string at once, this risk overflowing the pipe
1288 // and we would dead lock
1289 size_t len
= data
.length();
1290 const wxChar
*pc
= data
.c_str();
1293 const size_t CHUNK_SIZE
= 4096;
1294 m_out
.Write(pc
, len
> CHUNK_SIZE
? CHUNK_SIZE
: len
);
1296 // note that not all data could have been written as we don't block on
1297 // the write end of the pipe
1298 const size_t lenChunk
= m_out
.LastWrite();
1305 #endif // wxUSE_FILEDLG
1308 void MyPipeFrame::DoGet()
1310 // we don't have any way to be notified when any input appears on the
1311 // stream so we have to poll it :-(
1312 DoGetFromStream(m_textIn
, m_in
);
1313 DoGetFromStream(m_textErr
, m_err
);
1316 void MyPipeFrame::DoGetFromStream(wxTextCtrl
*text
, wxInputStream
& in
)
1318 while ( in
.CanRead() )
1320 wxChar buffer
[4096];
1321 buffer
[in
.Read(buffer
, WXSIZEOF(buffer
) - 1).LastRead()] = _T('\0');
1323 text
->AppendText(buffer
);
1327 void MyPipeFrame::DoClose()
1329 m_process
->CloseOutput();
1334 void MyPipeFrame::DisableInput()
1336 m_textOut
->SetEditable(false);
1337 FindWindow(Exec_Btn_Send
)->Disable();
1338 FindWindow(Exec_Btn_SendFile
)->Disable();
1339 FindWindow(Exec_Btn_Close
)->Disable();
1342 void MyPipeFrame::DisableOutput()
1344 FindWindow(Exec_Btn_Get
)->Disable();
1347 void MyPipeFrame::OnClose(wxCloseEvent
& event
)
1351 // we're not interested in getting the process termination notification
1352 // if we are closing it ourselves
1353 wxProcess
*process
= m_process
;
1355 process
->SetNextHandler(NULL
);
1357 process
->CloseOutput();
1363 void MyPipeFrame::OnProcessTerm(wxProcessEvent
& WXUNUSED(event
))
1370 wxLogWarning(_T("The other process has terminated, closing"));